Files
otunes/apps/mobile/app/(app)/(tabs)/home/settings.tsx
T
joshuafhiggins 9da758b196 perf: optimize app rendering and data loading (#18)
- Virtualize mobile lists and defer queue loading
- Split playback state from actions to reduce rerenders
- Skip invalid or unnecessary Convex queries

Reviewed-on: #18
2026-09-05 16:35:37 -04:00

886 lines
23 KiB
TypeScript

import { Ionicons } from "@expo/vector-icons"
import { useAction, useMutation, useQuery } from "convex/react"
import { Image } from "expo-image"
import * as ImagePicker from "expo-image-picker"
import { useRouter } from "expo-router"
import { useState } from "react"
import {
Pressable,
ScrollView,
StyleSheet,
Switch,
Text,
View,
} from "react-native"
import type { StyleProp, ViewStyle } from "react-native"
import { contentBottomInset } from "@/components/player"
import { Button, Input, LoadingView } from "@/components/ui/primitives"
import { useInvalidateAuthSession } from "@/contexts/convex-auth-session"
import { useServerConfig } from "@/contexts/server-config"
import { initialsFromName } from "@/lib/format"
import { signOutToSignIn } from "@/lib/session"
import { radius, spacing, useThemeColors } from "@/lib/theme"
import { showError, showSuccess } from "@/lib/toast"
import type { PlaybackQuality } from "@/lib/urls"
import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
type Section = "profile" | "quality" | "library" | "users"
type CurrentUser = {
_id: Id<"users">
name: string
image?: string
email: string
isAdmin?: boolean
playbackQuality?: PlaybackQuality
preferAtmos?: boolean
}
type AdminUser = {
_id: Id<"users">
name: string
email: string
isAdmin?: boolean
}
type SectionConfig = {
id: Section
label: string
icon: React.ComponentProps<typeof Ionicons>["name"]
admin?: boolean
}
const QUALITY_OPTIONS: {
value: PlaybackQuality
label: string
description: string
}[] = [
{ value: "low", label: "Low", description: "AAC 64kb/s" },
{ value: "medium", label: "Medium", description: "AAC 128kb/s" },
{ value: "high", label: "High", description: "AAC 256kb/s" },
{ value: "lossless", label: "Lossless", description: "ALAC or FLAC" },
]
const SECTIONS: SectionConfig[] = [
{ id: "profile", label: "Profile", icon: "person-circle-outline" },
{ id: "quality", label: "Playback", icon: "volume-high-outline" },
{ id: "library", label: "Library", icon: "library-outline", admin: true },
{ id: "users", label: "Users", icon: "people-outline", admin: true },
]
export default function SettingsScreen() {
const colors = useThemeColors()
const router = useRouter()
const user = useQuery(api.auth.currentUser)
const { invalidateSession } = useInvalidateAuthSession()
const { clearServer } = useServerConfig()
const [section, setSection] = useState<Section>("profile")
const allUsers = useQuery(
api.users.listUsers,
user?.isAdmin === true && section === "users" ? {} : "skip"
)
if (!user) {
return <LoadingView />
}
const isAdmin = user.isAdmin === true
const visibleSections = SECTIONS.filter((item) => !item.admin || isAdmin)
async function handleSignOut() {
await signOutToSignIn(router, invalidateSession)
}
async function handleChangeServer() {
await invalidateSession()
await clearServer()
router.replace("/server")
}
return (
<ScrollView
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[
styles.container,
{ paddingBottom: contentBottomInset + spacing.xl },
]}
contentInsetAdjustmentBehavior="automatic"
>
<View style={[styles.pillGroup, { backgroundColor: colors.card }]}>
{visibleSections.map((item) => {
const selected = section === item.id
return (
<Pressable
key={item.id}
accessibilityLabel={item.label}
accessibilityRole="button"
accessibilityState={{ selected }}
onPress={() => setSection(item.id)}
style={[
styles.pill,
{ backgroundColor: selected ? colors.primary : "transparent" },
]}
>
<Ionicons
name={item.icon}
size={26}
color={
selected ? colors.primaryForeground : colors.mutedForeground
}
/>
</Pressable>
)
})}
</View>
{section === "profile" ? <ProfileSection user={user} /> : null}
{section === "quality" ? <QualitySection user={user} /> : null}
{section === "library" && isAdmin ? <LibrarySection /> : null}
{section === "users" && isAdmin && allUsers ? (
<UsersSection users={allUsers} currentUserId={user._id} />
) : null}
{section === "profile" ? (
<SessionSection
onChangeServer={() => void handleChangeServer()}
onSignOut={() => void handleSignOut()}
/>
) : null}
</ScrollView>
)
}
function ProfileSection({ user }: { user: CurrentUser }) {
const colors = useThemeColors()
const updateName = useMutation(api.users.updateProfileName)
const updateEmail = useMutation(api.users.updateProfileEmail)
const updateImage = useMutation(api.users.updateProfileImage)
const updatePassword = useAction(api.users.updateOwnPassword)
const [name, setName] = useState(user.name)
const [email, setEmail] = useState(user.email)
const [newPassword, setNewPassword] = useState("")
const [confirmPassword, setConfirmPassword] = useState("")
const [changingPassword, setChangingPassword] = useState(false)
async function pickImage() {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ["images"],
quality: 0.8,
base64: true,
})
if (result.canceled || !result.assets[0]?.base64) return
const mime = result.assets[0].mimeType ?? "image/jpeg"
try {
await updateImage({
image: `data:${mime};base64,${result.assets[0].base64}`,
})
showSuccess("Profile photo updated")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update photo"
)
}
}
async function removeImage() {
try {
await updateImage({ image: null })
showSuccess("Profile photo removed")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to remove photo"
)
}
}
async function handlePasswordChange() {
if (newPassword !== confirmPassword) {
showError("Passwords do not match")
return
}
setChangingPassword(true)
try {
await updatePassword({ newPassword })
setNewPassword("")
setConfirmPassword("")
showSuccess("Password updated")
} catch (error) {
showError(
error instanceof Error ? error.message : "Failed to update password"
)
} finally {
setChangingPassword(false)
}
}
return (
<>
<SettingsCard
title="Profile Photo"
subtitle="This is the avatar shown in the app header and shared spaces."
>
<View style={styles.photoRow}>
<ProfileAvatar user={user} size={76} />
<View style={styles.photoActions}>
<Button
title="Choose Photo"
variant="secondary"
icon="image-outline"
onPress={() => void pickImage()}
/>
{user.image ? (
<Button
title="Remove"
variant="ghost"
icon="trash-outline"
onPress={() => void removeImage()}
/>
) : null}
</View>
</View>
</SettingsCard>
<SettingsCard
title="Account Details"
subtitle="Keep your profile information up to date."
>
<Field label="Name">
<Input value={name} onChangeText={setName} placeholder="Name" />
</Field>
<Button
title="Save Name"
variant="secondary"
disabled={name.trim() === user.name}
onPress={() =>
void updateName({ name: name.trim() }).then(
() => showSuccess("Name updated"),
(error: Error) => showError(error.message)
)
}
/>
<View style={[styles.divider, { backgroundColor: colors.border }]} />
<Field label="Email">
<Input
value={email}
onChangeText={setEmail}
placeholder="Email"
autoCapitalize="none"
keyboardType="email-address"
/>
</Field>
<Button
title="Save Email"
variant="secondary"
disabled={email.trim() === user.email}
onPress={() =>
void updateEmail({ email: email.trim() }).then(
() => showSuccess("Email updated"),
(error: Error) => showError(error.message)
)
}
/>
</SettingsCard>
<SettingsCard
title="Password"
subtitle="Choose a new password for this account."
>
<Field label="New Password">
<Input
value={newPassword}
onChangeText={setNewPassword}
placeholder="New password"
secureTextEntry
/>
</Field>
<Field label="Confirm Password">
<Input
value={confirmPassword}
onChangeText={setConfirmPassword}
placeholder="Confirm password"
secureTextEntry
/>
</Field>
<Button
title="Update Password"
loading={changingPassword}
disabled={!newPassword || newPassword !== confirmPassword}
onPress={() => void handlePasswordChange()}
/>
</SettingsCard>
</>
)
}
function QualitySection({ user }: { user: CurrentUser }) {
const colors = useThemeColors()
const updateQuality = useMutation(api.users.updatePlaybackQuality)
const updateAtmos = useMutation(api.users.updatePreferAtmos)
const quality = user.playbackQuality ?? "medium"
return (
<>
<SettingsCard
title="Streaming Quality"
subtitle="Pick the default audio quality for playback."
>
{QUALITY_OPTIONS.map((option) => {
const selected = quality === option.value
return (
<Pressable
key={option.value}
accessibilityRole="button"
accessibilityState={{ selected }}
onPress={() =>
void updateQuality({ playbackQuality: option.value }).catch(
(error: Error) => showError(error.message)
)
}
style={[
styles.optionRow,
{
borderColor: selected ? colors.primary : colors.border,
backgroundColor: selected ? colors.muted : colors.card,
},
]}
>
<View style={styles.optionCopy}>
<Text
style={[styles.optionTitle, { color: colors.foreground }]}
>
{option.label}
</Text>
<Text style={{ color: colors.mutedForeground }}>
{option.description}
</Text>
</View>
{selected ? (
<Ionicons
name="checkmark-circle"
size={22}
color={colors.primary}
/>
) : null}
</Pressable>
)
})}
</SettingsCard>
<SettingsCard title="Spatial Audio">
<SwitchRow
title="Prefer Dolby Atmos"
subtitle="Use Atmos versions when they are available."
value={user.preferAtmos ?? false}
onValueChange={(checked) =>
void updateAtmos({ preferAtmos: checked }).catch((error: Error) =>
showError(error.message)
)
}
/>
</SettingsCard>
</>
)
}
function LibrarySection() {
const updateLibrary = useAction(api.actions.updateLibrary)
const cleanupHlsStreams = useAction(api.actions.adminCleanupHlsStreams)
const [updating, setUpdating] = useState(false)
const [cleaningHls, setCleaningHls] = useState(false)
return (
<SettingsCard
title="Library Maintenance"
subtitle="Run administrative jobs for the shared music library."
>
<Button
title="Update Library"
icon="refresh-outline"
loading={updating}
onPress={async () => {
setUpdating(true)
try {
await updateLibrary({})
showSuccess("Library updated")
} catch (error) {
showError(
error instanceof Error
? error.message
: "Failed to update library"
)
} finally {
setUpdating(false)
}
}}
/>
<Button
title="Clean HLS Streams"
variant="secondary"
icon="sparkles-outline"
loading={cleaningHls}
onPress={async () => {
setCleaningHls(true)
try {
const result = await cleanupHlsStreams({})
showSuccess(`Removed ${result.removed} idle HLS streams`)
} catch (error) {
showError(
error instanceof Error
? error.message
: "Failed to clean HLS streams"
)
} finally {
setCleaningHls(false)
}
}}
/>
</SettingsCard>
)
}
function UsersSection({
users,
currentUserId,
}: {
users: AdminUser[]
currentUserId: Id<"users">
}) {
const colors = useThemeColors()
const appSettings = useQuery(api.users.getAppSettings)
const setDisableCreation = useMutation(api.users.setDisableAccountCreation)
const setAdmin = useMutation(api.users.setUserAdmin)
const deleteUserMutation = useMutation(api.users.deleteUser)
return (
<>
<SettingsCard title="Sign Up">
<SwitchRow
title="Disable account creation"
subtitle="Prevent new users from creating accounts."
value={appSettings?.disableAccountCreation ?? false}
onValueChange={(checked) =>
void setDisableCreation({ disabled: checked }).catch(
(error: Error) => showError(error.message)
)
}
/>
</SettingsCard>
<SettingsCard
title="People"
subtitle="Manage who can access this server."
>
{users.map((user, index) => (
<View key={user._id}>
{index > 0 ? (
<View
style={[styles.divider, { backgroundColor: colors.border }]}
/>
) : null}
<View style={styles.userRow}>
<ProfileAvatar user={user} size={44} />
<View style={styles.userCopy}>
<View style={styles.userNameRow}>
<Text
style={[styles.userName, { color: colors.foreground }]}
numberOfLines={1}
>
{user.name}
</Text>
{user.isAdmin ? (
<View
style={[styles.badge, { backgroundColor: colors.muted }]}
>
<Text
style={[
styles.badgeText,
{ color: colors.mutedForeground },
]}
>
Admin
</Text>
</View>
) : null}
</View>
<Text
style={{ color: colors.mutedForeground }}
numberOfLines={1}
>
{user.email}
</Text>
</View>
</View>
{user._id !== currentUserId ? (
<View style={styles.userActions}>
<Button
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
variant="secondary"
onPress={() =>
void setAdmin({
userId: user._id,
isAdmin: !user.isAdmin,
}).then(
() => showSuccess("Updated permissions"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
<Button
title="Delete"
variant="destructive"
onPress={() =>
void deleteUserMutation({ userId: user._id }).then(
() => showSuccess("User deleted"),
(error: Error) => showError(error.message)
)
}
style={styles.userActionButton}
/>
</View>
) : null}
</View>
))}
</SettingsCard>
</>
)
}
function SessionSection({
onChangeServer,
onSignOut,
}: {
onChangeServer: () => void
onSignOut: () => void
}) {
const colors = useThemeColors()
return (
<SettingsCard title="Session">
<ActionRow
icon="server-outline"
title="Change Server"
subtitle="Disconnect from this server and choose another."
onPress={onChangeServer}
/>
<View style={[styles.divider, { backgroundColor: colors.border }]} />
<ActionRow
icon="log-out-outline"
title="Sign Out"
subtitle="Return to the sign-in screen."
destructive
onPress={onSignOut}
/>
</SettingsCard>
)
}
function SettingsCard({
title,
subtitle,
children,
}: {
title: string
subtitle?: string
children: React.ReactNode
}) {
const colors = useThemeColors()
return (
<View style={[styles.card, { backgroundColor: colors.card }]}>
<View style={styles.cardHeader}>
<Text style={[styles.cardTitle, { color: colors.foreground }]}>
{title}
</Text>
{subtitle ? (
<Text
style={[styles.cardSubtitle, { color: colors.mutedForeground }]}
>
{subtitle}
</Text>
) : null}
</View>
{children}
</View>
)
}
function Field({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
const colors = useThemeColors()
return (
<View style={styles.field}>
<Text style={[styles.fieldLabel, { color: colors.mutedForeground }]}>
{label}
</Text>
{children}
</View>
)
}
function SwitchRow({
title,
subtitle,
value,
onValueChange,
}: {
title: string
subtitle?: string
value: boolean
onValueChange: (checked: boolean) => void
}) {
const colors = useThemeColors()
return (
<View style={styles.switchRow}>
<View style={styles.optionCopy}>
<Text style={[styles.optionTitle, { color: colors.foreground }]}>
{title}
</Text>
{subtitle ? (
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
) : null}
</View>
<Switch value={value} onValueChange={onValueChange} />
</View>
)
}
function ActionRow({
icon,
title,
subtitle,
destructive,
onPress,
}: {
icon: React.ComponentProps<typeof Ionicons>["name"]
title: string
subtitle: string
destructive?: boolean
onPress: () => void
}) {
const colors = useThemeColors()
const tint = destructive ? colors.destructive : colors.foreground
return (
<Pressable
accessibilityRole="button"
onPress={onPress}
style={({ pressed }) => [
styles.actionRow,
{ opacity: pressed ? 0.75 : 1 },
]}
>
<View style={[styles.actionIcon, { backgroundColor: colors.muted }]}>
<Ionicons name={icon} size={20} color={tint} />
</View>
<View style={styles.optionCopy}>
<Text style={[styles.optionTitle, { color: tint }]}>{title}</Text>
<Text style={{ color: colors.mutedForeground }}>{subtitle}</Text>
</View>
<Ionicons
name="chevron-forward"
size={18}
color={colors.mutedForeground}
/>
</Pressable>
)
}
function ProfileAvatar({
user,
size,
style,
}: {
user: Pick<CurrentUser, "name" | "image">
size: number
style?: StyleProp<ViewStyle>
}) {
const colors = useThemeColors()
const avatarStyle = [
styles.avatar,
{
width: size,
height: size,
borderRadius: size / 2,
backgroundColor: colors.muted,
},
style,
]
if (user.image) {
return (
<View style={avatarStyle}>
<Image
source={{ uri: user.image }}
style={styles.avatarImage}
contentFit="cover"
/>
</View>
)
}
return (
<View style={avatarStyle}>
<Text
style={[
styles.avatarInitials,
{ color: colors.foreground, fontSize: size * 0.34 },
]}
>
{initialsFromName(user.name)}
</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
gap: spacing.lg,
paddingHorizontal: spacing.lg,
paddingTop: spacing.md,
},
badge: {
alignSelf: "flex-start",
borderRadius: radius.full,
paddingHorizontal: spacing.sm,
paddingVertical: 2,
},
badgeText: {
fontSize: 12,
fontWeight: "700",
},
pillGroup: {
borderRadius: radius.xl,
padding: spacing.xs,
flexDirection: "row",
gap: spacing.xs,
},
pill: {
flex: 1,
minHeight: 48,
borderRadius: radius.full,
alignItems: "center",
justifyContent: "center",
},
card: {
borderRadius: radius.xl,
padding: spacing.lg,
gap: spacing.md,
},
cardHeader: {
gap: spacing.xs,
},
cardTitle: {
fontSize: 18,
fontWeight: "800",
},
cardSubtitle: {
fontSize: 14,
lineHeight: 20,
},
photoRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.lg,
},
photoActions: {
flex: 1,
gap: spacing.sm,
},
field: {
gap: spacing.sm,
},
fieldLabel: {
fontSize: 13,
fontWeight: "700",
textTransform: "uppercase",
},
divider: {
height: StyleSheet.hairlineWidth,
},
optionRow: {
borderWidth: 1,
borderRadius: radius.lg,
padding: spacing.md,
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
},
optionCopy: {
flex: 1,
gap: 3,
},
optionTitle: {
fontSize: 16,
fontWeight: "700",
},
switchRow: {
minHeight: 56,
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
},
userRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
},
userCopy: {
flex: 1,
gap: 3,
},
userNameRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.sm,
},
userName: {
flexShrink: 1,
fontSize: 16,
fontWeight: "700",
},
userActions: {
flexDirection: "row",
gap: spacing.sm,
marginTop: spacing.md,
},
userActionButton: {
flex: 1,
},
actionRow: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
},
actionIcon: {
width: 36,
height: 36,
borderRadius: 18,
alignItems: "center",
justifyContent: "center",
},
avatar: {
alignItems: "center",
justifyContent: "center",
overflow: "hidden",
},
avatarImage: {
width: "100%",
height: "100%",
},
avatarInitials: {
fontWeight: "800",
},
})