From 1aa932cf117fc6b4f7a880e105829570147e8e92 Mon Sep 17 00:00:00 2001 From: Yarin Levi <41652571+YarinQuapi@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:28:37 +0200 Subject: [PATCH 1/2] Let the iOS app build and run on Apple Silicon simulators libtesseract ships no arm64 simulator slice. SwiftyTesseract answers that by excluding arm64 from every simulator build, which leaves an Intel-only app that current iOS simulators refuse to install ("needs to be updated"). On Apple Silicon simulators only: - the Podfile drops that arm64 exclusion and leaves out the two SwiftyTesseract files that call into libtesseract; - the OCR plugin builds without libtesseract and answers a scan with an error. Label scanning therefore does not work in the simulator. Device builds are unchanged. Co-Authored-By: Claude Fable 5.2 --- apps/mobile/ios/Podfile | 17 +++++++++++++++++ apps/mobile/ios/Podfile.lock | 2 +- .../SwiftFlutterTesseractOcrPlugin.swift | 8 ++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/apps/mobile/ios/Podfile b/apps/mobile/ios/Podfile index 9d7ef08..00af103 100644 --- a/apps/mobile/ios/Podfile +++ b/apps/mobile/ios/Podfile @@ -39,5 +39,22 @@ end post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) + # libtesseract has no Apple Silicon simulator slice, so nothing that calls it + # can link there. Leave that code out on that one platform so the app still + # runs; label scanning reports itself unavailable (see the plugin's Swift file). + if target.name == 'SwiftyTesseract' + target.build_configurations.each do |config| + config.build_settings['EXCLUDED_SOURCE_FILE_NAMES[sdk=iphonesimulator*][arch=arm64]'] = 'SwiftyTesseract.swift SwiftyTesseractError.swift' + end + end + end + # SwiftyTesseract answers the missing slice by excluding arm64 from every + # simulator build, which leaves an Intel-only app that current simulators + # refuse to install. Drop that exclusion now that the code is left out instead. + support_files = File.join(installer.sandbox.root.to_s, 'Target Support Files') + Dir.glob(File.join(support_files, '{Pods-Runner*,SwiftyTesseract}', '*.xcconfig')).each do |path| + text = File.read(path) + kept = text.gsub(/^EXCLUDED_ARCHS\[sdk=iphonesimulator\*\] = arm64\n/, '') + File.write(path, kept) unless kept == text end end diff --git a/apps/mobile/ios/Podfile.lock b/apps/mobile/ios/Podfile.lock index 31a1ca0..49b7d3f 100644 --- a/apps/mobile/ios/Podfile.lock +++ b/apps/mobile/ios/Podfile.lock @@ -24,6 +24,6 @@ SPEC CHECKSUMS: flutter_tesseract_ocr: fffe5de044967e12d184feaded7fabfb546b6042 SwiftyTesseract: 1f3d96668ae92dc2208d9842c8a59bea9fad2cbb -PODFILE CHECKSUM: 3ba3a73b1b12adcf321a227a745625fe0888cc82 +PODFILE CHECKSUM: 91e106dbdd76557d0dc8a0078a8226d344da7b92 COCOAPODS: 1.17.0 diff --git a/apps/mobile/packages/flutter_tesseract_ocr/ios/Classes/SwiftFlutterTesseractOcrPlugin.swift b/apps/mobile/packages/flutter_tesseract_ocr/ios/Classes/SwiftFlutterTesseractOcrPlugin.swift index e858736..0ebd804 100644 --- a/apps/mobile/packages/flutter_tesseract_ocr/ios/Classes/SwiftFlutterTesseractOcrPlugin.swift +++ b/apps/mobile/packages/flutter_tesseract_ocr/ios/Classes/SwiftFlutterTesseractOcrPlugin.swift @@ -1,6 +1,10 @@ import Flutter import UIKit +// libtesseract has no Apple Silicon simulator slice; there the plugin builds +// without it and answers every scan with an error (see the Podfile). +#if !(targetEnvironment(simulator) && arch(arm64)) import libtesseract +#endif /// Drives libtesseract directly (instead of SwiftyTesseract's wrapper) so we /// can choose the page segmentation mode. Without a block mode Tesseract @@ -61,6 +65,9 @@ public class SwiftFlutterTesseractOcrPlugin: NSObject, FlutterPlugin { } private static func recognize(_ image: CGImage, tessdata: String, language: String, psm: Int) -> Outcome { + #if targetEnvironment(simulator) && arch(arm64) + return .failure("Text recognition is not available on this simulator") + #else let width = image.width let height = image.height // Hand Tesseract the colour pixels: its own thresholding reads @@ -93,5 +100,6 @@ public class SwiftFlutterTesseractOcrPlugin: NSObject, FlutterPlugin { guard let cString = TessBaseAPIGetUTF8Text(api) else { return .failure("No text returned") } defer { TessDeleteText(cString) } return .success(String(cString: cString)) + #endif } } From f3d6cfc4ae557392fbd305ee8b0cf5659dcc5f1d Mon Sep 17 00:00:00 2001 From: Yarin Levi <41652571+YarinQuapi@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:28:37 +0200 Subject: [PATCH 2/2] Add a weight goal with trend and estimated arrival date Users can set a target weight on the Weight screen (web and mobile) and see how they are doing against it: progress from where they started, weekly pace, a trend line and goal line on the chart, and the date the current pace reaches the goal. - API: new WeightGoal table (target, start weight, set date). GET /api/weights now also returns the goal and trend; PUT and DELETE /api/weights/goal set and remove it, behind the existing weights:create permission. - The pace is a least-squares line through the last 30 days of weigh-ins, so one odd reading does not swing the date. It widens to 90 days when those span under a week, and gives no estimate with less than a week of data, when moving away from the goal, or when the goal is more than three years out. - Moving the target further the same way keeps the progress made; a goal in the other direction restarts from the current weight. - Web and mobile: goal card with set, edit and remove; the chart gains a dotted goal line, a dashed trend line projected ahead, and a marker where the two meet. English and Hebrew. The mobile weigh-in list also used a hardcoded "kg"; it now uses the translated unit. Needs the 20261115120000_weight_goal migration. Co-Authored-By: Claude Fable 5.2 --- .../20261115120000_weight_goal/migration.sql | 13 + apps/api/prisma/schema.prisma | 12 + apps/api/src/domain.test.ts | 81 +++ apps/api/src/domain.ts | 90 +++ apps/api/src/routes/weights.ts | 101 +++- apps/api/src/schemas.ts | 4 + apps/mobile/lib/copy.dart | 80 +++ apps/mobile/lib/main.dart | 536 ++++++++++++++++-- apps/mobile/test/weight_goal_test.dart | 137 +++++ apps/web/src/App.tsx | 174 +++++- apps/web/src/api.ts | 17 + apps/web/src/clock.ts | 10 + apps/web/src/i18n.tsx | 38 ++ apps/web/src/styles.css | 17 + 14 files changed, 1226 insertions(+), 84 deletions(-) create mode 100644 apps/api/prisma/migrations/20261115120000_weight_goal/migration.sql create mode 100644 apps/mobile/test/weight_goal_test.dart diff --git a/apps/api/prisma/migrations/20261115120000_weight_goal/migration.sql b/apps/api/prisma/migrations/20261115120000_weight_goal/migration.sql new file mode 100644 index 0000000..9c3d0d4 --- /dev/null +++ b/apps/api/prisma/migrations/20261115120000_weight_goal/migration.sql @@ -0,0 +1,13 @@ +-- CreateTable +CREATE TABLE `WeightGoal` ( + `userId` VARCHAR(191) NOT NULL, + `targetKg` DECIMAL(6, 2) NOT NULL, + `startKg` DECIMAL(6, 2) NOT NULL, + `setAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updatedAt` DATETIME(3) NOT NULL, + + PRIMARY KEY (`userId`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `WeightGoal` ADD CONSTRAINT `WeightGoal_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index e24472b..ea15be7 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -80,6 +80,7 @@ model User { dailyGoals DailyGoal[] diaryEntries DiaryEntry[] weights WeightEntry[] + weightGoal WeightGoal? foods Food[] @relation("FoodOwner") verifiedFoods Food[] @relation("VerifiedBy") fastingSettings FastingSettings? @@ -191,6 +192,17 @@ model WeightEntry { @@index([userId, loggedAt]) } +// The weight the user is working towards. startKg is where they stood when +// the goal was set, so progress can be shown as a share of the way there. +model WeightGoal { + userId String @id + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + targetKg Decimal @db.Decimal(6, 2) + startKg Decimal @db.Decimal(6, 2) + setAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} + model HealthSettings { userId String @id user User @relation(fields: [userId], references: [id], onDelete: Cascade) diff --git a/apps/api/src/domain.test.ts b/apps/api/src/domain.test.ts index 38f2047..872aee7 100644 --- a/apps/api/src/domain.test.ts +++ b/apps/api/src/domain.test.ts @@ -21,6 +21,7 @@ import { validatePassword, weightChangeKg, weightForGoal, + weightTrend, } from "./domain.js"; import { DEFAULT_USER_PERMISSIONS, OPERATIONS, resolvePermissions } from "./rbac.js"; import { changePasswordSchema, fastingSchema, foodSchema, healthSettingsSchema, healthSyncSchema, profileSchema, signupSchema } from "./schemas.js"; @@ -522,3 +523,83 @@ test("Apple Health sync payloads are validated and default to empty lists", () = assert.equal(healthSettingsSchema.safeParse({ exerciseGoalMinutes: 30, stepGoal: 10000 }).success, true); assert.equal(healthSettingsSchema.safeParse({ exerciseGoalMinutes: 0, stepGoal: 10000 }).success, false); }); + +const trendNow = new Date("2026-11-15T10:00:00.000Z"); +function weighIn(daysAgo: number, weightKg: number) { + return { loggedAt: new Date(trendNow.getTime() - daysAgo * 86400000), weightKg }; +} + +test("weight trend fits recent weigh-ins and projects when the goal is reached", () => { + // Exactly 0.1 kg lost per day: 82 → 80 over 20 days, 5 kg left to 75. + const trend = weightTrend({ + weights: [weighIn(20, 82), weighIn(10, 81), weighIn(0, 80)], + targetKg: 75, + startKg: 82, + now: trendNow, + }); + assert.equal(trend.status, "on_track"); + assert.equal(trend.currentKg, 80); + assert.equal(trend.remainingKg, 5); + assert.equal(trend.ratePerWeekKg, -0.7); + assert.equal(trend.progress, 0.29); + assert.equal(Math.round((trend.etaAt!.getTime() - trendNow.getTime()) / 86400000), 50); + assert.equal(trend.line!.fromKg, 82); +}); + +test("weight trend ignores weigh-ins older than the recent window", () => { + // A big drop months ago must not speed up today's slow pace. + const trend = weightTrend({ + weights: [weighIn(200, 100), weighIn(28, 81.4), weighIn(14, 81.2), weighIn(0, 81)], + targetKg: 80, + startKg: 100, + now: trendNow, + }); + assert.equal(trend.ratePerWeekKg, -0.1); + assert.equal(Math.round((trend.etaAt!.getTime() - trendNow.getTime()) / 86400000), 70); +}); + +test("weight trend widens the window when the last month is too thin", () => { + const trend = weightTrend({ + weights: [weighIn(60, 84), weighIn(2, 81.1)], + targetKg: 78, + startKg: 84, + now: trendNow, + }); + assert.equal(trend.status, "on_track"); + assert.equal(trend.ratePerWeekKg, -0.35); +}); + +test("weight trend needs a week of weigh-ins before it estimates", () => { + const few = weightTrend({ weights: [weighIn(3, 81), weighIn(0, 80)], targetKg: 75, startKg: 81, now: trendNow }); + assert.equal(few.status, "need_data"); + assert.equal(few.etaAt, null); + assert.equal(few.line, null); + const none = weightTrend({ weights: [], targetKg: 75, startKg: 81, now: trendNow }); + assert.equal(none.status, "need_data"); + assert.equal(none.currentKg, 81); + assert.equal(none.progress, 0); +}); + +test("weight trend is off track when moving away from, or barely towards, the goal", () => { + const away = weightTrend({ weights: [weighIn(14, 80), weighIn(0, 81)], targetKg: 75, startKg: 80, now: trendNow }); + assert.equal(away.status, "off_track"); + assert.equal(away.ratePerWeekKg, 0.5); + assert.equal(away.etaAt, null); + assert.equal(away.progress, 0); + const flat = weightTrend({ weights: [weighIn(14, 80), weighIn(0, 80)], targetKg: 75, startKg: 80, now: trendNow }); + assert.equal(flat.status, "off_track"); + const crawl = weightTrend({ weights: [weighIn(28, 80.04), weighIn(0, 80)], targetKg: 70, startKg: 80.04, now: trendNow }); + assert.equal(crawl.status, "off_track"); +}); + +test("weight trend reports a reached goal in either direction", () => { + const lost = weightTrend({ weights: [weighIn(14, 76), weighIn(0, 74.8)], targetKg: 75, startKg: 80, now: trendNow }); + assert.equal(lost.status, "reached"); + assert.equal(lost.remainingKg, 0); + assert.equal(lost.progress, 1); + const gaining = weightTrend({ weights: [weighIn(14, 60), weighIn(0, 61)], targetKg: 65, startKg: 60, now: trendNow }); + assert.equal(gaining.status, "on_track"); + assert.equal(gaining.ratePerWeekKg, 0.5); + const gained = weightTrend({ weights: [weighIn(0, 65.2)], targetKg: 65, startKg: 60, now: trendNow }); + assert.equal(gained.status, "reached"); +}); diff --git a/apps/api/src/domain.ts b/apps/api/src/domain.ts index 0f5fe16..3ad24ed 100644 --- a/apps/api/src/domain.ts +++ b/apps/api/src/domain.ts @@ -352,6 +352,96 @@ export function weightChangeKg(input: { return round2(inWeek[0].weightKg - before[0].weightKg); } +export type WeightTrendStatus = "need_data" | "on_track" | "off_track" | "reached"; + +export type WeightTrend = { + status: WeightTrendStatus; + /** Latest weigh-in, or the goal's start weight when there is none. */ + currentKg: number; + /** Distance left to the target, never negative. */ + remainingKg: number; + /** Share of the way from the start weight to the target, 0 to 1. */ + progress: number; + /** Signed change per week along the fitted line. Null without enough weigh-ins. */ + ratePerWeekKg: number | null; + /** When the fitted line reaches the target. Only set when on track. */ + etaAt: Date | null; + /** The fitted line, for drawing: weight at `fromAt` and its change per day. */ + line: { fromAt: Date; fromKg: number; perDayKg: number } | null; +}; + +const DAY_MS = 24 * 60 * 60 * 1000; +/** Recent weigh-ins describe the current pace; widen only when they are too few. */ +const TREND_WINDOWS_DAYS = [30, 90]; +/** Day-to-day swings (water, food) drown out real change over less than a week. */ +const TREND_MIN_SPAN_DAYS = 7; +/** An arrival further out than this is not a useful estimate. */ +const TREND_MAX_ETA_DAYS = 3 * 365; + +function fitLine(points: { t: number; kg: number }[]): { slope: number; at: (t: number) => number } { + const meanT = points.reduce((sum, point) => sum + point.t, 0) / points.length; + const meanKg = points.reduce((sum, point) => sum + point.kg, 0) / points.length; + let covariance = 0; + let variance = 0; + for (const point of points) { + covariance += (point.t - meanT) * (point.kg - meanKg); + variance += (point.t - meanT) ** 2; + } + const slope = variance === 0 ? 0 : covariance / variance; + return { slope, at: (t) => meanKg + slope * (t - meanT) }; +} + +/** + * Where the user stands against their weight goal. The pace is a least-squares + * line through recent weigh-ins, so one unusual reading does not swing the ETA. + */ +export function weightTrend(input: { + weights: { loggedAt: Date; weightKg: number }[]; + targetKg: number; + startKg: number; + now: Date; +}): WeightTrend { + const now = input.now.getTime(); + const past = input.weights + .filter((entry) => entry.loggedAt.getTime() <= now) + .sort((a, b) => a.loggedAt.getTime() - b.loggedAt.getTime()); + const currentKg = past.length > 0 ? past[past.length - 1].weightKg : input.startKg; + const direction = Math.sign(input.targetKg - input.startKg); + const reached = direction <= 0 ? currentKg <= input.targetKg : currentKg >= input.targetKg; + const total = Math.abs(input.targetKg - input.startKg); + const remainingKg = reached ? 0 : round2(Math.abs(input.targetKg - currentKg)); + const progress = reached || total === 0 ? 1 : Math.min(1, Math.max(0, 1 - Math.abs(input.targetKg - currentKg) / total)); + + let window: typeof past = []; + for (const days of TREND_WINDOWS_DAYS) { + window = past.filter((entry) => entry.loggedAt.getTime() >= now - days * DAY_MS); + if (window.length >= 2) { + const span = window[window.length - 1].loggedAt.getTime() - window[0].loggedAt.getTime(); + if (span >= TREND_MIN_SPAN_DAYS * DAY_MS) break; + } + window = []; + } + const base = { currentKg, remainingKg, progress: round2(progress) }; + if (window.length === 0) { + return { ...base, status: reached ? "reached" : "need_data", ratePerWeekKg: null, etaAt: null, line: null }; + } + + const fromAt = window[0].loggedAt; + // Days since the first weigh-in in the window keep the sums small and exact enough. + const fit = fitLine(window.map((entry) => ({ t: (entry.loggedAt.getTime() - fromAt.getTime()) / DAY_MS, kg: entry.weightKg }))); + const line = { fromAt, fromKg: round2(fit.at(0)), perDayKg: fit.slope }; + const ratePerWeekKg = round2(fit.slope * 7); + if (reached) return { ...base, status: "reached", ratePerWeekKg, etaAt: null, line }; + + const nowDays = (now - fromAt.getTime()) / DAY_MS; + const daysLeft = fit.slope === 0 ? Infinity : Math.max(0, (input.targetKg - fit.at(nowDays)) / fit.slope); + const towards = fit.slope * direction > 0; + if (!towards || daysLeft > TREND_MAX_ETA_DAYS) { + return { ...base, status: "off_track", ratePerWeekKg, etaAt: null, line }; + } + return { ...base, status: "on_track", ratePerWeekKg, etaAt: new Date(now + daysLeft * DAY_MS), line }; +} + export type PasswordChecks = { length: boolean; english: boolean; diff --git a/apps/api/src/routes/weights.ts b/apps/api/src/routes/weights.ts index c233a01..7c2f0b7 100644 --- a/apps/api/src/routes/weights.ts +++ b/apps/api/src/routes/weights.ts @@ -1,31 +1,60 @@ import { Router } from "express"; import { currentUser, requireUser } from "../auth.js"; import { prisma } from "../db.js"; +import { weightTrend } from "../domain.js"; import { asyncRoute } from "../http.js"; import { num } from "../present.js"; import { requirePermission } from "../rbac.js"; -import { weightSchema } from "../schemas.js"; +import { weightGoalSchema, weightSchema } from "../schemas.js"; +import { jerusalemDay } from "../time.js"; export const weightsRouter = Router(); weightsRouter.use(requireUser); +/** Weigh-ins plus the goal and how the user is trending towards it. */ +async function weightOverview(userId: string) { + const [rows, goal] = await Promise.all([ + prisma.weightEntry.findMany({ where: { userId }, orderBy: { loggedAt: "asc" } }), + prisma.weightGoal.findUnique({ where: { userId } }), + ]); + const weights = rows.map((entry) => ({ + id: entry.id, + weightKg: num(entry.weightKg), + loggedAt: entry.loggedAt.toISOString(), + source: entry.source, + })); + if (!goal) return { weights, goal: null, trend: null }; + const trend = weightTrend({ + weights: rows.map((entry) => ({ loggedAt: entry.loggedAt, weightKg: num(entry.weightKg) })), + targetKg: num(goal.targetKg), + startKg: num(goal.startKg), + now: new Date(), + }); + return { + weights, + goal: { targetKg: num(goal.targetKg), startKg: num(goal.startKg), setAt: goal.setAt.toISOString() }, + trend: { + status: trend.status, + currentKg: trend.currentKg, + remainingKg: trend.remainingKg, + progress: trend.progress, + ratePerWeekKg: trend.ratePerWeekKg, + etaAt: trend.etaAt?.toISOString() ?? null, + etaDay: trend.etaAt ? jerusalemDay(trend.etaAt) : null, + line: trend.line && { + fromAt: trend.line.fromAt.toISOString(), + fromKg: trend.line.fromKg, + perDayKg: trend.line.perDayKg, + }, + }, + }; +} + weightsRouter.get( "/", requirePermission("weights:read"), asyncRoute(async (_req, res) => { - const user = currentUser(res); - const rows = await prisma.weightEntry.findMany({ - where: { userId: user.id }, - orderBy: { loggedAt: "asc" }, - }); - res.json({ - weights: rows.map((entry) => ({ - id: entry.id, - weightKg: num(entry.weightKg), - loggedAt: entry.loggedAt.toISOString(), - source: entry.source, - })), - }); + res.json(await weightOverview(currentUser(res).id)); }), ); @@ -52,3 +81,47 @@ weightsRouter.post( }); }), ); + +weightsRouter.put( + "/goal", + requirePermission("weights:create"), + asyncRoute(async (req, res) => { + const user = currentUser(res); + const body = weightGoalSchema.parse(req.body); + const [existing, latest, profile] = await Promise.all([ + prisma.weightGoal.findUnique({ where: { userId: user.id } }), + prisma.weightEntry.findFirst({ + where: { userId: user.id, loggedAt: { lte: new Date() } }, + orderBy: { loggedAt: "desc" }, + }), + prisma.profile.findUnique({ where: { userId: user.id } }), + ]); + // Moving the target further along the same way keeps the progress made so far; + // a goal in the other direction (or a first goal) starts from today's weight. + const sameWay = + existing != null && + Math.sign(body.targetKg - num(existing.startKg)) === Math.sign(num(existing.targetKg) - num(existing.startKg)) && + body.targetKg !== num(existing.startKg); + if (sameWay) { + await prisma.weightGoal.update({ where: { userId: user.id }, data: { targetKg: body.targetKg } }); + } else { + const startKg = latest ? num(latest.weightKg) : profile ? num(profile.weightKg) : body.targetKg; + await prisma.weightGoal.upsert({ + where: { userId: user.id }, + create: { userId: user.id, targetKg: body.targetKg, startKg }, + update: { targetKg: body.targetKg, startKg, setAt: new Date() }, + }); + } + res.json(await weightOverview(user.id)); + }), +); + +weightsRouter.delete( + "/goal", + requirePermission("weights:create"), + asyncRoute(async (_req, res) => { + const user = currentUser(res); + await prisma.weightGoal.deleteMany({ where: { userId: user.id } }); + res.json(await weightOverview(user.id)); + }), +); diff --git a/apps/api/src/schemas.ts b/apps/api/src/schemas.ts index 1fe15e1..2c8bde9 100644 --- a/apps/api/src/schemas.ts +++ b/apps/api/src/schemas.ts @@ -114,6 +114,10 @@ export const weightSchema = z.object({ loggedAt: z.string().datetime().optional(), }); +export const weightGoalSchema = z.object({ + targetKg: z.number().gt(0).max(500), +}); + export const healthSettingsSchema = z.object({ exerciseGoalMinutes: z.number().int().min(1).max(1440), stepGoal: z.number().int().min(100).max(200000), diff --git a/apps/mobile/lib/copy.dart b/apps/mobile/lib/copy.dart index 919a42e..d870f88 100644 --- a/apps/mobile/lib/copy.dart +++ b/apps/mobile/lib/copy.dart @@ -296,6 +296,86 @@ class Copy { String get logWeight => pick('Log weight', 'רישום משקל'); String get graphEmpty => pick('Log a weight to see the graph.', 'רשמו משקל כדי לראות את הגרף.'); + String get weightGoal => pick('Weight goal', 'יעד משקל'); + String get goalWeightKg => pick('Goal weight (kg)', 'משקל יעד (ק״ג)'); + String get setGoal => pick('Set goal', 'קביעת יעד'); + String get removeGoal => pick('Remove goal', 'הסרת היעד'); + String get goalIntro => pick( + 'Set a target weight to see your trend and an estimated date.', + 'קבעו משקל יעד כדי לראות את המגמה ותאריך משוער.', + ); + String get goalEta => pick('Estimated goal date', 'תאריך יעד משוער'); + String get atCurrentPace => pick('at your current pace', 'בקצב הנוכחי'); + String get goalReached => pick('Goal reached', 'הגעתם ליעד'); + String get goalReachedHint => + pick('You can set a new goal any time.', 'אפשר לקבוע יעד חדש בכל רגע.'); + String get goalNeedData => pick( + "Keep logging. After a week of weigh-ins you'll see your pace and an estimated date.", + 'המשיכו לרשום. אחרי שבוע של שקילות יוצגו הקצב ותאריך משוער.', + ); + String get goalNoEta => pick('No estimated date', 'אין תאריך משוער'); + String get goalOffTrack => pick( + "Your recent weigh-ins aren't moving toward the goal.", + 'השקילות האחרונות לא מתקדמות לכיוון היעד.', + ); + String get currentWeight => pick('Current', 'נוכחי'); + String get toGo => pick('To go', 'נותרו'); + String get weightPace => pick('Pace', 'קצב'); + String get kgPerWeek => pick('kg/week', 'ק״ג בשבוע'); + String get weighIns => pick('Weigh-ins', 'שקילות'); + String get trend => pick('Trend', 'מגמה'); + String get goalLine => pick('Goal', 'יעד'); + + /// "In 7 weeks" style distance to a day [days] ahead, in the largest unit that reads naturally. + String until(int days) { + String count( + int n, + String enOne, + String enMany, + String heOne, + String heTwo, + String heMany, + ) => he + ? 'בעוד ${n == 1 + ? heOne + : n == 2 + ? heTwo + : '$n $heMany'}' + : 'In $n ${n == 1 ? enOne : enMany}'; + if (days <= 0) return pick('Today', 'היום'); + if (days < 14) { + return count(days, 'day', 'days', 'יום', 'יומיים', 'ימים'); + } + if (days < 70) { + return count( + (days / 7).round(), + 'week', + 'weeks', + 'שבוע', + 'שבועיים', + 'שבועות', + ); + } + if (days < 730) { + return count( + (days / 30.44).round(), + 'month', + 'months', + 'חודש', + 'חודשיים', + 'חודשים', + ); + } + return count( + (days / 365.25).round(), + 'year', + 'years', + 'שנה', + 'שנתיים', + 'שנים', + ); + } + String get autoPublish => pick('Publish new foods by default', 'פרסום מזונות חדשים כברירת מחדל'); String get fasting => pick('Intermittent fasting', 'צום לסירוגין'); diff --git a/apps/mobile/lib/main.dart b/apps/mobile/lib/main.dart index 32b7455..a278bb2 100644 --- a/apps/mobile/lib/main.dart +++ b/apps/mobile/lib/main.dart @@ -2629,8 +2629,15 @@ class _WeightScreenState extends State { late List> weights = ((widget.api.peek('/api/weights')?['weights'] as List?) ?? const []) .cast>(); + late Map? goal = + widget.api.peek('/api/weights')?['goal'] as Map?; + late Map? trend = + widget.api.peek('/api/weights')?['trend'] as Map?; final controller = TextEditingController(); + final goalController = TextEditingController(); String error = ''; + String goalError = ''; + bool editingGoal = false; @override void initState() { @@ -2638,10 +2645,272 @@ class _WeightScreenState extends State { unawaited(load()); } + @override + void dispose() { + controller.dispose(); + goalController.dispose(); + super.dispose(); + } + Future load() async { final data = await widget.api.send('GET', '/api/weights'); - setState( - () => weights = (data['weights'] as List).cast>(), + if (!mounted) return; + setState(() { + weights = (data['weights'] as List).cast>(); + goal = data['goal'] as Map?; + trend = data['trend'] as Map?; + }); + } + + /// Saves ([targetKg] set) or removes (null) the goal, then reloads the trend. + Future changeGoal(num? targetKg) async { + try { + if (targetKg == null) { + await widget.api.send('DELETE', '/api/weights/goal'); + } else { + await widget.api.send( + 'PUT', + '/api/weights/goal', + body: {'targetKg': targetKg}, + ); + } + await load(); + if (!mounted) return; + setState(() { + editingGoal = false; + goalError = ''; + }); + } on ApiException catch (err) { + setState(() => goalError = widget.t.error(err.code)); + } + } + + Widget goalForm(Copy t, AppleColors apple) { + final hasGoal = goal != null; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(t.weightGoal, style: Theme.of(context).textTheme.titleMedium), + if (!hasGoal) ...[ + const SizedBox(height: Gaps.xs), + Text(t.goalIntro, style: TextStyle(color: apple.labelSecondary)), + ], + const SizedBox(height: Gaps.md), + decimalField(goalController, t.goalWeightKg), + if (goalError.isNotEmpty) ...[ + const SizedBox(height: Gaps.sm), + ErrorText(goalError), + ], + const SizedBox(height: Gaps.md), + FilledButton( + onPressed: () { + final targetKg = parseDecimal(goalController.text); + if (targetKg == null) { + setState(() => goalError = t.error('invalid_body')); + return; + } + unawaited(changeGoal(targetKg)); + }, + child: Text(hasGoal ? t.save : t.setGoal), + ), + if (hasGoal) ...[ + const SizedBox(height: Gaps.sm), + Row( + spacing: Gaps.sm, + children: [ + Expanded( + child: OutlinedButton( + onPressed: () => setState(() { + editingGoal = false; + goalError = ''; + }), + child: Text(t.cancel), + ), + ), + Expanded( + child: TextButton( + style: TextButton.styleFrom( + foregroundColor: apple.accentDangerText, + minimumSize: const Size.fromHeight(Gaps.hit), + ), + onPressed: () => unawaited(changeGoal(null)), + child: Text(t.removeGoal), + ), + ), + ], + ), + ], + ], + ); + } + + Widget goalSummary(Copy t, AppleColors apple) { + final status = trend!['status'] as String; + final etaAt = trend!['etaAt'] as String?; + final rate = trend!['ratePerWeekKg'] as num?; + final progress = (trend!['progress'] as num).toDouble(); + final secondary = TextStyle(color: apple.labelSecondary, fontSize: 13); + Widget headline(String text, {Color? color}) => Text( + text, + style: TextStyle( + fontSize: 28, + fontWeight: FontWeight.w700, + letterSpacing: -0.4, + color: color, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ); + Widget stat(String label, String value, [String? unit]) => Expanded( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: Gaps.md, + vertical: Gaps.sm, + ), + decoration: BoxDecoration( + color: apple.tertiaryFill, + borderRadius: BorderRadius.circular(Radii.sm), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: TextStyle(color: apple.labelSecondary, fontSize: 12), + ), + Text( + value, + textDirection: TextDirection.ltr, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w700, + fontFeatures: [FontFeature.tabularFigures()], + ), + ), + if (unit != null) + Text( + unit, + style: TextStyle(color: apple.labelSecondary, fontSize: 12), + ), + ], + ), + ), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + t.weightGoal, + style: Theme.of(context).textTheme.titleMedium, + ), + ), + TextButton( + style: TextButton.styleFrom( + minimumSize: const Size(Gaps.hit, Gaps.hit), + ), + onPressed: () => setState(() { + goalController.text = '${goal!['targetKg']}'; + editingGoal = true; + }), + child: Text(t.edit), + ), + ], + ), + if (status == 'on_track' && etaAt != null) ...[ + Text(t.goalEta, style: secondary), + headline(_jerusalemDate(etaAt)), + Text( + '${t.until(_daysUntil(etaAt))} ${t.atCurrentPace}', + style: secondary, + ), + ] else if (status == 'reached') ...[ + headline(t.goalReached, color: apple.accentSuccessText), + Text(t.goalReachedHint, style: secondary), + ] else if (status == 'off_track') ...[ + headline(t.goalNoEta), + Text(t.goalOffTrack, style: secondary), + ] else + Text(t.goalNeedData, style: TextStyle(color: apple.labelSecondary)), + const SizedBox(height: Gaps.md), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('${goal!['startKg']} ${t.kg}', style: secondary), + Text('${goal!['targetKg']} ${t.kg}', style: secondary), + ], + ), + const SizedBox(height: Gaps.sm), + EaseBuilder( + from: 0, + value: progress, + builder: (context, shown) => ClipRRect( + borderRadius: BorderRadius.circular(999), + child: LinearProgressIndicator( + value: shown, + minHeight: 8, + backgroundColor: apple.tertiaryFill, + color: status == 'reached' + ? apple.accentSuccess + : apple.accentPrimary, + semanticsLabel: t.weightGoal, + ), + ), + ), + const SizedBox(height: Gaps.lg), + Row( + spacing: Gaps.sm, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + stat(t.currentWeight, '${trend!['currentKg']}', t.kg), + stat(t.toGo, '${trend!['remainingKg']}', t.kg), + stat( + t.weightPace, + rate == null + ? '—' + : '${rate > 0 + ? '+' + : rate < 0 + ? '−' + : ''}${rate.abs()}', + t.kgPerWeek, + ), + ], + ), + ], + ); + } + + Widget legend(Copy t, AppleColors apple) { + Widget item(Color color, String label, {bool dashed = false}) => Row( + mainAxisSize: MainAxisSize.min, + spacing: Gaps.sm, + children: [ + SizedBox( + width: 20, + height: 3, + child: CustomPaint(painter: _SwatchPainter(color, dashed)), + ), + Text( + label, + style: TextStyle(color: apple.labelSecondary, fontSize: 13), + ), + ], + ); + return Wrap( + spacing: Gaps.lg, + runSpacing: Gaps.sm, + children: [ + item(apple.accentPrimary, t.weighIns), + if (trend?['line'] != null) + item(apple.labelSecondary, t.trend, dashed: true), + item( + apple.accentSuccess, + '${t.goalLine} ${goal!['targetKg']} ${t.kg}', + dashed: true, + ), + ], ); } @@ -2689,6 +2958,14 @@ class _WeightScreenState extends State { ), ), ), + Card( + child: Padding( + padding: const EdgeInsets.all(Gaps.lg), + child: goal == null || trend == null || editingGoal + ? goalForm(t, apple) + : goalSummary(t, apple), + ), + ), Card( child: Padding( padding: const EdgeInsets.all(Gaps.lg), @@ -2700,11 +2977,21 @@ class _WeightScreenState extends State { t.graphEmpty, style: TextStyle(color: apple.labelSecondary), ) - else + else ...[ SizedBox( height: 180, - child: AnimatedWeightChart(weights: weights), + child: AnimatedWeightChart( + weights: weights, + goal: goal, + trend: trend, + ), ), + if (goal != null) ...[ + const SizedBox(height: Gaps.md), + legend(t, apple), + const SizedBox(height: Gaps.sm), + ], + ], for (final point in weights.reversed) ...[ Divider( color: apple.separator, @@ -2714,7 +3001,7 @@ class _WeightScreenState extends State { ListTile( contentPadding: EdgeInsets.zero, minTileHeight: Gaps.hit, - title: Text('${point['weightKg']} kg'), + title: Text('${point['weightKg']} ${t.kg}'), subtitle: Text( '${_jerusalemDate(point['loggedAt'] as String)} ${_jerusalemTime(point['loggedAt'] as String)} · ${point['source'] == 'health' ? t.healthSource : t.manualSource}', style: TextStyle(color: apple.labelSecondary), @@ -2730,22 +3017,81 @@ class _WeightScreenState extends State { } } +int _daysUntil(String iso) { + final left = DateTime.parse(iso).difference(DateTime.now()); + return (left.inMinutes / (24 * 60)).round(); +} + +void _dashedLine( + Canvas canvas, + Offset from, + Offset to, + Paint paint, { + required double dash, + required double gap, +}) { + final length = (to - from).distance; + if (length == 0) return; + final step = (to - from) / length; + for (var at = 0.0; at < length; at += dash + gap) { + final end = at + dash < length ? at + dash : length; + canvas.drawLine(from + step * at, from + step * end, paint); + } +} + +class _SwatchPainter extends CustomPainter { + const _SwatchPainter(this.color, this.dashed); + final Color color; + final bool dashed; + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..strokeWidth = dashed ? 2 : 3 + ..strokeCap = StrokeCap.round; + final from = Offset(1, size.height / 2); + final to = Offset(size.width - 1, size.height / 2); + if (dashed) { + _dashedLine(canvas, from, to, paint, dash: 3, gap: 4); + } else { + canvas.drawLine(from, to, paint); + } + } + + @override + bool shouldRepaint(covariant _SwatchPainter oldDelegate) => + oldDelegate.color != color || oldDelegate.dashed != dashed; +} + class WeightPainter extends CustomPainter { - WeightPainter(this.weights, this.progress, this.color, this.healthColor); + WeightPainter( + this.weights, + this.progress, + this.color, + this.healthColor, { + this.goal, + this.trend, + required this.trendColor, + required this.goalColor, + required this.surface, + }); final List> weights; final double progress; final Color color; final Color healthColor; + final Map? goal; + final Map? trend; + final Color trendColor; + final Color goalColor; + final Color surface; + + static const _dayMs = 24 * 60 * 60 * 1000; @override void paint(Canvas canvas, Size size) { - final dot = Paint()..color = color.withValues(alpha: progress.clamp(0, 1)); - if (weights.length < 2) { - if (weights.isNotEmpty) { - canvas.drawCircle(Offset(size.width / 2, size.height / 2), 4, dot); - } - return; - } + if (weights.isEmpty) return; + final shown = progress.clamp(0.0, 1.0); final times = weights .map( (point) => @@ -2756,47 +3102,122 @@ class WeightPainter extends CustomPainter { final values = weights .map((point) => (point['weightKg'] as num).toDouble()) .toList(); - final minT = times.reduce((a, b) => a < b ? a : b); - final maxT = times.reduce((a, b) => a > b ? a : b); - final minV = values.reduce((a, b) => a < b ? a : b); - final maxV = values.reduce((a, b) => a > b ? a : b); - final paint = Paint() - ..color = color - ..strokeWidth = 3 - ..strokeCap = StrokeCap.round - ..strokeJoin = StrokeJoin.round - ..style = PaintingStyle.stroke; - final path = Path(); - final spots = []; - for (var i = 0; i < weights.length; i++) { - final x = maxT == minT - ? size.width / 2 - : (times[i] - minT) / (maxT - minT) * (size.width - 16) + 8; - final y = maxV == minV - ? size.height / 2 - : size.height - - 8 - - (values[i] - minV) / (maxV - minV) * (size.height - 16); - final spot = Offset(x, y); - spots.add(spot); - if (i == 0) { - path.moveTo(x, y); - } else { - path.lineTo(x, y); + double least(Iterable all) => all.reduce((a, b) => a < b ? a : b); + double most(Iterable all) => all.reduce((a, b) => a > b ? a : b); + final firstT = least(times); + final lastT = most(times); + final goalKg = (goal?['targetKg'] as num?)?.toDouble(); + + // The fitted line runs on past today: to the goal when that is no further + // ahead than the history shown, otherwise part of the way. + final line = trend?['line'] as Map?; + double? fitFromT, fitToT, fitFromKg, fitToKg; + var arrives = false; + if (goalKg != null && line != null) { + final now = DateTime.now().millisecondsSinceEpoch.toDouble(); + final span = lastT - firstT; + final horizon = now + (span > 30 * _dayMs ? span : 30 * _dayMs); + final etaAt = trend!['etaAt'] as String?; + final eta = etaAt == null + ? null + : DateTime.parse(etaAt).millisecondsSinceEpoch.toDouble(); + arrives = eta != null && eta <= horizon; + fitFromT = DateTime.parse(line['fromAt'] as String).millisecondsSinceEpoch + .toDouble(); + fitFromKg = (line['fromKg'] as num).toDouble(); + fitToT = trend!['status'] == 'reached' + ? now + : arrives + ? eta + : horizon; + fitToKg = arrives + ? goalKg + : fitFromKg + + (line['perDayKg'] as num).toDouble() * + (fitToT - fitFromT) / + _dayMs; + } + + final minT = firstT; + final maxT = fitToT != null && fitToT > lastT ? fitToT : lastT; + final scale = [...values, ?goalKg, ?fitFromKg, ?fitToKg]; + final minV = least(scale); + final maxV = most(scale); + double x(double time) => maxT == minT + ? size.width / 2 + : (time - minT) / (maxT - minT) * (size.width - 16) + 8; + double y(double kg) => maxV == minV + ? size.height / 2 + : size.height - 8 - (kg - minV) / (maxV - minV) * (size.height - 16); + + if (goalKg != null) { + _dashedLine( + canvas, + Offset(8, y(goalKg)), + Offset(size.width - 8, y(goalKg)), + Paint() + ..color = goalColor.withValues(alpha: shown) + ..strokeWidth = 2 + ..strokeCap = StrokeCap.round, + dash: 1, + gap: 6, + ); + } + if (fitFromT != null) { + _dashedLine( + canvas, + Offset(x(fitFromT), y(fitFromKg!)), + Offset(x(fitToT!), y(fitToKg!)), + Paint() + ..color = trendColor.withValues(alpha: trendColor.a * shown) + ..strokeWidth = 2 + ..strokeCap = StrokeCap.round, + dash: 6, + gap: 6, + ); + } + + final spots = [ + for (var i = 0; i < weights.length; i++) + Offset(x(times[i]), y(values[i])), + ]; + if (spots.length > 1) { + final path = Path()..moveTo(spots.first.dx, spots.first.dy); + for (final spot in spots.skip(1)) { + path.lineTo(spot.dx, spot.dy); } + final metric = path.computeMetrics().first; + canvas.drawPath( + metric.extractPath(0, metric.length * shown), + Paint() + ..color = color + ..strokeWidth = 3 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..style = PaintingStyle.stroke, + ); } - final metric = path.computeMetrics().first; - canvas.drawPath( - metric.extractPath(0, metric.length * progress.clamp(0, 1)), - paint, - ); for (var i = 0; i < spots.length; i++) { - final along = i / (spots.length - 1); + final along = spots.length == 1 ? 0.0 : i / (spots.length - 1); if (along > progress) continue; canvas.drawCircle( spots[i], 4, - Paint()..color = weights[i]['source'] == 'health' ? healthColor : color, + Paint() + ..color = (weights[i]['source'] == 'health' ? healthColor : color) + .withValues(alpha: spots.length == 1 ? shown : 1), + ); + } + if (arrives && shown == 1) { + final arrival = Offset(x(fitToT!), y(goalKg!)); + canvas.drawCircle(arrival, 5, Paint()..color = surface); + canvas.drawCircle( + arrival, + 5, + Paint() + ..color = goalColor + ..strokeWidth = 3 + ..style = PaintingStyle.stroke, ); } } @@ -2805,8 +3226,13 @@ class WeightPainter extends CustomPainter { bool shouldRepaint(covariant WeightPainter oldDelegate) => oldDelegate.progress != progress || oldDelegate.weights != weights || + oldDelegate.goal != goal || + oldDelegate.trend != trend || oldDelegate.color != color || - oldDelegate.healthColor != healthColor; + oldDelegate.healthColor != healthColor || + oldDelegate.trendColor != trendColor || + oldDelegate.goalColor != goalColor || + oldDelegate.surface != surface; } class SettingsScreen extends StatefulWidget { @@ -4711,8 +5137,15 @@ class HealthProgressRow extends StatelessWidget { } class AnimatedWeightChart extends StatefulWidget { - const AnimatedWeightChart({super.key, required this.weights}); + const AnimatedWeightChart({ + super.key, + required this.weights, + this.goal, + this.trend, + }); final List> weights; + final Map? goal; + final Map? trend; @override State createState() => _AnimatedWeightChartState(); @@ -4768,6 +5201,11 @@ class _AnimatedWeightChartState extends State Curves.easeOutCubic.transform(controller.value), context.apple.accentPrimary, context.apple.accentSuccess, + goal: widget.goal, + trend: widget.trend, + trendColor: context.apple.labelSecondary, + goalColor: context.apple.accentSuccess, + surface: context.apple.cardBg, ), child: const SizedBox.expand(), ), diff --git a/apps/mobile/test/weight_goal_test.dart b/apps/mobile/test/weight_goal_test.dart new file mode 100644 index 0000000..261e5dd --- /dev/null +++ b/apps/mobile/test/weight_goal_test.dart @@ -0,0 +1,137 @@ +import 'package:drop_it/api.dart'; +import 'package:drop_it/copy.dart'; +import 'package:drop_it/main.dart'; +import 'package:drop_it/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:timezone/data/latest.dart' as tz_data; + +/// Serves a fixed weight overview and records goal changes. +class FakeApi extends Api { + FakeApi(this.overview); + Map overview; + final calls = []; + + @override + Future> send( + String method, + String path, { + Object? body, + }) async { + calls.add('$method $path${body == null ? '' : ' $body'}'); + return overview; + } +} + +Map onTrack() { + final now = DateTime.now().toUtc(); + String at(int days) => now.add(Duration(days: days)).toIso8601String(); + return { + 'weights': [ + for (final (i, kg) in [74.2, 73.5, 72.8, 72.0, 71.0].indexed) + { + 'id': 'w$i', + 'weightKg': kg, + 'loggedAt': at(-(4 - i) * 7), + 'source': i.isEven ? 'manual' : 'health', + }, + ], + 'goal': {'targetKg': 68, 'startKg': 74.2, 'setAt': at(-28)}, + 'trend': { + 'status': 'on_track', + 'currentKg': 71, + 'remainingKg': 3, + 'progress': 0.52, + 'ratePerWeekKg': -0.8, + 'etaAt': at(26), + 'etaDay': at(26).substring(0, 10), + 'line': {'fromAt': at(-28), 'fromKg': 74.3, 'perDayKg': -0.114}, + }, + }; +} + +Future pumpWeight(WidgetTester tester, FakeApi api, String lang) async { + await tester.binding.setSurfaceSize(const Size(390, 1400)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + MaterialApp( + theme: buildAppleTheme(Brightness.light), + home: Directionality( + textDirection: lang == 'he' ? TextDirection.rtl : TextDirection.ltr, + child: Scaffold( + body: WeightScreen(api: api, t: Copy(lang)), + ), + ), + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + setUpAll(tz_data.initializeTimeZones); + + test('time until the goal reads naturally in both languages', () { + const en = Copy('en'); + const he = Copy('he'); + expect(en.until(0), 'Today'); + expect(en.until(1), 'In 1 day'); + expect(en.until(13), 'In 13 days'); + expect(en.until(49), 'In 7 weeks'); + expect(en.until(120), 'In 4 months'); + expect(en.until(800), 'In 2 years'); + expect(he.until(1), 'בעוד יום'); + expect(he.until(14), 'בעוד שבועיים'); + expect(he.until(49), 'בעוד 7 שבועות'); + expect(he.until(365), 'בעוד 12 חודשים'); + }); + + testWidgets('shows the estimated goal date and pace when on track', ( + tester, + ) async { + await pumpWeight(tester, FakeApi(onTrack()), 'en'); + expect(find.text('Estimated goal date'), findsOneWidget); + expect(find.text('In 4 weeks at your current pace'), findsOneWidget); + expect(find.text('−0.8'), findsOneWidget); + expect(find.text('Goal 68 kg'), findsOneWidget); + expect(find.text('Trend'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('renders right to left in Hebrew', (tester) async { + await pumpWeight(tester, FakeApi(onTrack()), 'he'); + expect(find.text('תאריך יעד משוער'), findsOneWidget); + expect(find.text('בעוד 4 שבועות בקצב הנוכחי'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('offers to set a goal, then saves it', (tester) async { + final api = FakeApi({...onTrack(), 'goal': null, 'trend': null}); + await pumpWeight(tester, api, 'en'); + expect(find.text('Estimated goal date'), findsNothing); + await tester.enterText(find.byType(TextField).last, '68'); + api.overview = onTrack(); + await tester.tap(find.text('Set goal')); + await tester.pumpAndSettle(); + expect(api.calls, contains('PUT /api/weights/goal {targetKg: 68}')); + expect(find.text('Estimated goal date'), findsOneWidget); + }); + + testWidgets('explains a missing estimate and lets the goal be removed', ( + tester, + ) async { + final data = onTrack(); + (data['trend'] as Map) + ..['status'] = 'off_track' + ..['etaAt'] = null + ..['ratePerWeekKg'] = 0.3; + final api = FakeApi(data); + await pumpWeight(tester, api, 'en'); + expect(find.text('No estimated date'), findsOneWidget); + expect(find.text('+0.3'), findsOneWidget); + await tester.tap(find.text('Edit')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Remove goal')); + await tester.pumpAndSettle(); + expect(api.calls, contains('DELETE /api/weights/goal')); + }); +} diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index db25056..9fe3a36 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -24,10 +24,13 @@ import { type Profile, setStoredToken, type WeekResponse, + type WeightGoal, + type WeightOverview, type WeightPoint, + type WeightTrend, } from "./api"; import { fetchAppleConfig, signInWithApple, type AppleConfig } from "./apple"; -import { addDays, formatDayLabel, formatJerusalem, formatJerusalemDay, formatJerusalemTime, formatWeekday, formatWeekRange, hourLabel, jerusalemParts, todayJerusalemDay } from "./clock"; +import { addDays, formatDayLabel, formatJerusalem, formatJerusalemDay, formatJerusalemTime, formatUntil, formatWeekday, formatWeekRange, hourLabel, jerusalemParts, todayJerusalemDay } from "./clock"; import { THEME_MODES, useI18n, useTheme, type Copy, type Lang, type ThemeMode } from "./i18n"; import { ageFromDob, @@ -1386,11 +1389,13 @@ function formatKcal(value: number): string { function WeightPage() { const { t } = useI18n(); - const [weights, setWeights] = useState(() => peek<{ weights: WeightPoint[] }>("/api/weights")?.weights ?? []); + const [overview, setOverview] = useState( + () => peek("/api/weights") ?? { weights: [], goal: null, trend: null }, + ); const [error, setError] = useState(""); + const { weights, goal, trend } = overview; async function load() { - const data = await api<{ weights: WeightPoint[] }>("/api/weights"); - setWeights(data.weights); + setOverview(await api("/api/weights")); } useEffect(() => { load().catch((err) => setError(message(t, err))); }, [t]); async function save(event: FormEvent) { @@ -1422,8 +1427,9 @@ function WeightPage() { {error &&

