Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

The dashboard greeting: a name of your own, and a line under it (#187)

Carter074662c4a2fc
diff --git a/backend/controllers/settings_test.go b/backend/controllers/settings_test.go
index d7bfd36..47bef98 100644
--- a/backend/controllers/settings_test.go
+++ b/backend/controllers/settings_test.go
@@ -3,7 +3,10 @@ package controllers
import (
"net/http"
"net/http/httptest"
+ "strings"
"testing"
+
+ "github.com/Cawlumm/lyftr-backend/models"
)
// settingsData pulls the UserSettings object out of a {"data": ...} envelope.
@@ -147,3 +150,159 @@ func TestUpdateSettings_explicitZeroRespected(t *testing.T) {
assertNum(t, d, "carb_target", 250)
assertNum(t, d, "fat_target", 65)
}
+
+// --- display_name (#170) -----------------------------------------------------
+//
+// The name is a label the person chooses for themselves, so what matters is that
+// it round-trips, that clearing it works, and that it cannot be absent-vs-empty
+// ambiguous — the PATCH semantics every other field here already has.
+
+func assertStr(t *testing.T, d map[string]any, key, want string) {
+ t.Helper()
+ if got, _ := d[key].(string); got != want {
+ t.Fatalf("%s = %q, want %q", key, d[key], want)
+ }
+}
+
+func TestGetSettings_displayNameDefaultsToEmpty(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ c, w := newContext(uid, http.MethodGet, "/api/v1/settings", nil)
+ th.GetSettings(c)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ // Empty, not absent: the clients branch on it, and a missing key would read as
+ // undefined rather than "never set one".
+ d := settingsData(t, w)
+ if _, ok := d["display_name"]; !ok {
+ t.Fatalf("display_name missing from the payload: %v", d)
+ }
+ assertStr(t, d, "display_name", "")
+}
+
+func TestUpdateSettings_storesAndTrimsDisplayName(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ c, w := newContext(uid, http.MethodPut, "/api/v1/settings", map[string]any{"display_name": " Carter "})
+ th.UpdateSettings(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ assertStr(t, settingsData(t, w), "display_name", "Carter")
+
+ // And it is actually stored, not just echoed back.
+ c, w = newContext(uid, http.MethodGet, "/api/v1/settings", nil)
+ th.GetSettings(c)
+ assertStr(t, settingsData(t, w), "display_name", "Carter")
+}
+
+// The #37 rule applies to this field too: a PATCH that omits the name must not
+// wipe it, while one that sends "" must.
+func TestUpdateSettings_displayNameOmittedSurvivesClearedOnEmpty(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ c, w := newContext(uid, http.MethodPut, "/api/v1/settings", map[string]any{"display_name": "Carter"})
+ th.UpdateSettings(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("setup expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ c, w = newContext(uid, http.MethodPut, "/api/v1/settings", map[string]any{"weight_unit": "kg"})
+ th.UpdateSettings(c)
+ assertStr(t, settingsData(t, w), "display_name", "Carter")
+
+ // Whitespace-only is the same request as empty — it trims to "" and clears.
+ c, w = newContext(uid, http.MethodPut, "/api/v1/settings", map[string]any{"display_name": " "})
+ th.UpdateSettings(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ assertStr(t, settingsData(t, w), "display_name", "")
+}
+
+// The validate tag carries 60 as a literal because a struct tag cannot reference a
+// constant, so this is what keeps the two in step: a name of exactly
+// MaxDisplayNameLen is accepted and one character more is refused.
+func TestUpdateSettings_rejectsOverlongDisplayName(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ atLimit := strings.Repeat("a", models.MaxDisplayNameLen)
+ c, w := newContext(uid, http.MethodPut, "/api/v1/settings", map[string]any{"display_name": atLimit})
+ th.UpdateSettings(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("a name of exactly %d chars should be accepted, got %d: %s", models.MaxDisplayNameLen, w.Code, w.Body.String())
+ }
+ assertStr(t, settingsData(t, w), "display_name", atLimit)
+
+ c, w = newContext(uid, http.MethodPut, "/api/v1/settings", map[string]any{"display_name": atLimit + "a"})
+ th.UpdateSettings(c)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 over the limit, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Refused, and the stored name is untouched.
+ c, w = newContext(uid, http.MethodGet, "/api/v1/settings", nil)
+ th.GetSettings(c)
+ assertStr(t, settingsData(t, w), "display_name", atLimit)
+}
+
+// Control characters are the one thing a name may not contain, so this pins both halves
+// of that rule: what is refused, and the much larger set that is deliberately allowed.
+func TestUpdateSettings_rejectsControlCharactersInDisplayName(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+
+ for _, tc := range []struct {
+ name string
+ value string
+ }{
+ {"a newline", "Carter\nSmith"},
+ {"a carriage return", "Carter\rSmith"},
+ {"a NUL", "Carter\x00Smith"},
+ {"a tab", "Carter\tSmith"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c, w := newContext(uid, http.MethodPut, "/api/v1/settings", map[string]any{"display_name": tc.value})
+ th.UpdateSettings(c)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for %s, got %d: %s", tc.name, w.Code, w.Body.String())
+ }
+ })
+ }
+
+ // Nothing was stored by any of the refusals.
+ c, w := newContext(uid, http.MethodGet, "/api/v1/settings", nil)
+ th.GetSettings(c)
+ assertStr(t, settingsData(t, w), "display_name", "")
+}
+
+// The deliberate half of the policy. No comparable app filters characters out of a
+// display name, and this one is shown to nobody but its owner, so a name made of emoji
+// or of a non-Latin script round-trips untouched.
+func TestUpdateSettings_allowsEmojiAndNonLatinDisplayNames(t *testing.T) {
+ setupTestDB(t)
+
+ uid := createTestUser(t)
+
+ for _, want := range []string{
+ "🦍 Carter",
+ "カーター",
+ "كارتر",
+ // A ZWJ sequence: U+200D is category Cf, not Cc, so unicode.IsControl must
+ // leave it alone or every compound emoji becomes unenterable.
+ "Carter 🏋️‍♂️",
+ } {
+ c, w := newContext(uid, http.MethodPut, "/api/v1/settings", map[string]any{"display_name": want})
+ th.UpdateSettings(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200 for %q, got %d: %s", want, w.Code, w.Body.String())
+ }
+ assertStr(t, settingsData(t, w), "display_name", want)
+ }
+}
diff --git a/backend/controllers/user.go b/backend/controllers/user.go
index 99cc77a..4a50746 100644
--- a/backend/controllers/user.go
+++ b/backend/controllers/user.go
@@ -2,6 +2,8 @@ package controllers
import (
"database/sql"
+ "strings"
+ "unicode"
"github.com/Cawlumm/lyftr-backend/middleware"
"github.com/Cawlumm/lyftr-backend/models"
@@ -43,6 +45,29 @@ func (h *Handler) UpdateSettings(c *gin.Context) {
utils.BadRequest(c, utils.BindMessage(err))
return
}
+ // Trimmed before it is measured, so " Carter " is a 6-character name rather than
+ // an 8-character one, and before it is stored, so the greeting never opens with a
+ // space. A name of nothing but whitespace trims to "" and so clears the name,
+ // which is the same thing an empty field does — there is no third state.
+ if req.DisplayName != nil {
+ trimmed := strings.TrimSpace(*req.DisplayName)
+ // The only characters a name may not contain, and the reasoning is narrow on
+ // purpose. Of eight comparable apps — Mastodon, Discourse, Gitea, Nextcloud,
+ // Immich, GitLab, FitTrackee, wger — none applies character-level validation to
+ // a display name, so emoji, scripts and punctuation are all deliberately
+ // allowed: this name is shown to nobody but its owner, and the spoofing that
+ // motivates filtering elsewhere needs a second person to deceive.
+ //
+ // Control characters are the exception, and not for security. TrimSpace has
+ // already taken the ones at either end, so what is left is interior: a newline
+ // inside a greeting is a layout bug, and a NUL in a text field is never
+ // intentional (Django rejects it on every CharField for that reason).
+ if strings.ContainsFunc(trimmed, unicode.IsControl) {
+ utils.BadRequest(c, "A name can't contain line breaks or other control characters.")
+ return
+ }
+ req.DisplayName = &trimmed
+ }
// Enforce the request tags (weight_unit oneof, targets gte=0) like every other
// controller — binding alone doesn't run them, so without this an invalid unit
// or a negative target would be persisted unchecked.
diff --git a/backend/db/migrations.go b/backend/db/migrations.go
index 7f73198..c08719b 100644
--- a/backend/db/migrations.go
+++ b/backend/db/migrations.go
@@ -89,6 +89,11 @@ func alterMigrations() {
// column changes nothing until a client reports a real zone.
ensureColumn("user_settings", "timezone", `ALTER TABLE user_settings ADD COLUMN timezone TEXT NOT NULL DEFAULT 'UTC'`)
+ // #170. '' rather than NULL because the settings upsert COALESCEs over NULL to mean
+ // "absent from this PATCH", so "no name" needs to be a different value from "unset".
+ // Every existing row reads '' and the clients fall back to the email, as before.
+ ensureColumn("user_settings", "display_name", `ALTER TABLE user_settings ADD COLUMN display_name TEXT NOT NULL DEFAULT ''`)
+
workoutProgramDayMigration()
normalizeWorkoutStartedAt()
@@ -844,7 +849,8 @@ CREATE TABLE IF NOT EXISTS user_settings (
protein_target INTEGER NOT NULL DEFAULT 150,
carb_target INTEGER NOT NULL DEFAULT 250,
fat_target INTEGER NOT NULL DEFAULT 65,
- timezone TEXT NOT NULL DEFAULT 'UTC'
+ timezone TEXT NOT NULL DEFAULT 'UTC',
+ display_name TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS exercises (
diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go
index 19a0ea6..eebb3da 100644
--- a/backend/db/migrations_test.go
+++ b/backend/db/migrations_test.go
@@ -743,3 +743,47 @@ func TestDedupeSavedFoods_isIdempotentAcrossBoots(t *testing.T) {
t.Fatalf("expected the single bookmark to survive two boots, got %d rows", n)
}
}
+
+// The display_name column (#170) is in the base schema, so a fresh install never
+// exercises the ALTER path that every EXISTING install takes. Dropping it back off
+// reproduces a pre-#170 database and checks the claim the migration comment makes:
+// existing rows come out with an empty name, which is what the clients read as unset.
+func TestAlterMigrations_addsDisplayNameToAnExistingSettingsRow(t *testing.T) {
+ setupMigrationTestDB(t)
+
+ if _, err := DB.Exec(`ALTER TABLE user_settings DROP COLUMN display_name`); err != nil {
+ t.Fatalf("make the schema look pre-#170: %v", err)
+ }
+
+ res, err := DB.Exec(`INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x')`)
+ if err != nil {
+ t.Fatalf("seed user: %v", err)
+ }
+ uid, _ := res.LastInsertId()
+ if _, err := DB.Exec(`INSERT INTO user_settings (user_id, weight_unit) VALUES (?, 'kg')`, uid); err != nil {
+ t.Fatalf("seed settings: %v", err)
+ }
+
+ alterMigrations()
+
+ var name, unit string
+ if err := DB.QueryRow(`SELECT display_name, weight_unit FROM user_settings WHERE user_id = ?`, uid).Scan(&name, &unit); err != nil {
+ t.Fatalf("read back: %v", err)
+ }
+ if name != "" {
+ t.Fatalf("display_name = %q, want empty for a row that predates the column", name)
+ }
+ // The surrounding row is untouched — the column was added, not rebuilt.
+ if unit != "kg" {
+ t.Fatalf("weight_unit = %q, want kg", unit)
+ }
+
+ // Second boot must be a no-op rather than an error.
+ alterMigrations()
+ if err := DB.QueryRow(`SELECT display_name FROM user_settings WHERE user_id = ?`, uid).Scan(&name); err != nil {
+ t.Fatalf("read back after a second boot: %v", err)
+ }
+ if name != "" {
+ t.Fatalf("display_name = %q after re-running migrations", name)
+ }
+}
diff --git a/backend/models/models.go b/backend/models/models.go
index 4cc3146..1bc1cc2 100644
--- a/backend/models/models.go
+++ b/backend/models/models.go
@@ -25,8 +25,21 @@ type UserSettings struct {
// "UTC" is the default and keeps the pre-existing behaviour for anyone who
// never sets one.
Timezone string `json:"timezone" db:"timezone"`
+ // What to call this person on screen (#170). Empty means they never set one and
+ // the clients fall back to the local part of their email, which is what every
+ // screen did before this existed.
+ DisplayName string `json:"display_name" db:"display_name"`
}
+// MaxDisplayNameLen bounds a self-chosen label that nothing indexes or joins on, so
+// its only job is to keep a pasted novel out of the greeting. Sixty is where the
+// comparable self-hosted apps land (Nextcloud and workout-tracker both cap at 64).
+//
+// The `max` in UpdateSettingsRequest's validate tag must match this number — a struct
+// tag cannot reference a constant — which is what TestUpdateSettings_rejectsOverlong-
+// DisplayName exists to keep true.
+const MaxDisplayNameLen = 60
+
// DefaultUserSettings is the single source of truth for a brand-new user's
// settings — returned when no row exists yet and used as the base a partial
// update merges onto. Must stay in sync with the user_settings column defaults.
@@ -39,6 +52,7 @@ func DefaultUserSettings(uid int64) UserSettings {
CarbTarget: 250,
FatTarget: 65,
Timezone: "UTC",
+ DisplayName: "",
}
}
@@ -379,6 +393,12 @@ type UpdateSettingsRequest struct {
// Validated by loading it, not by a pattern: the only definition of a usable
// zone is one the runtime can resolve (see controllers.ParseLocation).
Timezone *string `json:"timezone"`
+ // An explicit "" clears the name, which is why this one is not `required` and
+ // why `omitempty` is load-bearing: it skips the length check for the empty
+ // string, so clearing is always allowed however long the old name was. 60 is
+ // MaxDisplayNameLen — a tag cannot reference the constant, so the two are
+ // checked against each other by TestUpdateSettings_rejectsOverlongDisplayName.
+ DisplayName *string `json:"display_name" validate:"omitempty,max=60"`
}
type Program struct {
diff --git a/backend/stores/user.go b/backend/stores/user.go
index 3b9538c..f48cad1 100644
--- a/backend/stores/user.go
+++ b/backend/stores/user.go
@@ -89,14 +89,14 @@ func (s *UserStore) ChangePassword(uid int64, oldHash, newHash string) (int, err
return int(v), err
}
-const userSettingsSelect = `SELECT user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone FROM user_settings`
+const userSettingsSelect = `SELECT user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone, display_name FROM user_settings`
// GetSettings returns the user's settings row, or sql.ErrNoRows if none (the
// controller owns the default fallback).
func (s *UserStore) GetSettings(uid int64) (models.UserSettings, error) {
var st models.UserSettings
err := s.db.QueryRow(userSettingsSelect+` WHERE user_id = ?`, uid).
- Scan(&st.UserID, &st.WeightUnit, &st.CalorieTarget, &st.ProteinTarget, &st.CarbTarget, &st.FatTarget, &st.Timezone)
+ Scan(&st.UserID, &st.WeightUnit, &st.CalorieTarget, &st.ProteinTarget, &st.CarbTarget, &st.FatTarget, &st.Timezone, &st.DisplayName)
return st, err
}
@@ -112,16 +112,17 @@ func (s *UserStore) UpsertSettings(uid int64, req models.UpdateSettingsRequest)
d := models.DefaultUserSettings(uid)
var st models.UserSettings
err := s.db.QueryRow(
- `INSERT INTO user_settings (user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone)
- VALUES (?, COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?))
+ `INSERT INTO user_settings (user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone, display_name)
+ VALUES (?, COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?), COALESCE(?, ?))
ON CONFLICT(user_id) DO UPDATE SET
weight_unit = COALESCE(?, user_settings.weight_unit),
calorie_target = COALESCE(?, user_settings.calorie_target),
protein_target = COALESCE(?, user_settings.protein_target),
carb_target = COALESCE(?, user_settings.carb_target),
fat_target = COALESCE(?, user_settings.fat_target),
- timezone = COALESCE(?, user_settings.timezone)
- RETURNING user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone`,
+ timezone = COALESCE(?, user_settings.timezone),
+ display_name = COALESCE(?, user_settings.display_name)
+ RETURNING user_id, weight_unit, calorie_target, protein_target, carb_target, fat_target, timezone, display_name`,
uid,
req.WeightUnit, d.WeightUnit,
req.CalorieTarget, d.CalorieTarget,
@@ -129,8 +130,9 @@ func (s *UserStore) UpsertSettings(uid int64, req models.UpdateSettingsRequest)
req.CarbTarget, d.CarbTarget,
req.FatTarget, d.FatTarget,
req.Timezone, d.Timezone,
- req.WeightUnit, req.CalorieTarget, req.ProteinTarget, req.CarbTarget, req.FatTarget, req.Timezone,
- ).Scan(&st.UserID, &st.WeightUnit, &st.CalorieTarget, &st.ProteinTarget, &st.CarbTarget, &st.FatTarget, &st.Timezone)
+ req.DisplayName, d.DisplayName,
+ req.WeightUnit, req.CalorieTarget, req.ProteinTarget, req.CarbTarget, req.FatTarget, req.Timezone, req.DisplayName,
+ ).Scan(&st.UserID, &st.WeightUnit, &st.CalorieTarget, &st.ProteinTarget, &st.CarbTarget, &st.FatTarget, &st.Timezone, &st.DisplayName)
if err != nil {
return models.UserSettings{}, err
}
diff --git a/mobile/app/(tabs)/index.tsx b/mobile/app/(tabs)/index.tsx
index a07f6a8..994b17a 100644
--- a/mobile/app/(tabs)/index.tsx
+++ b/mobile/app/(tabs)/index.tsx
@@ -9,7 +9,7 @@ import {
import {
Activity, ArrowRight, BookOpen, ChevronRight, Dumbbell, Play, Plus, Scale, Timer, TrendingUp,
} from 'lucide-react-native'
-import { apiErrorMessage, isDailyStats, activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, sessionNameForDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay } from '@lyftr/shared'
+import { apiErrorMessage, isDailyStats, activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, sessionNameForDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay, nameInitial, lifterQuip } from '@lyftr/shared'
import { AppText, Card, ErrorState, IconButton, Label, Screen, SectionHeader, SegmentedControl } from '../../src/components/ui'
import { ExerciseImage } from '../../src/components/workouts/ExerciseImage'
import {
@@ -17,7 +17,7 @@ import {
} from '../../src/components/dashboard/DashboardCharts'
import { QuickWeighInSheet } from '../../src/components/dashboard/QuickWeighInSheet'
import { DashboardSkeleton } from '../../src/components/dashboard/DashboardSkeleton'
-import { client, useAuthStore, useSettingsStore, useWorkoutSession } from '../../src/lib/lyftr'
+import { client, useAuthStore, useDisplayName, useSettingsStore, useWorkoutSession } from '../../src/lib/lyftr'
import { muscleColor } from '../../src/utils/exerciseUtils'
import { useTheme } from '../../src/theme/useTheme'
@@ -175,6 +175,9 @@ export default function Dashboard() {
setRefreshing(false)
}, [load])
+ // Above the early returns — see web's Dashboard: a hook must run every render.
+ const username = useDisplayName()
+
if (loading) return <DashboardSkeleton />
if (error) {
@@ -278,8 +281,7 @@ export default function Dashboard() {
weight: displayWeight(l.weight, unit),
}))
- const username = user?.email?.split('@')[0] ?? 'there'
- const avatarInitial = (username[0] ?? 'U').toUpperCase()
+ const avatarInitial = nameInitial(username)
return (
<Screen>
@@ -295,7 +297,8 @@ export default function Dashboard() {
<Text className="font-sans-medium text-[11px] uppercase text-tx-muted" style={{ letterSpacing: 1 }}>
{format(now, 'EEEE, MMMM d')}
</Text>
- <AppText variant="title" className="mt-0.5" numberOfLines={1}>{greeting(now)}, {username}</AppText>
+ {/* No numberOfLines: a name is never clipped — see web's Dashboard. */}
+ <AppText variant="title" className="mt-0.5">{greeting(now)}, {username}</AppText>
</View>
<View className="flex-row items-center gap-2">
<Pressable
@@ -324,6 +327,9 @@ export default function Dashboard() {
</Pressable>
</View>
</View>
+ {/* Outside the header row: that row's left column is ~190px once Start and the
+ avatar take theirs, which wraps a sentence into four lines. */}
+ <AppText variant="caption" color="muted" className="-mt-3">{lifterQuip(user?.id ?? '')}</AppText>
{/* ── Active-session banner ── */}
{session ? (
diff --git a/mobile/app/(tabs)/settings/index.tsx b/mobile/app/(tabs)/settings/index.tsx
index b15e3fd..7888ec8 100644
--- a/mobile/app/(tabs)/settings/index.tsx
+++ b/mobile/app/(tabs)/settings/index.tsx
@@ -17,6 +17,7 @@ import {
Server,
Timer,
Trash2,
+ User,
} from 'lucide-react-native'
import { useAsyncAction,
memberSince,
@@ -45,7 +46,7 @@ import {
Toggle,
type ToastVariant,
} from '../../../src/components/ui'
-import { client, useAuthStore, useServerStore, useSettingsStore } from '../../../src/lib/lyftr'
+import { client, useAuthStore, useDisplayName, useServerStore, useSettingsStore } from '../../../src/lib/lyftr'
import { useTheme } from '../../../src/theme/useTheme'
const REST_PRESETS = [60, 90, 120, 180]
@@ -54,6 +55,7 @@ type ToastState = { variant: ToastVariant; title: string; description?: string }
export default function SettingsScreen() {
const user = useAuthStore((s) => s.user)
+ const name = useDisplayName()
const logout = useAuthStore((s) => s.logout)
const serverUrl = useServerStore((s) => s.serverUrl)
const setServerUrl = useServerStore((s) => s.setServerUrl)
@@ -198,7 +200,19 @@ export default function SettingsScreen() {
{/* Account */}
<SettingsGroup title="Account">
- <SettingsRow icon={Mail} label="Email" value={user?.email ?? '—'} />
+ {/* Shows what the greeting will actually say, so the fallback is visible
+ without opening anything: the email's local part until a name is set.
+ SettingsRow truncates its value to one line, which the dashboard heading
+ deliberately does not — a row is a fixed-height nav affordance and the
+ full name is one tap away, where the heading IS the content. */}
+ <SettingsRow
+ icon={User}
+ label="Name"
+ value={name}
+ chevron
+ onPress={() => router.push('/settings/name')}
+ />
+ <SettingsRow icon={Mail} label="Email" value={user?.email ?? '—'} divider />
<SettingsRow icon={CalendarDays} label="Member since" value={memberSince(user?.created_at)} divider />
<SettingsRow
icon={KeyRound}
diff --git a/mobile/app/(tabs)/settings/name.tsx b/mobile/app/(tabs)/settings/name.tsx
new file mode 100644
index 0000000..6148a7a
--- /dev/null
+++ b/mobile/app/(tabs)/settings/name.tsx
@@ -0,0 +1,114 @@
+import { useState } from 'react'
+import { Pressable, ScrollView, View } from 'react-native'
+import { router } from 'expo-router'
+import { ArrowLeft } from 'lucide-react-native'
+import { useAsyncAction, displayName, MAX_DISPLAY_NAME_LEN } from '@lyftr/shared'
+import {
+ Alert,
+ AppText,
+ Button,
+ Card,
+ Field,
+ Muted,
+ PageHeader,
+ Screen,
+} from '../../../src/components/ui'
+import { useAuthStore, useSettingsStore } from '../../../src/lib/lyftr'
+import { useTheme } from '../../../src/theme/useTheme'
+
+// Its own screen, laid out like password.tsx — back link, header, form on a card, Save
+// beside Cancel. Account rows are icon + label + value, so an editor belongs here rather
+// than as a form wedged into that group.
+export default function ChangeNameScreen() {
+ const { colors } = useTheme()
+ const user = useAuthStore((s) => s.user)
+ const settings = useSettingsStore((s) => s.settings)
+ const updateSettings = useSettingsStore((s) => s.update)
+
+ const [name, setName] = useState(settings.display_name ?? '')
+
+ const back = () => (router.canGoBack() ? router.back() : router.navigate('/settings'))
+
+ // Trimmed before sending so the field agrees with what comes back — the server trims
+ // too, and a field left holding " Carter " would show a value the record does not have.
+ //
+ // Returns to Settings with no confirmation, and that is the rule rather than an
+ // exception: a save is confirmed in proportion to its CONSEQUENCE, not to the shape of
+ // the screen it happened on.
+ //
+ // password.tsx stays and shows a card — changing it signs you out everywhere, which
+ // is a consequence worth spelling out in words
+ // targets stays and toasts — it saves in place, so nothing on screen changes
+ // to show that anything happened
+ // here pops back to a row already showing the new value, and a name has no
+ // consequence to warn anyone about
+ //
+ // So a new settings editor should ask what its save COSTS the person, not which of
+ // these three screens it most resembles.
+ const save = useAsyncAction(async () => {
+ await updateSettings({ display_name: name.trim() })
+ back()
+ }, "Couldn't save your name. Please try again.")
+
+ return (
+ <Screen>
+ <ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled">
+ <View className="gap-5 py-4">
+ <Pressable
+ onPress={back}
+ hitSlop={8}
+ className="flex-row items-center gap-1.5 self-start active:opacity-60"
+ >
+ <ArrowLeft size={16} color={colors.txMuted} />
+ <AppText variant="body" color="muted">Settings</AppText>
+ </Pressable>
+
+ <PageHeader
+ title="Name"
+ subtitle="The name the app greets you by."
+ />
+
+ <Card className="gap-4">
+ {/* No visible label — the header says "Name" one line above — but it still
+ needs an accessible one, or a screen reader announces only the email
+ placeholder, as if that were the current value. */}
+ <Field
+ accessibilityLabel="Name"
+ placeholder={displayName('', user?.email)}
+ value={name}
+ onChangeText={setName}
+ maxLength={MAX_DISPLAY_NAME_LEN}
+ autoCapitalize="words"
+ autoCorrect={false}
+ autoFocus
+ returnKeyType="done"
+ onSubmitEditing={() => { if (!save.busy) void save.run() }}
+ />
+ <Muted className="text-xs">
+ Leave it empty and we&apos;ll use your email instead.
+ </Muted>
+
+ {save.error ? <Alert variant="error">{save.error}</Alert> : null}
+
+ <View className="flex-row gap-2">
+ <Button
+ title="Save"
+ onPress={() => void save.run()}
+ loading={save.busy}
+ disabled={name.trim() === (settings.display_name ?? '')}
+ className="flex-1"
+ />
+ <Button
+ title="Cancel"
+ variant="secondary"
+ onPress={back}
+ disabled={save.busy}
+ className="flex-1"
+ />
+ </View>
+ </Card>
+ </View>
+ </ScrollView>
+ </Screen>
+ )
+}
diff --git a/mobile/src/lib/lyftr.ts b/mobile/src/lib/lyftr.ts
index 532b438..15ea233 100644
--- a/mobile/src/lib/lyftr.ts
+++ b/mobile/src/lib/lyftr.ts
@@ -4,6 +4,7 @@ import * as Localization from 'expo-localization'
import {
createClient,
createUseRestTimer,
+ createUseDisplayName,
createAuthStore,
createServerStore,
createSettingsStore,
@@ -48,6 +49,8 @@ export const useWorkoutSession = createWorkoutSession(storage)
// Rest-timer state derived from the session store above. Logic in @lyftr/shared.
export const useRestTimer = createUseRestTimer(useWorkoutSession)
+export const useDisplayName = createUseDisplayName(useSettingsStore, useAuthStore)
+
// The selected server's /info — version and whether it is taking new accounts. Same
// hook and same cache the web uses; only the store binding differs.
export const useServerInfo = () =>
diff --git a/packages/shared/src/hooks/useDisplayName.ts b/packages/shared/src/hooks/useDisplayName.ts
new file mode 100644
index 0000000..ad84e4c
--- /dev/null
+++ b/packages/shared/src/hooks/useDisplayName.ts
@@ -0,0 +1,22 @@
+import { displayName } from '../utils/profile'
+
+// Bound per app the way createUseRestTimer is, because the store instances live in each
+// app's lib/lyftr.ts rather than in this package.
+//
+// `displayName` collapsed four ad-hoc derivations of a name from an email into one
+// function (#170) — but the four CALL SITES still had to wire the same two fields from
+// two different stores, which is the same drift one level up: a fifth screen that passes
+// only the email silently goes back to pre-#170 behaviour and nothing fails. This is the
+// wiring, written once.
+type SettingsHook = <T>(selector: (state: { settings: { display_name?: string } }) => T) => T
+type AuthHook = <T>(selector: (state: { user?: { email?: string } | null }) => T) => T
+
+export function createUseDisplayName(useSettingsStore: SettingsHook, useAuthStore: AuthHook) {
+ return function useDisplayName(): string {
+ // Selected narrowly rather than taking whole stores: the greeting re-renders on a
+ // name or email change, not on every target or weight-unit write.
+ const name = useSettingsStore((s) => s.settings.display_name)
+ const email = useAuthStore((s) => s.user?.email)
+ return displayName(name, email)
+ }
+}
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 8faec45..5efa017 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -22,12 +22,14 @@ export * from './utils/food'
export * from './utils/dashboard'
export * from './utils/version'
export * from './utils/passwordRules'
+export * from './utils/profile'
export * from './theme/tokens'
export * from './hooks/useAsyncAction'
export * from './hooks/useCountdown'
export * from './hooks/useNumericText'
export * from './hooks/useElapsedSeconds'
export * from './hooks/useRestTimer'
+export * from './hooks/useDisplayName'
export * from './hooks/useServerList'
export * from './hooks/useServerInfo'
export * from './hooks/useFavorites'
diff --git a/packages/shared/src/stores/settings.ts b/packages/shared/src/stores/settings.ts
index eea393f..7b1df15 100644
--- a/packages/shared/src/stores/settings.ts
+++ b/packages/shared/src/stores/settings.ts
@@ -36,6 +36,7 @@ const BASE_DEFAULTS: types.UserSettings = {
rest_enabled: true,
rest_seconds_default: 90,
timezone: 'UTC',
+ display_name: '',
}
export interface SettingsStore {
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index 779a249..620e798 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -20,6 +20,12 @@ export interface UserSettings {
rest_seconds_default?: number // default rest seconds, seeds new exercises
/** IANA zone the server buckets this user's day-scoped data in. */
timezone: string
+ /**
+ * What the person wants to be called (#170). Empty means they never set one and
+ * the screens fall back to their email — see `displayName`. Optional because a
+ * settings payload from an instance older than this field simply omits it.
+ */
+ display_name?: string
}
export interface Exercise {
diff --git a/packages/shared/src/utils/dashboard.test.ts b/packages/shared/src/utils/dashboard.test.ts
index 56c9681..b11904a 100644
--- a/packages/shared/src/utils/dashboard.test.ts
+++ b/packages/shared/src/utils/dashboard.test.ts
@@ -1,4 +1,4 @@
-import { greeting, muscleHex, muscleRoast, nextStartableDay } from './dashboard'
+import { greeting, lifterQuip, muscleHex, muscleRoast, nextStartableDay } from './dashboard'
import type { Program } from '../types'
describe('muscleHex', () => {
@@ -88,3 +88,36 @@ describe('greeting', () => {
expect(greeting(at(21))).toBe('Good evening')
})
})
+describe('lifterQuip', () => {
+ // The whole point: the dashboard re-renders on every fetch and refresh, so the same
+ // account on the same day has to keep answering the same line.
+ it('is stable for an account and a day', () => {
+ const first = lifterQuip(7, '2026-10-06')
+ for (let i = 0; i < 50; i++) expect(lifterQuip(7, '2026-10-06')).toBe(first)
+ })
+
+ it('moves on when the day does', () => {
+ const week = ['03', '04', '05', '06', '07', '08', '09']
+ .map((d) => lifterQuip(7, `2026-10-${d}`))
+ expect(new Set(week).size).toBeGreaterThan(1)
+ })
+
+ // Not keyed on the name: it arrives late from a settings fetch, so a line that moved
+ // when it landed would flicker on every cold load.
+ it('does not depend on what the person is called', () => {
+ expect(lifterQuip(7, '2026-10-06')).toBe(lifterQuip(7, '2026-10-06'))
+ })
+
+ it('always answers with a line, whatever the account', () => {
+ for (const id of ['', 0, 7, 'anonymous', '日本', 'x'.repeat(500)]) {
+ const quip = lifterQuip(id, '2026-10-06')
+ expect(typeof quip).toBe('string')
+ expect(quip.length).toBeGreaterThan(0)
+ }
+ })
+
+ // Reads the real clock rather than a passed day — the shape both dashboards call.
+ it('needs only an account id', () => {
+ expect(typeof lifterQuip(7)).toBe('string')
+ })
+})
diff --git a/packages/shared/src/utils/dashboard.ts b/packages/shared/src/utils/dashboard.ts
index 0dce70d..ac3f8bd 100644
--- a/packages/shared/src/utils/dashboard.ts
+++ b/packages/shared/src/utils/dashboard.ts
@@ -1,5 +1,6 @@
import type { Program, ProgramDay } from '../types'
import { isDayStartable, todaysDay } from './programUtils'
+import { todayStr } from './dateUtils'
// Per-muscle accent for the dashboard's training-split chart. Hex rather than theme
// tokens for the same reason as MACRO_COLORS: both platforms hand these to drawing
@@ -48,6 +49,45 @@ export function greeting(now: Date): string {
return 'Good evening'
}
+// The line under the greeting. Same voice as MUSCLE_ROAST above — dry, second person,
+// on the lifter's side. None of these are about how the person looks, and none of them
+// scold: this is the first thing they read every time they open the app, and a nag you
+// cannot dismiss stops being funny on about day three.
+const LIFTER_QUIPS: string[] = [
+ 'The bar does not care how you feel about it.',
+ 'Progressive overload: the only pyramid scheme that works.',
+ 'Nobody has ever regretted the warm-up.',
+ 'The hardest rep is the one that gets you off the couch.',
+ 'Form first. Ego lifts are for the parking lot.',
+ 'Legs are not optional. They are just unpopular.',
+ 'Chalk is not a personality. It helps, though.',
+ 'You cannot out-train a log you never fill in.',
+ 'Deload weeks count. Reluctantly.',
+ 'Mirror check later. Barbell now.',
+ 'Half reps, full lies.',
+ 'The only bad set is the one you talked yourself out of.',
+ 'Somewhere a squat rack is holding a coat. Not yours.',
+ 'Showing up is the part most people skip.',
+ 'Protein is not optional. Neither is sleep.',
+ 'Rest is part of the plan, not a gap in it.',
+]
+
+// Derived, not random: the dashboard re-renders on every fetch, refresh and tab return,
+// so Math.random() would rewrite the sentence while it was being read.
+//
+// Keyed on the account id, not the shown name — the name arrives from a settings fetch
+// the dashboard deliberately does not await, so keying on it painted one line and swapped
+// it the moment settings landed, and re-rolled whenever someone renamed themselves.
+//
+// The day is composed here rather than by each caller, so the two apps cannot drift into
+// showing different lines for the same person on the same day. Tests pass one explicitly.
+export function lifterQuip(accountId: string | number, day: string = todayStr()): string {
+ const key = `${day}:${accountId}`
+ let sum = 0
+ for (let i = 0; i < key.length; i++) sum += key.charCodeAt(i)
+ return LIFTER_QUIPS[sum % LIFTER_QUIPS.length]
+}
+
// The "up next" card: the first program whose day-for-today actually has exercises.
// Programs are scanned in order, so an earlier program wins a tie — matching the
// order they're listed on the Programs screen.
diff --git a/packages/shared/src/utils/profile.test.ts b/packages/shared/src/utils/profile.test.ts
new file mode 100644
index 0000000..36b4abe
--- /dev/null
+++ b/packages/shared/src/utils/profile.test.ts
@@ -0,0 +1,48 @@
+import { displayName, nameInitial } from './profile'
+
+describe('displayName', () => {
+ it('prefers the name the person chose', () => {
+ expect(displayName('Carter', '[email protected]')).toBe('Carter')
+ })
+
+ it('falls back to the local part of the email when no name is set', () => {
+ expect(displayName('', '[email protected]')).toBe('carter')
+ expect(displayName(undefined, '[email protected]')).toBe('carter')
+ })
+
+ // A row written before the server trimmed, or a settings payload from an older
+ // instance; either way the greeting must not open with a space.
+ it('trims a stored name, and treats a whitespace-only one as unset', () => {
+ expect(displayName(' Carter ', '[email protected]')).toBe('Carter')
+ expect(displayName(' ', '[email protected]')).toBe('carter')
+ })
+
+ // The empty-user window while the first /me is in flight.
+ it('reads as a sentence when there is neither name nor email', () => {
+ expect(displayName(undefined, undefined)).toBe('there')
+ expect(displayName('', '')).toBe('there')
+ })
+
+ it('keeps a name that happens to contain an @', () => {
+ expect(displayName('@carter', '[email protected]')).toBe('@carter')
+ })
+})
+
+describe('nameInitial', () => {
+ it('is the first letter of whatever displayName returned', () => {
+ expect(nameInitial(displayName('Carter', '[email protected]'))).toBe('C')
+ expect(nameInitial(displayName('', '[email protected]'))).toBe('C')
+ })
+
+ // Not every name starts with a Latin letter, and toUpperCase must not mangle one.
+ it('leaves a non-cased first character alone', () => {
+ expect(nameInitial('日本')).toBe('日')
+ })
+
+ // The name is free text, so it can start outside the BMP. charAt(0) would return half
+ // a surrogate pair here and the avatar would render a replacement glyph.
+ it('takes a whole code point, not half a surrogate pair', () => {
+ expect(nameInitial('🦍 Carter')).toBe('🦍')
+ expect(nameInitial('🦍 Carter')).toHaveLength(2) // one code point, two UTF-16 units
+ })
+})
diff --git a/packages/shared/src/utils/profile.ts b/packages/shared/src/utils/profile.ts
new file mode 100644
index 0000000..7f37536
--- /dev/null
+++ b/packages/shared/src/utils/profile.ts
@@ -0,0 +1,29 @@
+// An independently maintained mirror of models.MaxDisplayNameLen. Not an identity: Go's
+// `max` counts runes and these fields count UTF-16 units, so the client cuts off earlier
+// for astral characters — the safe direction, never a 400 on a name it let you finish.
+export const MAX_DISPLAY_NAME_LEN = 60
+
+// What to call the person on screen: their chosen name, else the local part of their
+// email, else a word that still reads as a sentence. One copy, imported by both apps, so
+// the sidebar and the greeting can never disagree about who is signed in — before #170
+// four places derived this from the email and three of them disagreed about the fallback.
+//
+// 'there' covers the empty-user window while the first /me is in flight; without it the
+// greeting reads "Good morning, " with nothing after the comma.
+export function displayName(name?: string, email?: string): string {
+ const given = (name ?? '').trim()
+ if (given) return given
+ const local = (email ?? '').split('@')[0].trim()
+ return local || 'there'
+}
+
+// The avatar letter. Takes what displayName already returned rather than deriving it
+// again, so the circle and the name beside it always start with the same letter.
+//
+// Spread rather than charAt(0): a name is free text bounded only by length, so it can
+// begin with an emoji, and charAt returns half a surrogate pair — which toUpperCase
+// leaves alone and every avatar then renders as a replacement glyph. The string iterator
+// yields whole code points.
+export function nameInitial(name: string): string {
+ return ([...name][0] ?? '').toUpperCase()
+}
diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsx
index bb3c769..d1e80ff 100644
--- a/web/src/components/Layout.tsx
+++ b/web/src/components/Layout.tsx
@@ -9,7 +9,8 @@ import { useAuthStore } from '../stores/auth'
import { useTheme } from '../hooks/useTheme'
import { useWorkoutSession } from '../stores/workoutSession'
import { useRestTimer } from '../hooks/useRestTimer'
-import { fmtClock, formatElapsed, useElapsedSeconds } from '@lyftr/shared'
+import { fmtClock, formatElapsed, useElapsedSeconds, nameInitial } from '@lyftr/shared'
+import { useDisplayName } from '../lib/lyftr'
import { useSettingsStore, weightShort } from '../stores/settings'
import GymModeWorkout from '../pages/GymModeWorkout'
import RestTimerBanner from './RestTimerBanner'
@@ -92,8 +93,8 @@ function UserMenu() {
return () => document.removeEventListener('mousedown', handler)
}, [])
- const username = user?.email?.split('@')[0] ?? 'U'
- const initial = username[0].toUpperCase()
+ const username = useDisplayName()
+ const initial = nameInitial(username)
return (
<div ref={ref} className="relative">
diff --git a/web/src/lib/lyftr.ts b/web/src/lib/lyftr.ts
index da84ae6..d619743 100644
--- a/web/src/lib/lyftr.ts
+++ b/web/src/lib/lyftr.ts
@@ -1,6 +1,7 @@
import {
createAuthStore,
createUseRestTimer,
+ createUseDisplayName,
createClient,
createServerStore,
createSettingsStore,
@@ -94,3 +95,5 @@ export const hydrateStores = async () => {
// Rest-timer state derived from the session store above. The logic lives in
// @lyftr/shared; this binds it to web's store instance.
export const useRestTimer = createUseRestTimer(useWorkoutSession)
+
+export const useDisplayName = createUseDisplayName(useSettingsStore, useAuthStore)
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index ac3ad72..da9f4fb 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -17,7 +17,8 @@ import { workoutAPI, foodAPI, weightAPI, programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import { useAuthStore } from '../stores/auth'
import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'
-import { apiErrorMessage, isDailyStats, workoutDay, entryDay, types, activeSessionExercisesForDay, dayLabel, sessionNameForDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay } from '@lyftr/shared'
+import { useDisplayName } from '../lib/lyftr'
+import { apiErrorMessage, isDailyStats, workoutDay, entryDay, types, activeSessionExercisesForDay, dayLabel, sessionNameForDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay, lifterQuip } from '@lyftr/shared'
import { useNavigate, Link } from 'react-router-dom'
import { muscleColor } from '../utils/exerciseUtils'
@@ -145,6 +146,10 @@ export default function Dashboard() {
.finally(() => setLoading(false))
}, [TODAY, retryKey, fetchSettings])
+ // Above the early returns: it is a hook now, so it has to run on every render or the
+ // hook order changes between the loading branch and the loaded one.
+ const username = useDisplayName()
+
if (loading) return <Loading />
// The dashboard is nothing but other requests' answers, so when the load fails there
@@ -255,8 +260,6 @@ export default function Dashboard() {
weight: displayWeight(l.weight, settings.weight_unit),
}))
- const username = user?.email?.split('@')[0] ?? 'there'
-
return (
<div className="space-y-4 animate-slide-up">
@@ -266,9 +269,15 @@ export default function Dashboard() {
<p className="text-[11px] text-tx-muted uppercase tracking-wider font-medium">
{format(TODAY, 'EEEE, MMMM d')}
</p>
- <h1 className="font-display font-bold text-2xl text-tx-primary mt-0.5">
+ {/* Never clipped: a name is the one string here that is the user's own, and
+ its length is bounded at the input instead (MaxDisplayNameLen). text-balance
+ breaks it at the comma rather than mid-surname; browsers without it just
+ wrap. Mobile wraps too, but gets no text-balance and deliberately no
+ leading-tight — an imposed lineHeight clips descenders on iOS (ui/Field.tsx). */}
+ <h1 className="font-display font-bold text-2xl text-tx-primary mt-0.5 leading-tight text-balance">
{greeting(TODAY)}, {username}
</h1>
+ <p className="text-xs text-tx-muted mt-1">{lifterQuip(user?.id ?? '')}</p>
</div>
<button
onClick={() => navigate('/workout/start')}
diff --git a/web/src/pages/Settings.test.tsx b/web/src/pages/Settings.test.tsx
new file mode 100644
index 0000000..fa6c4c2
--- /dev/null
+++ b/web/src/pages/Settings.test.tsx
@@ -0,0 +1,140 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { MemoryRouter } from 'react-router-dom'
+import Settings from './Settings'
+
+// What these pin is the shape of the WRITES this page makes, which is where #170 went
+// wrong twice. The name began life inside `formData`, and the only button that commits
+// `formData` is labelled "Save targets", sits in another section, and disappears
+// entirely when the settings read fails — so the field could not be saved on purpose and
+// could be saved by accident, because the weight-unit toggle sent the whole form.
+//
+// Hence: every assertion below is about which keys reach `update`.
+
+const update = vi.fn()
+const fetchSettings = vi.fn()
+
+let state: Record<string, unknown>
+
+const makeState = (over: Record<string, unknown> = {}) => ({
+ settings: {
+ user_id: 1,
+ weight_unit: 'lbs',
+ calorie_target: 2000,
+ protein_target: 150,
+ carb_target: 250,
+ fat_target: 65,
+ timezone: 'UTC',
+ display_name: '',
+ workout_layout: 'list',
+ rest_enabled: true,
+ rest_seconds_default: 90,
+ },
+ loaded: true,
+ loadFailed: false,
+ update,
+ fetch: fetchSettings,
+ setWorkoutLayout: vi.fn(),
+ setRestEnabled: vi.fn(),
+ setRestSeconds: vi.fn(),
+ ...over,
+})
+
+vi.mock('../stores/settings', () => ({
+ useSettingsStore: Object.assign(
+ (selector?: (s: unknown) => unknown) => (selector ? selector(state) : state),
+ { getState: () => state },
+ ),
+}))
+
+vi.mock('../stores/auth', () => ({
+ useAuthStore: () => ({
+ user: { id: 1, email: '[email protected]', created_at: '2026-07-01T00:00:00Z' },
+ logout: vi.fn(),
+ }),
+}))
+
+vi.mock('../stores/server', () => ({ useServerStore: () => '' }))
+vi.mock('../hooks/useServerInfo', () => ({ useServerInfo: () => null }))
+vi.mock('../hooks/useTheme', () => ({ useTheme: () => ({ theme: 'dark', toggleTheme: vi.fn() }) }))
+vi.mock('../components/ServerSettings', () => ({ default: () => null }))
+vi.mock('../services/api', () => ({
+ exerciseAPI: {
+ cacheStatus: vi.fn().mockResolvedValue({ count: 0 }),
+ refreshCache: vi.fn(),
+ clearCacheOnServer: vi.fn(),
+ },
+ userAPI: { deleteAccount: vi.fn() },
+}))
+
+const renderPage = () => render(<MemoryRouter><Settings /></MemoryRouter>)
+const nameField = () => screen.getByLabelText('Name')
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ state = makeState()
+ update.mockResolvedValue(undefined)
+})
+
+describe('the Name row', () => {
+ it('offers no Save until the name actually changes', async () => {
+ renderPage()
+ await waitFor(() => expect(nameField()).toBeTruthy())
+
+ expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()
+
+ fireEvent.change(nameField(), { target: { value: 'Carter' } })
+ expect(screen.getByRole('button', { name: 'Save' })).toBeTruthy()
+ })
+
+ // The regression: it must send ONLY its own field. Sending the whole form is how the
+ // unit toggle used to commit a half-typed name.
+ it('sends only display_name, trimmed', async () => {
+ renderPage()
+ await waitFor(() => expect(nameField()).toBeTruthy())
+
+ fireEvent.change(nameField(), { target: { value: ' Carter ' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+
+ await waitFor(() => expect(update).toHaveBeenCalledTimes(1))
+ expect(update).toHaveBeenCalledWith({ display_name: 'Carter' })
+ })
+
+ // The other half of the same bug, from the other direction.
+ it('does not carry a half-typed name when the weight unit is changed', async () => {
+ renderPage()
+ await waitFor(() => expect(nameField()).toBeTruthy())
+
+ fireEvent.change(nameField(), { target: { value: 'Half' } })
+ fireEvent.click(screen.getByRole('button', { name: 'kg' }))
+
+ await waitFor(() => expect(update).toHaveBeenCalledTimes(1))
+ expect(update).toHaveBeenCalledWith({ weight_unit: 'kg' })
+ })
+
+ // `loadFailed` means the settings on screen are substitutes, not the user's. Offering
+ // to write a name over one we failed to read is the silent-default-substitution shape
+ // the rest of this page was hardened against.
+ it('will not offer to overwrite a name it could not read', async () => {
+ state = makeState({ loadFailed: true })
+ renderPage()
+
+ await waitFor(() => expect(screen.getByText(/Couldn't load your name/)).toBeTruthy())
+ expect(screen.queryByLabelText('Name')).toBeNull()
+ expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()
+ })
+
+ // The in-flight "Saving…" state is deliberately NOT tested here. It only appears
+ // because the real store applies its patch optimistically before awaiting, which makes
+ // the row stop being dirty mid-write — and this file's store is a plain stub that never
+ // re-renders, so any assertion about it passes whether the fix is present or not. It is
+ // verified against the real store in a browser with the response delayed instead.
+ it('names the field and its help text for a screen reader', async () => {
+ renderPage()
+ await waitFor(() => expect(nameField()).toBeTruthy())
+
+ const described = nameField().getAttribute('aria-describedby')
+ expect(described).toBeTruthy()
+ expect(document.getElementById(described!)?.textContent).toMatch(/use your email/)
+ })
+})
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 9be14b3..d709460 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react'
-import { apiErrorMessage, useAsyncAction, memberSince } from '@lyftr/shared'
+import { apiErrorMessage, useAsyncAction, memberSince, displayName, MAX_DISPLAY_NAME_LEN } from '@lyftr/shared'
import { useAuthStore } from '../stores/auth'
import { useServerStore } from '../stores/server'
import { useServerInfo } from '../hooks/useServerInfo'
@@ -36,12 +36,15 @@ import {
// `descriptionTone` lets a row report its own failure in place of its description. A row
// like the unit toggle sits far down a long page, and the page-level banner is at the very
// top — measured at 809px above the control, off-screen, which is the same as saying nothing.
-function SettingRow({ label, description, descriptionTone, children }: { label: string; description?: string; descriptionTone?: 'error'; children: React.ReactNode }) {
+// `descriptionId` lets a control inside the row point at the description with
+// aria-describedby. Without it the description is visible-only: a screen reader names the
+// field and never reads the sentence that says what clearing it does.
+function SettingRow({ label, description, descriptionTone, descriptionId, children }: { label: string; description?: string; descriptionTone?: 'error'; descriptionId?: string; children: React.ReactNode }) {
return (
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-4">
<div className="min-w-[9rem] flex-1">
<p className="text-sm font-medium text-tx-primary">{label}</p>
- {description && <p className={`text-xs mt-0.5 ${descriptionTone === 'error' ? 'text-error-400' : 'text-tx-muted'}`}>{description}</p>}
+ {description && <p id={descriptionId} className={`text-xs mt-0.5 ${descriptionTone === 'error' ? 'text-error-400' : 'text-tx-muted'}`}>{description}</p>}
</div>
{/* break-words so a long unbroken value wraps instead of overflowing the card. */}
<div className="min-w-0 max-w-full flex-shrink-0 break-words">{children}</div>
@@ -87,6 +90,11 @@ export default function Settings() {
// right now." were the same small grey text — a failure that does not read as one.
const [seedMsg, setSeedMsg] = useState<{ text: string; failed: boolean } | null>(null)
+ // Deliberately NOT in formData: the only button that commits formData is labelled
+ // "Save targets", lives in Goals & Units ~900px below, and is removed entirely when
+ // the settings read fails. A name parked in there has no honest way to be saved.
+ const [name, setName] = useState(storedSettings.display_name ?? '')
+
const [formData, setFormData] = useState({
weight_unit: storedSettings.weight_unit,
calorie_target: storedSettings.calorie_target,
@@ -112,6 +120,7 @@ export default function Settings() {
try {
await fetchSettings()
const s = useSettingsStore.getState().settings
+ setName(s.display_name ?? '')
setFormData({
weight_unit: s.weight_unit,
calorie_target: s.calorie_target,
@@ -173,7 +182,7 @@ export default function Settings() {
setFormData(prev => ({ ...prev, weight_unit: unit }))
setUnitError(null)
try {
- await updateSettings({ ...formData, weight_unit: unit })
+ await updateSettings({ weight_unit: unit })
} catch (err) {
setFormData(prev => ({ ...prev, weight_unit: previous }))
setUnitError(apiErrorMessage(err, "Couldn't change the weight unit."))
@@ -199,6 +208,19 @@ export default function Settings() {
await logout()
}, 'Could not delete account')
+ // Its own commit, like handleUnitChange above and unlike the targets block: one
+ // scoped patch, trimmed at the call site the way mobile's screen does it, and the
+ // error reported in the row rather than in a banner at the top of a long page.
+ const storedName = storedSettings.display_name ?? ''
+ const nameDirty = name.trim() !== storedName
+ const saveName = useAsyncAction(async () => {
+ const display_name = name.trim()
+ await updateSettings({ display_name })
+ setName(display_name)
+ }, "Couldn't save your name.")
+
+ const handleSaveName = () => { void saveName.run() }
+
const handleSave = () => {
setSuccess(false)
void save.run()
@@ -234,6 +256,48 @@ export default function Settings() {
{/* Account */}
<Section title="Account">
+ {/* aria-label because SettingRow's label is a <p>, not a <label>, so the row
+ text names nothing — the same reason the custom-rest input carries one.
+ autoComplete is "nickname", not "name": this is a chosen label, and "name"
+ invites the browser to fill in a legal name. */}
+ <SettingRow
+ label="Name"
+ description={settingsLoadFailed
+ ? "Couldn't load your name, so we won't offer to overwrite it."
+ : saveName.error || "The name the app greets you by. Leave it empty and we'll use your email instead."}
+ descriptionTone={settingsLoadFailed || saveName.error ? 'error' : undefined}
+ descriptionId="name-help"
+ >
+ {settingsLoadFailed ? (
+ <span className="text-sm text-tx-muted">—</span>
+ ) : (
+ <div className="flex items-center gap-2">
+ <input
+ type="text"
+ aria-label="Name"
+ aria-describedby="name-help"
+ value={name}
+ onChange={e => { setName(e.target.value); saveName.reset() }}
+ onKeyDown={e => { if (e.key === 'Enter' && nameDirty) handleSaveName() }}
+ maxLength={MAX_DISPLAY_NAME_LEN}
+ placeholder={displayName('', user?.email)}
+ className="input text-sm py-2 w-40 sm:w-44"
+ autoComplete="nickname"
+ />
+ {/* Only while there is something to save, so the row carries no permanent
+ chrome for a field most people touch once — but kept while the write is
+ in flight, because the store applies the patch optimistically BEFORE it
+ awaits, so nameDirty goes false on the very next render and the button
+ would otherwise vanish the instant it was clicked, taking its own
+ "Saving…" state with it. */}
+ {(nameDirty || saveName.busy) && (
+ <button onClick={handleSaveName} disabled={saveName.busy} className="btn-secondary btn-sm flex-shrink-0">
+ {saveName.busy ? 'Saving…' : 'Save'}
+ </button>
+ )}
+ </div>
+ )}
+ </SettingRow>
<SettingRow label="Email" description="Your login email address">
<span className="text-sm text-tx-muted font-mono">{user?.email}</span>
</SettingRow>