{error}

} +
- {weights.length === 0 ?

{t.graphEmpty}

: } + {weights.length === 0 ?

{t.graphEmpty}

: } {weights.map((point) => (
@@ -1438,28 +1444,154 @@ function WeightPage() { ); } -function WeightGraph({ weights }: { weights: WeightPoint[] }) { +/** The goal, progress towards it, and when the current pace gets there. */ +function WeightGoalCard({ goal, trend, onChange }: { goal: WeightGoal | null; trend: WeightTrend | null; onChange: () => Promise }) { + const { t } = useI18n(); + const [editing, setEditing] = useState(false); + const [error, setError] = useState(""); + async function run(request: () => Promise) { + try { + await request(); + await onChange(); + setEditing(false); + setError(""); + } catch (err) { + setError(message(t, err)); + } + } + function save(event: FormEvent) { + event.preventDefault(); + const data = new FormData(event.currentTarget); + return run(() => api("/api/weights/goal", { method: "PUT", body: JSON.stringify({ targetKg: readNutrient(data.get("targetKg")) }) })); + } + if (!goal || !trend || editing) { + return ( +
+

{t.weightGoal}

+ {!goal &&

{t.goalIntro}

} + + {error &&

{error}

} +
+ + {goal && } + {goal && } +
+
+ ); + } + const rate = trend.ratePerWeekKg; + const until = trend.etaAt ? formatUntil(trend.etaAt) : ""; + return ( +
+
+

{t.weightGoal}

+ +
+ {trend.status === "on_track" && trend.etaAt && ( +
+ {t.goalEta} + {formatJerusalemDay(trend.etaAt)} + {until.charAt(0).toUpperCase() + until.slice(1)} {t.atCurrentPace} +
+ )} + {trend.status === "reached" && ( +
+ {t.goalReached} + {t.goalReachedHint} +
+ )} + {trend.status === "off_track" && ( +
+ {t.goalNoEta} + {t.goalOffTrack} +
+ )} + {trend.status === "need_data" &&

{t.goalNeedData}

} +
+
+ {goal.startKg} {t.kg} + {goal.targetKg} {t.kg} +
+
+ +
+
+
+
{t.currentWeight}{trend.currentKg} {t.kg}
+
{t.toGo}{trend.remainingKg} {t.kg}
+
+ {t.weightPace} + + {rate == null ? "—" : <>{rate > 0 ? "+" : rate < 0 ? "−" : ""}{Math.abs(rate)} {t.kgPerWeek}} + +
+
+
+ ); +} + +const DAY_MS = 24 * 60 * 60 * 1000; + +function WeightGraph({ weights, goal, trend }: { weights: WeightPoint[]; goal: WeightGoal | null; trend: WeightTrend | null }) { + const { t } = useI18n(); const times = weights.map((point) => new Date(point.loggedAt).getTime()); const values = weights.map((point) => point.weightKg); - const minT = Math.min(...times); - const maxT = Math.max(...times); - const minV = Math.min(...values); - const maxV = Math.max(...values); + const firstT = Math.min(...times); + const lastT = Math.max(...times); + + // The fitted line runs on past today: to the goal when that is no further ahead than the history shown, otherwise part of the way. + let fit: { fromT: number; toT: number; fromKg: number; toKg: number; arrives: boolean } | null = null; + if (goal && trend?.line) { + const { fromKg, perDayKg } = trend.line; + const fromT = new Date(trend.line.fromAt).getTime(); + const now = Date.now(); + const horizon = now + Math.max(lastT - firstT, 30 * DAY_MS); + const eta = trend.etaAt ? new Date(trend.etaAt).getTime() : null; + const arrives = eta != null && eta <= horizon; + const toT = trend.status === "reached" ? now : arrives ? eta : horizon; + fit = { fromT, toT, fromKg, toKg: arrives ? goal.targetKg : fromKg + (perDayKg * (toT - fromT)) / DAY_MS, arrives }; + } + + const minT = firstT; + const maxT = Math.max(lastT, fit?.toT ?? lastT); + const scaleValues = [...values, ...(goal ? [goal.targetKg] : []), ...(fit ? [fit.fromKg, fit.toKg] : [])]; + const minV = Math.min(...scaleValues); + const maxV = Math.max(...scaleValues); const width = 640; const height = 220; - const plotted = weights.map((point) => { - const x = maxT === minT ? width / 2 : ((new Date(point.loggedAt).getTime() - minT) / (maxT - minT)) * (width - 24) + 12; - const y = maxV === minV ? height / 2 : height - 16 - ((point.weightKg - minV) / (maxV - minV)) * (height - 32); - return { id: point.id, x, y, source: point.source }; - }); + const x = (time: number) => (maxT === minT ? width / 2 : ((time - minT) / (maxT - minT)) * (width - 24) + 12); + const y = (kg: number) => (maxV === minV ? height / 2 : height - 16 - ((kg - minV) / (maxV - minV)) * (height - 32)); + const plotted = weights.map((point, index) => ({ id: point.id, x: x(times[index]), y: y(point.weightKg), source: point.source })); const points = plotted.map((point) => `${point.x},${point.y}`).join(" "); return ( - - - {plotted.map((point) => ( - - ))} - + <> + + {goal && } + {fit && } + + {plotted.map((point) => ( + + ))} + {fit?.arrives && goal && } + + {goal && ( +
+ {t.weighIns} + {fit && {t.trend}} + {t.goalLine} {goal.targetKg} {t.kg} +
+ )} + ); } diff --git a/apps/web/src/api.ts b/apps/web/src/api.ts index 85b2c3d..b3efa46 100644 --- a/apps/web/src/api.ts +++ b/apps/web/src/api.ts @@ -230,6 +230,23 @@ export type WeekResponse = { export type WeightPoint = { id: string; weightKg: number; loggedAt: string; source: "manual" | "health" }; +export type WeightGoal = { targetKg: number; startKg: number; setAt: string }; + +export type WeightTrend = { + status: "need_data" | "on_track" | "off_track" | "reached"; + currentKg: number; + remainingKg: number; + /** Share of the way from the start weight to the target, 0 to 1. */ + progress: number; + ratePerWeekKg: number | null; + etaAt: string | null; + etaDay: string | null; + /** Fitted line through recent weigh-ins: weight at `fromAt` and change per day. */ + line: { fromAt: string; fromKg: number; perDayKg: number } | null; +}; + +export type WeightOverview = { weights: WeightPoint[]; goal: WeightGoal | null; trend: WeightTrend | null }; + export type AppleHealthState = { connected: boolean; connectedOn: string | null; diff --git a/apps/web/src/clock.ts b/apps/web/src/clock.ts index d464aa1..d3f18a9 100644 --- a/apps/web/src/clock.ts +++ b/apps/web/src/clock.ts @@ -98,3 +98,13 @@ export function formatWeekday(day: string): string { export function formatDayLabel(day: string): string { return new Intl.DateTimeFormat(locale(), { timeZone: "UTC", weekday: "short", day: "numeric", month: "short" }).format(dayDate(day)); } + +/** "in 7 weeks" style distance to a future moment, in the largest unit that reads naturally. */ +export function formatUntil(iso: string, now = new Date()): string { + const days = Math.max(0, Math.round((new Date(iso).getTime() - now.getTime()) / 86400000)); + const format = new Intl.RelativeTimeFormat(locale(), { numeric: "auto" }); + if (days < 14) return format.format(days, "day"); + if (days < 70) return format.format(Math.round(days / 7), "week"); + if (days < 730) return format.format(Math.round(days / 30.44), "month"); + return format.format(Math.round(days / 365.25), "year"); +} diff --git a/apps/web/src/i18n.tsx b/apps/web/src/i18n.tsx index 367f587..a991357 100644 --- a/apps/web/src/i18n.tsx +++ b/apps/web/src/i18n.tsx @@ -194,6 +194,25 @@ const en = { logWeight: "Log weight", loggedAt: "When", graphEmpty: "Log a weight to see the graph.", + weightGoal: "Weight goal", + goalWeightKg: "Goal weight (kg)", + setGoal: "Set goal", + removeGoal: "Remove goal", + goalIntro: "Set a target weight to see your trend and an estimated date.", + goalEta: "Estimated goal date", + atCurrentPace: "at your current pace", + goalReached: "Goal reached", + goalReachedHint: "You can set a new goal any time.", + goalNeedData: "Keep logging. After a week of weigh-ins you'll see your pace and an estimated date.", + goalNoEta: "No estimated date", + goalOffTrack: "Your recent weigh-ins aren't moving toward the goal.", + currentWeight: "Current", + toGo: "To go", + weightPace: "Pace", + kgPerWeek: "kg/week", + weighIns: "Weigh-ins", + trend: "Trend", + goalLine: "Goal", autoPublish: "Publish new foods by default", fasting: "Intermittent fasting", fastingTab: "Fasting", @@ -445,6 +464,25 @@ const he: typeof en = { logWeight: "רישום משקל", loggedAt: "מתי", graphEmpty: "רשמו משקל כדי לראות את הגרף.", + weightGoal: "יעד משקל", + goalWeightKg: "משקל יעד (ק״ג)", + setGoal: "קביעת יעד", + removeGoal: "הסרת היעד", + goalIntro: "קבעו משקל יעד כדי לראות את המגמה ותאריך משוער.", + goalEta: "תאריך יעד משוער", + atCurrentPace: "בקצב הנוכחי", + goalReached: "הגעתם ליעד", + goalReachedHint: "אפשר לקבוע יעד חדש בכל רגע.", + goalNeedData: "המשיכו לרשום. אחרי שבוע של שקילות יוצגו הקצב ותאריך משוער.", + goalNoEta: "אין תאריך משוער", + goalOffTrack: "השקילות האחרונות לא מתקדמות לכיוון היעד.", + currentWeight: "נוכחי", + toGo: "נותרו", + weightPace: "קצב", + kgPerWeek: "ק״ג בשבוע", + weighIns: "שקילות", + trend: "מגמה", + goalLine: "יעד", autoPublish: "פרסום מזונות חדשים כברירת מחדל", fasting: "צום לסירוגין", fastingTab: "צום", diff --git a/apps/web/src/styles.css b/apps/web/src/styles.css index 1e29dbf..c67dbb9 100644 --- a/apps/web/src/styles.css +++ b/apps/web/src/styles.css @@ -748,6 +748,23 @@ button.quiet:active { transform: scale(0.96); opacity: 0.65; box-shadow: none; } animation: draw 0.9s cubic-bezier(0.22, 1, 0.36, 1) forwards; } +.graph-goal { stroke: var(--accent-success); stroke-width: 2; stroke-linecap: round; stroke-dasharray: 1 7; } +.graph-trend { stroke: var(--label-secondary); stroke-width: 2; stroke-linecap: round; stroke-dasharray: 8 7; } +.graph-arrival { fill: var(--bg-elevated); stroke: var(--accent-success); stroke-width: 3; } +.graph-legend { display: flex; flex-wrap: wrap; gap: var(--gap-sm) var(--gap-lg); margin: var(--gap-sm) 0 var(--gap-md); color: var(--label-secondary); font-size: 0.8125rem; } +.graph-legend span { display: inline-flex; align-items: center; gap: var(--gap-sm); } +.graph-legend i { width: 20px; height: 0; border-top: 3px solid var(--accent-primary); border-radius: var(--radius-pill); } +.graph-legend i.swatch-trend { border-top: 2px dashed var(--label-secondary); border-radius: 0; } +.graph-legend i.swatch-goal { border-top: 2px dotted var(--accent-success); border-radius: 0; } + +/* Weight goal */ +.goal-head { display: flex; align-items: center; justify-content: space-between; gap: var(--gap-md); margin-bottom: var(--gap-sm); } +.goal-head h2 { margin: 0; } +.goal-eta { display: grid; gap: 2px; } +.goal-eta span, .goal-eta small { color: var(--label-secondary); font-size: 0.8125rem; } +.goal-eta b { font-size: 1.75rem; line-height: 1.15; letter-spacing: -0.022em; font-variant-numeric: tabular-nums; } +.goal-stats { margin-top: var(--gap-lg); } + .graph-dot { fill: var(--accent-primary); opacity: 0;