Polish mobile and web experience

This commit is contained in:
2026-08-17 00:18:55 -04:00
parent 6c74436092
commit 9929d7321d
28 changed files with 835 additions and 688 deletions
+3 -5
View File
@@ -2,7 +2,6 @@ import { router } from "expo-router";
import { useState } from "react";
import {
Alert,
RefreshControl,
ScrollView,
StyleSheet,
Text,
@@ -15,6 +14,7 @@ import { FloatingActionButton } from "@/components/FloatingActionButton";
import { GlassSurface } from "@/components/GlassSurface";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { PullToRefresh } from "@/components/PullToRefresh";
import { SwipeableRow } from "@/components/SwipeableRow";
import { TabPage } from "@/components/TabPage";
import { TabScrollView } from "@/components/TabScrollView";
@@ -71,8 +71,7 @@ export default function EntitiesScreen() {
const businesses = businessesQuery.data ?? [];
function refresh() {
if (tab === "clients") void clientsQuery.refetch();
else void businessesQuery.refetch();
return tab === "clients" ? clientsQuery.refetch() : businessesQuery.refetch();
}
function confirmDelete(id: string, name: string) {
@@ -100,8 +99,7 @@ export default function EntitiesScreen() {
/>
}
refreshControl={
<RefreshControl
refreshing={activeQuery.isRefetching}
<PullToRefresh
onRefresh={refresh}
tintColor={colors.primary}
/>
+27 -9
View File
@@ -1,11 +1,12 @@
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { Pressable, RefreshControl, StyleSheet, Text, View } from "react-native";
import { Pressable, StyleSheet, Text, View } from "react-native";
import { AppBackground } from "@/components/AppBackground";
import { GlassSurface } from "@/components/GlassSurface";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { PullToRefresh } from "@/components/PullToRefresh";
import { Screen } from "@/components/Screen";
import { StatCard } from "@/components/StatCard";
import { StatusBadge } from "@/components/StatusBadge";
@@ -152,12 +153,8 @@ export default function DashboardScreen() {
<TabScrollView
header={<PageHeader title={`Hello, ${firstName}`} subtitle="What needs attention now" />}
refreshControl={
<RefreshControl
refreshing={statsQuery.isRefetching || runningQuery.isRefetching}
onRefresh={() => {
void statsQuery.refetch();
void runningQuery.refetch();
}}
<PullToRefresh
onRefresh={() => Promise.all([statsQuery.refetch(), runningQuery.refetch()])}
tintColor={colors.primary}
/>
}
@@ -221,7 +218,10 @@ export default function DashboardScreen() {
</Card>
{running ? (
<Pressable onPress={() => router.push("/(app)/timer")}>
<Pressable
accessibilityRole="button"
onPress={() => router.push("/(app)/timer")}
>
<GlassSurface style={styles.runningGlass}>
<View style={styles.runningRow}>
<View style={styles.runningDot} />
@@ -299,6 +299,11 @@ export default function DashboardScreen() {
{stats.currentDraft ? (
<GlassSurface style={styles.draftGlass}>
<Pressable
accessible
accessibilityLabel={`Current draft, ${
stats.currentDraft.client?.name ?? "Client"
}, ${formatCurrency(stats.currentDraft.totalAmount)}, ${stats.currentDraft.totalHours.toFixed(1)} hours logged`}
accessibilityRole="button"
style={styles.draftBanner}
onPress={() => router.push(`/(app)/invoices/${stats.currentDraft!.id}`)}
>
@@ -325,7 +330,12 @@ export default function DashboardScreen() {
<View style={styles.statCell}>
<StatCard label="Overdue" value={String(stats.overdueCount)} />
</View>
<Pressable style={styles.statCell} onPress={() => router.push("/(app)/entities")}>
<Pressable
accessibilityRole="button"
accessibilityLabel={`Clients, ${stats.totalClients}`}
style={styles.statCell}
onPress={() => router.push("/(app)/entities")}
>
<StatCard label="Clients" value={String(stats.totalClients)} />
</Pressable>
</View>
@@ -354,6 +364,14 @@ export default function DashboardScreen() {
const status = getInvoiceStatus(invoice);
return (
<Pressable
accessible
accessibilityLabel={`${invoice.invoicePrefix}${invoice.invoiceNumber}, ${
invoice.client?.name ?? "Client"
}, ${formatDate(invoice.issueDate)}, ${formatCurrency(
invoice.totalAmount,
invoice.currency,
)}, ${status}`}
accessibilityRole="button"
key={invoice.id}
style={({ pressed }) => [styles.recentRow, pressed && styles.pressed]}
onPress={() => router.push(`/(app)/invoices/${invoice.id}`)}
+2 -3
View File
@@ -2,7 +2,6 @@ import { router } from "expo-router";
import { useState } from "react";
import {
Alert,
RefreshControl,
ScrollView,
StyleSheet,
Text,
@@ -15,6 +14,7 @@ import { FloatingActionButton } from "@/components/FloatingActionButton";
import { GlassSurface } from "@/components/GlassSurface";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { PullToRefresh } from "@/components/PullToRefresh";
import { SwipeableRow } from "@/components/SwipeableRow";
import { StatusBadge } from "@/components/StatusBadge";
import { TabPage } from "@/components/TabPage";
@@ -121,8 +121,7 @@ export default function InvoicesScreen() {
<PageHeader title="Invoices" subtitle="Review status, amounts, and due dates" />
}
refreshControl={
<RefreshControl
refreshing={invoicesQuery.isRefetching}
<PullToRefresh
onRefresh={() => invoicesQuery.refetch()}
tintColor={colors.primary}
/>
+21 -8
View File
@@ -29,6 +29,7 @@ import { formatCurrency } from "@/lib/format";
import {
isRequiredString,
isValidTaxRate,
useFieldVisibility,
validateLineItems,
} from "@/lib/form-validation";
import { resolveInvoiceBusinessId } from "@/lib/invoice-business";
@@ -70,6 +71,7 @@ export default function NewInvoiceScreen() {
);
const [section, setSection] = useState<InvoiceEditorSection>("setup");
const [error, setError] = useState<string | null>(null);
const { touch, visible, markSubmitted } = useFieldVisibility();
useEffect(() => {
if (businessId || !businessesQuery.data?.length) return;
@@ -184,10 +186,12 @@ export default function NewInvoiceScreen() {
}
function updateItem(index: number, patch: Partial<EditableLineItem>) {
touch("lineItems");
setItems((prev) => prev.map((item, i) => (i === index ? { ...item, ...patch } : item)));
}
function addItem() {
touch("lineItems");
setItems((prev) => [
...prev,
{
@@ -200,10 +204,12 @@ export default function NewInvoiceScreen() {
}
function removeItem(index: number) {
touch("lineItems");
setItems((prev) => prev.filter((_, i) => i !== index));
}
function duplicateItem(index: number) {
touch("lineItems");
setItems((prev) => {
const source = prev[index];
if (!source) return prev;
@@ -213,6 +219,7 @@ export default function NewInvoiceScreen() {
}
function handleCreate() {
markSubmitted();
if (!canCreate) return;
setError(null);
@@ -296,27 +303,31 @@ export default function NewInvoiceScreen() {
businessId={businessId}
onBusinessIdChange={setBusinessId}
businessOptions={businessOptions}
businessError={businessError}
businessError={visible("business") ? businessError : undefined}
onBusinessBlur={() => touch("business")}
clientId={clientId}
onClientIdChange={setClientId}
clientOptions={clientOptions}
clientError={clientError}
clientError={visible("client") ? clientError : undefined}
onClientBlur={() => touch("client")}
invoiceNumber={invoiceNumber}
onInvoiceNumberChange={setInvoiceNumber}
invoiceNumberError={
visible("invoiceNumber") ? invoiceNumberError : undefined
}
onInvoiceNumberBlur={() => touch("invoiceNumber")}
issueDate={issueDate}
onIssueDateChange={setIssueDate}
dueDate={dueDate}
onDueDateChange={setDueDate}
taxRate={taxRate}
onTaxRateChange={setTaxRate}
taxRateError={visible("taxRate") ? taxError : undefined}
onTaxRateBlur={() => touch("taxRate")}
notes={notes}
onNotesChange={setNotes}
/>
)}
{taxError ? <Text style={styles.error}>{taxError}</Text> : null}
{invoiceNumberError ? (
<Text style={styles.error}>{invoiceNumberError}</Text>
) : null}
</Card>
) : (
<>
@@ -354,11 +365,13 @@ export default function NewInvoiceScreen() {
/>
</Card>
{lineItemsError ? <Text style={styles.error}>{lineItemsError}</Text> : null}
{visible("lineItems") && lineItemsError ? (
<Text selectable style={styles.error}>{lineItemsError}</Text>
) : null}
</>
)}
{error ? <Text style={styles.error}>{error}</Text> : null}
{error ? <Text selectable style={styles.error}>{error}</Text> : null}
<InvoiceEditorFooter
primaryTitle={isBlank ? "Create blank invoice" : "Create invoice"}
@@ -2,7 +2,6 @@ import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { useMemo, useState } from "react";
import {
RefreshControl,
ScrollView,
StyleSheet,
Text,
@@ -15,6 +14,7 @@ import { AppBackground } from "@/components/AppBackground";
import { FilterChip } from "@/components/FilterChip";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { PullToRefresh } from "@/components/PullToRefresh";
import { SwipeableRow } from "@/components/SwipeableRow";
import { TabPage } from "@/components/TabPage";
import { TabScrollView } from "@/components/TabScrollView";
@@ -110,9 +110,8 @@ export default function ExpensesScreen() {
</View>
}
refreshControl={
<RefreshControl
refreshing={expensesQuery.isRefetching}
onRefresh={() => void expensesQuery.refetch()}
<PullToRefresh
onRefresh={() => expensesQuery.refetch()}
tintColor={colors.primary}
/>
}
+4 -4
View File
@@ -1,8 +1,9 @@
import { RefreshControl, StyleSheet, Text, View } from "react-native";
import { StyleSheet, Text, View } from "react-native";
import { AppBackground } from "@/components/AppBackground";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { PullToRefresh } from "@/components/PullToRefresh";
import { SwipeableRow } from "@/components/SwipeableRow";
import { TabPage } from "@/components/TabPage";
import { TabScrollView } from "@/components/TabScrollView";
@@ -46,9 +47,8 @@ export default function RecurringScreen() {
/>
}
refreshControl={
<RefreshControl
refreshing={query.isRefetching}
onRefresh={() => void query.refetch()}
<PullToRefresh
onRefresh={() => query.refetch()}
tintColor={colors.primary}
/>
}
+10 -8
View File
@@ -1,8 +1,9 @@
import { RefreshControl, StyleSheet, Text, View } from "react-native";
import { StyleSheet, Text, View } from "react-native";
import { AppBackground } from "@/components/AppBackground";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { PullToRefresh } from "@/components/PullToRefresh";
import { StatCard } from "@/components/StatCard";
import { TabPage } from "@/components/TabPage";
import { TabScrollView } from "@/components/TabScrollView";
@@ -48,13 +49,14 @@ export default function ReportsScreen() {
<TabScrollView
header={<PageHeader title="Reports" subtitle="Business performance snapshot" />}
refreshControl={
<RefreshControl
refreshing={statsQuery.isRefetching}
onRefresh={() => {
void statsQuery.refetch();
void expensesQuery.refetch();
void summaryQuery.refetch();
}}
<PullToRefresh
onRefresh={() =>
Promise.all([
statsQuery.refetch(),
expensesQuery.refetch(),
summaryQuery.refetch(),
])
}
tintColor={colors.primary}
/>
}
+4 -4
View File
@@ -1,9 +1,10 @@
import { useMemo, useState } from "react";
import { RefreshControl, StyleSheet, Text, View } from "react-native";
import { StyleSheet, Text, View } from "react-native";
import { AppBackground } from "@/components/AppBackground";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { PullToRefresh } from "@/components/PullToRefresh";
import { SwipeableRow } from "@/components/SwipeableRow";
import { TabPage } from "@/components/TabPage";
import { TabScrollView } from "@/components/TabScrollView";
@@ -74,9 +75,8 @@ export default function TimeEntriesScreen() {
<PageHeader title="Time entries" subtitle={`${completed.length} completed entries`} />
}
refreshControl={
<RefreshControl
refreshing={entriesQuery.isRefetching}
onRefresh={() => void entriesQuery.refetch()}
<PullToRefresh
onRefresh={() => entriesQuery.refetch()}
tintColor={colors.primary}
/>
}
+14 -5
View File
@@ -21,7 +21,11 @@ import { useAppTheme } from "@/contexts/ThemeContext";
import { resetPassword } from "@/lib/auth-api";
import type { ThemeColors } from "@/lib/theme-palette";
import { useThemedStyles } from "@/lib/use-themed-styles";
import { isRequiredString, isValidPassword } from "@/lib/form-validation";
import {
isRequiredString,
isValidPassword,
useFieldVisibility,
} from "@/lib/form-validation";
export default function ResetPasswordScreen() {
const styles = useThemedStyles(createResetPasswordStyles);
@@ -33,6 +37,7 @@ export default function ResetPasswordScreen() {
const [success, setSuccess] = useState(false);
const [loading, setLoading] = useState(false);
const [serverReady, setServerReady] = useState(true);
const { touch, visible, markSubmitted } = useFieldVisibility();
useEffect(() => {
if (typeof tokenParam === "string" && tokenParam.length > 0) {
@@ -56,6 +61,7 @@ export default function ResetPasswordScreen() {
confirmPassword.length > 0;
async function handleSubmit() {
markSubmitted();
if (!canSubmit) return;
setError(null);
@@ -111,30 +117,33 @@ export default function ResetPasswordScreen() {
autoCapitalize="none"
value={token}
onChangeText={setToken}
onBlur={() => touch("token")}
placeholder="Paste token from email"
required
error={tokenError}
error={visible("token") ? tokenError : undefined}
/>
<Input
label="New password"
secureTextEntry
value={password}
onChangeText={setPassword}
onBlur={() => touch("password")}
placeholder="At least 8 characters"
required
error={passwordError}
error={visible("password") ? passwordError : undefined}
/>
<Input
label="Confirm password"
secureTextEntry
value={confirmPassword}
onChangeText={setConfirmPassword}
onBlur={() => touch("confirmPassword")}
placeholder="Repeat password"
required
error={confirmError}
error={visible("confirmPassword") ? confirmError : undefined}
/>
{error ? <Text style={styles.error}>{error}</Text> : null}
{error ? <Text selectable style={styles.error}>{error}</Text> : null}
<Button
title="Update password"
+4 -1
View File
@@ -14,7 +14,10 @@ export function FilterChip({ label, active, onPress }: FilterChipProps) {
return (
<Pressable
accessible
accessibilityLabel={label}
accessibilityRole="button"
accessibilityState={{ selected: Boolean(active) }}
onPress={onPress}
style={[
styles.chip,
@@ -39,7 +42,7 @@ export function FilterChip({ label, active, onPress }: FilterChipProps) {
const styles = StyleSheet.create({
chip: {
height: 32,
minHeight: 44,
borderWidth: 1,
borderRadius: radii.pill,
overflow: "hidden",
+34
View File
@@ -0,0 +1,34 @@
import { useCallback, useState } from "react";
import { RefreshControl, type RefreshControlProps } from "react-native";
type PullToRefreshProps = Omit<RefreshControlProps, "onRefresh" | "refreshing"> & {
onRefresh: () => Promise<unknown> | unknown;
};
/**
* Keeps the native refresh indicator tied to an actual pull gesture.
* Query `isRefetching` also covers background polling and invalidations, which
* can repeatedly move an offscreen iOS scroll view when used as `refreshing`.
*/
export function PullToRefresh({ onRefresh, ...props }: PullToRefreshProps) {
const [refreshing, setRefreshing] = useState(false);
const handleRefresh = useCallback(async () => {
if (refreshing) return;
setRefreshing(true);
try {
await onRefresh();
} finally {
setRefreshing(false);
}
}, [onRefresh, refreshing]);
return (
<RefreshControl
{...props}
refreshing={refreshing}
onRefresh={() => void handleRefresh()}
/>
);
}
+57 -19
View File
@@ -4,9 +4,15 @@ import { Pressable, type PressableProps, StyleSheet, Text, View } from "react-na
import Swipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import Animated, {
interpolate,
useAnimatedStyle,
type SharedValue,
} from "react-native-reanimated";
import { fonts, radii, spacing } from "@/constants/theme";
import { useAppTheme } from "@/contexts/ThemeContext";
import { resolveActionForeground } from "@/lib/action-contrast";
import type { ThemeColors } from "@/lib/theme-palette";
import { useThemedStyles } from "@/lib/use-themed-styles";
@@ -29,6 +35,38 @@ type SwipeableRowProps = {
contentStyle?: PressableProps["style"];
};
type SwipeActionsProps = {
actions: SwipeAction[];
progress: SharedValue<number>;
onActionPress: (action: SwipeAction) => void;
};
function SwipeActions({ actions, progress, onActionPress }: SwipeActionsProps) {
const styles = useThemedStyles(createSwipeableRowStyles);
const revealStyle = useAnimatedStyle(() => ({
opacity: interpolate(progress.value, [0, 0.02, 0.15], [0, 0, 1], "clamp"),
}));
return (
<Animated.View style={[styles.actions, revealStyle]}>
{actions.map((action) => {
const foreground = resolveActionForeground(action.backgroundColor, action.color);
return (
<Pressable
key={action.key}
style={[styles.actionButton, { backgroundColor: action.backgroundColor }]}
onPress={() => onActionPress(action)}
>
<Ionicons name={action.icon} size={20} color={foreground} />
<Text style={[styles.actionLabel, { color: foreground }]}>{action.label}</Text>
</Pressable>
);
})}
</Animated.View>
);
}
export function SwipeableRow({
children,
actions,
@@ -92,25 +130,20 @@ export function SwipeableRow({
);
}
function renderRightActions() {
function handleActionPress(action: SwipeAction) {
suppressContentPress();
swipeRef.current?.close();
rowOpenRef.current = false;
action.onPress();
}
function renderRightActions(progress: SharedValue<number>) {
return (
<View style={styles.actions}>
{actions.map((action) => (
<Pressable
key={action.key}
style={[styles.actionButton, { backgroundColor: action.backgroundColor }]}
onPress={() => {
suppressContentPress();
swipeRef.current?.close();
rowOpenRef.current = false;
action.onPress();
}}
>
<Ionicons name={action.icon} size={20} color={action.color} />
<Text style={[styles.actionLabel, { color: action.color }]}>{action.label}</Text>
</Pressable>
))}
</View>
<SwipeActions
actions={actions}
progress={progress}
onActionPress={handleActionPress}
/>
);
}
@@ -121,6 +154,7 @@ export function SwipeableRow({
return (
<Swipeable
ref={swipeRef}
containerStyle={styles.container}
renderRightActions={renderRightActions}
overshootRight={false}
onSwipeableOpenStartDrag={suppressContentPress}
@@ -141,11 +175,15 @@ export function SwipeableRow({
const createSwipeableRowStyles = (colors: ThemeColors) =>
StyleSheet.create({
container: {
borderRadius: radii.lg,
overflow: "hidden",
marginBottom: spacing.xs,
},
row: {
backgroundColor: colors.background,
borderRadius: radii.lg,
overflow: "hidden",
marginBottom: spacing.xs,
},
actions: {
flexDirection: "row",
@@ -17,7 +17,7 @@ import { fonts, spacing } from "@/constants/theme";
import { useAppTheme } from "@/contexts/ThemeContext";
import type { ThemeColors } from "@/lib/theme-palette";
import { useThemedStyles } from "@/lib/use-themed-styles";
import { isRequiredString } from "@/lib/form-validation";
import { isRequiredString, useFieldVisibility } from "@/lib/form-validation";
import { api } from "@/lib/trpc";
type BusinessFormValues = {
@@ -78,6 +78,7 @@ export function BusinessForm({
const [values, setValues] = useState<BusinessFormValues>(emptyValues);
const [fieldError, setFieldError] = useState<string | null>(null);
const { touch, visible, markSubmitted } = useFieldVisibility();
const switchProps = {
trackColor: { false: colors.switchTrackOff, true: colors.switchTrackOn },
@@ -154,6 +155,7 @@ export function BusinessForm({
}
function handleSave() {
markSubmitted();
if (!canSave) return;
const payload = buildPayload();
@@ -203,8 +205,9 @@ export function BusinessForm({
label="Name"
value={values.name}
onChangeText={(v) => patch("name", v)}
onBlur={() => touch("name")}
required
error={nameError}
error={visible("name") ? nameError : undefined}
/>
<Input
label="Nickname"
@@ -281,7 +284,7 @@ export function BusinessForm({
/>
</Card>
{fieldError ? <Text style={styles.error}>{fieldError}</Text> : null}
{fieldError ? <Text selectable style={styles.error}>{fieldError}</Text> : null}
<View style={styles.actions}>
<Button
+12 -4
View File
@@ -15,7 +15,11 @@ import { Input } from "@/components/ui/Input";
import { fonts, spacing } from "@/constants/theme";
import type { ThemeColors } from "@/lib/theme-palette";
import { useThemedStyles } from "@/lib/use-themed-styles";
import { isRequiredString, parseNonNegativeNumber } from "@/lib/form-validation";
import {
isRequiredString,
parseNonNegativeNumber,
useFieldVisibility,
} from "@/lib/form-validation";
import { api } from "@/lib/trpc";
export type ClientFormValues = {
@@ -71,6 +75,7 @@ export function ClientForm({
const [values, setValues] = useState<ClientFormValues>(emptyValues);
const [fieldError, setFieldError] = useState<string | null>(null);
const { touch, visible, markSubmitted } = useFieldVisibility();
useEffect(() => {
const client = clientQuery.data;
@@ -125,6 +130,7 @@ export function ClientForm({
}
function handleSave() {
markSubmitted();
if (!canSave) return;
const rate = values.defaultHourlyRate.trim()
@@ -199,8 +205,9 @@ export function ClientForm({
label="Name"
value={values.name}
onChangeText={(v) => patch("name", v)}
onBlur={() => touch("name")}
required
error={nameError}
error={visible("name") ? nameError : undefined}
/>
<Input
label="Email"
@@ -247,9 +254,10 @@ export function ClientForm({
label="Default hourly rate"
value={values.defaultHourlyRate}
onChangeText={(v) => patch("defaultHourlyRate", v)}
onBlur={() => touch("defaultHourlyRate")}
keyboardType="decimal-pad"
placeholder="Optional"
error={rateError}
error={visible("defaultHourlyRate") ? rateError : undefined}
/>
<Input
label="Currency"
@@ -260,7 +268,7 @@ export function ClientForm({
/>
</Card>
{fieldError ? <Text style={styles.error}>{fieldError}</Text> : null}
{fieldError ? <Text selectable style={styles.error}>{fieldError}</Text> : null}
<View style={styles.actions}>
<Button
@@ -14,14 +14,18 @@ type InvoiceSetupFormProps = {
onBusinessIdChange: (value: string) => void;
businessOptions: SelectOption[];
businessError?: string;
onBusinessBlur?: () => void;
businessReadOnly?: boolean;
clientId: string;
onClientIdChange: (value: string) => void;
clientOptions: SelectOption[];
clientError?: string;
onClientBlur?: () => void;
clientReadOnly?: boolean;
invoiceNumber: string;
onInvoiceNumberChange?: (value: string) => void;
invoiceNumberError?: string;
onInvoiceNumberBlur?: () => void;
invoiceNumberReadOnly?: boolean;
issueDate: Date;
onIssueDateChange?: (date: Date) => void;
@@ -30,6 +34,8 @@ type InvoiceSetupFormProps = {
onDueDateChange: (date: Date) => void;
taxRate: string;
onTaxRateChange?: (value: string) => void;
taxRateError?: string;
onTaxRateBlur?: () => void;
taxRateReadOnly?: boolean;
notes: string;
onNotesChange: (value: string) => void;
@@ -43,14 +49,18 @@ export function InvoiceSetupForm({
onBusinessIdChange,
businessOptions,
businessError,
onBusinessBlur,
businessReadOnly = false,
clientId,
onClientIdChange,
clientOptions,
clientError,
onClientBlur,
clientReadOnly = false,
invoiceNumber,
onInvoiceNumberChange,
invoiceNumberError,
onInvoiceNumberBlur,
invoiceNumberReadOnly = false,
issueDate,
onIssueDateChange,
@@ -59,6 +69,8 @@ export function InvoiceSetupForm({
onDueDateChange,
taxRate,
onTaxRateChange,
taxRateError,
onTaxRateBlur,
taxRateReadOnly = false,
notes,
onNotesChange,
@@ -84,6 +96,7 @@ export function InvoiceSetupForm({
error={businessError}
disabled={businessReadOnly}
onValueChange={onBusinessIdChange}
onBlur={onBusinessBlur}
/>
)}
@@ -101,6 +114,7 @@ export function InvoiceSetupForm({
error={clientError}
disabled={clientReadOnly}
onValueChange={onClientIdChange}
onBlur={onClientBlur}
/>
)}
@@ -118,8 +132,10 @@ export function InvoiceSetupForm({
label="Invoice number"
value={invoiceNumber}
onChangeText={onInvoiceNumberChange}
onBlur={onInvoiceNumberBlur}
autoCapitalize="characters"
required
error={invoiceNumberError}
/>
)}
@@ -160,7 +176,9 @@ export function InvoiceSetupForm({
label="Tax rate (%)"
value={taxRate}
onChangeText={onTaxRateChange}
onBlur={onTaxRateBlur}
keyboardType="decimal-pad"
error={taxRateError}
/>
)}
@@ -2,7 +2,6 @@ import { useEffect, useMemo, useState, type ReactNode } from "react";
import {
Alert,
Pressable,
RefreshControl,
StyleSheet,
Text,
TextInput,
@@ -13,6 +12,7 @@ import { router } from "expo-router";
import { FilterChip } from "@/components/FilterChip";
import { GlassSurface } from "@/components/GlassSurface";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PullToRefresh } from "@/components/PullToRefresh";
import { SwipeableRow } from "@/components/SwipeableRow";
import { TabScrollView } from "@/components/TabScrollView";
import { TimeEntryEditSheet } from "@/components/time-clock/TimeEntryEditSheet";
@@ -20,16 +20,14 @@ import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { DateTimeField } from "@/components/ui/DateTimeField";
import { Input } from "@/components/ui/Input";
import { SelectField } from "@/components/ui/SelectField";
import { fonts, spacing } from "@/constants/theme";
import { useAccounts } from "@/contexts/AccountsContext";
import { useAppTheme } from "@/contexts/ThemeContext";
import { formatCurrency, formatDateTime } from "@/lib/format";
import { parseNonNegativeNumber } from "@/lib/form-validation";
import type { ThemeColors } from "@/lib/theme-palette";
import {
getLastTimeClockClientId,
setLastTimeClockClientId,
} from "@/lib/time-clock-prefs";
import { setLastTimeClockClientId } from "@/lib/time-clock-prefs";
import { useThemedStyles } from "@/lib/use-themed-styles";
import {
endTimeClockLiveActivity,
@@ -99,12 +97,8 @@ export function TimeClockPanel({
const [agoMinutes, setAgoMinutes] = useState(60);
const [agoMinutesText, setAgoMinutesText] = useState("60");
const [optionsExpanded, setOptionsExpanded] = useState(false);
const [clientsExpanded, setClientsExpanded] = useState(false);
const [editEntryId, setEditEntryId] = useState<string | null>(null);
const [runningStartedAt, setRunningStartedAt] = useState(() => new Date());
const [featuredClientIds, setFeaturedClientIds] = useState<string[]>([]);
const [storedLastClientId, setStoredLastClientId] = useState<string | null>(null);
const [prefsLoaded, setPrefsLoaded] = useState(false);
const running = runningQuery.data;
const elapsed = useRunningElapsed(running?.startedAt);
@@ -124,19 +118,6 @@ export function TimeClockPanel({
const entriesQuery = api.timeEntries.getAll.useQuery();
const recentClientIds = useMemo(() => {
const seen = new Set<string>();
const ids: string[] = [];
for (const entry of entriesQuery.data ?? []) {
if (entry.clientId && !seen.has(entry.clientId)) {
seen.add(entry.clientId);
ids.push(entry.clientId);
if (ids.length >= 2) break;
}
}
return ids;
}, [entriesQuery.data]);
const clockIn = api.timeEntries.clockIn.useMutation({
onSuccess: async () => {
await utils.timeEntries.getRunning.invalidate();
@@ -180,18 +161,6 @@ export function TimeClockPanel({
},
});
useEffect(() => {
if (!activeAccountId) {
setPrefsLoaded(true);
return;
}
setPrefsLoaded(false);
void getLastTimeClockClientId(activeAccountId).then((id) => {
setStoredLastClientId(id);
setPrefsLoaded(true);
});
}, [activeAccountId]);
useEffect(() => {
if (!running) return;
setClientId(running.clientId ?? "");
@@ -209,22 +178,6 @@ export function TimeClockPanel({
setRateText((current) => current.trim() || clientRateText(client));
}, [clientId, clients, running]);
useEffect(() => {
if (featuredClientIds.length > 0 || !prefsLoaded || clients.length === 0) return;
const ids: string[] = [];
const add = (id: string | null | undefined) => {
if (!id || ids.includes(id)) return;
if (!clients.some((client) => client.id === id)) return;
ids.push(id);
};
add(storedLastClientId);
for (const id of recentClientIds) add(id);
setFeaturedClientIds(ids.slice(0, 1));
}, [clients, featuredClientIds.length, prefsLoaded, recentClientIds, storedLastClientId]);
const selectedClient = clients.find((client) => client.id === clientId);
const rateCurrency = selectedClient?.currency ?? "USD";
const effectiveRate = resolveEffectiveHourlyRate(
@@ -235,21 +188,6 @@ export function TimeClockPanel({
? (running.rate ?? effectiveRate ?? 0)
: (effectiveRate ?? 0);
const featuredClients = useMemo(
() =>
featuredClientIds
.map((id) => clients.find((client) => client.id === id))
.filter((client) => client != null),
[clients, featuredClientIds],
);
const moreClients = useMemo(() => {
const featuredIds = new Set(featuredClientIds);
return clients
.filter((client) => !featuredIds.has(client.id))
.sort((a, b) => a.name.localeCompare(b.name));
}, [clients, featuredClientIds]);
const resolvedStartAt = useMemo(() => {
if (startMode === "now") return new Date();
if (startMode === "ago") return startedAtFromMinutesAgo(agoMinutes);
@@ -285,11 +223,14 @@ export function TimeClockPanel({
),
[entriesQuery.data, todayStart],
);
const todayHours = useMemo(
() => todayEntries.reduce((total, entry) => total + Number(entry.hours ?? 0), 0),
[todayEntries],
);
async function persistClientChoice(nextClientId: string, syncState = false) {
async function persistClientChoice(nextClientId: string) {
if (!activeAccountId || !nextClientId) return;
await setLastTimeClockClientId(activeAccountId, nextClientId);
if (syncState) setStoredLastClientId(nextClientId);
}
function selectClient(nextClientId: string) {
@@ -305,9 +246,6 @@ export function TimeClockPanel({
setClientId(nextClientId);
setInvoiceId("");
setRateText(clientRateText(client));
if (nextClientId && !featuredClientIds.includes(nextClientId)) {
setClientsExpanded(true);
}
if (nextClientId) {
void persistClientChoice(nextClientId);
}
@@ -420,63 +358,83 @@ export function TimeClockPanel({
.join(" · ");
function renderClientChip(client: (typeof clients)[number]) {
return (
<FilterChip
key={client.id}
label={client.name}
active={clientId === client.id}
onPress={() => selectClient(client.id)}
/>
);
}
return (
<TabScrollView
style={styles.scroll}
header={header}
refreshControl={
<RefreshControl
refreshing={runningQuery.isRefetching}
onRefresh={() => {
void runningQuery.refetch();
void clientsQuery.refetch();
void billableQuery.refetch();
void entriesQuery.refetch();
}}
<PullToRefresh
onRefresh={() =>
Promise.all([
runningQuery.refetch(),
clientsQuery.refetch(),
billableQuery.refetch(),
entriesQuery.refetch(),
])
}
tintColor={colors.primary}
/>
}
>
{running || !compact ? (
{running ? (
<GlassSurface style={running ? styles.runningCard : undefined}>
<View style={[styles.hero, running && styles.heroRunning]}>
{running ? (
<>
<View style={styles.heroHeader}>
<View style={styles.pulseDot} />
<Text style={styles.heroLabelRunning}>Timer running</Text>
</View>
<Text style={styles.timerValue}>{formatElapsedSeconds(elapsed)}</Text>
<Text style={styles.runningTitle}>{runningTitle}</Text>
{runningMeta ? (
<Text style={styles.runningMeta}>{runningMeta}</Text>
) : null}
</>
) : (
<Text style={styles.idleHint}>
Start the timer anytime add client, invoice, and details later.
</Text>
)}
<View style={styles.heroHeader}>
<View style={styles.pulseDot} />
<Text style={styles.heroLabelRunning}>In progress</Text>
</View>
<Text selectable style={styles.timerValue}>
{formatElapsedSeconds(elapsed)}
</Text>
<Text selectable style={styles.runningTitle}>{runningTitle}</Text>
{runningMeta ? (
<Text selectable style={styles.runningMeta}>{runningMeta}</Text>
) : null}
</View>
</GlassSurface>
) : null}
<GlassSurface style={styles.setupCard}>
<Text style={styles.cardTitle}>{running ? "Update & stop" : "Clock in"}</Text>
{!running ? (
<View style={styles.idleIntro}>
<Text style={styles.idleEyebrow}>Ready to start</Text>
<Text style={styles.idleTitle}>What are you working on?</Text>
<Text style={styles.idleCopy}>
Add what you know now. You can update the rest while the timer runs.
</Text>
</View>
) : null}
{running ? (
<View style={styles.formSection}>
<>
<Button
title={clockOut.isPending ? "Stopping…" : "Stop & save entry"}
variant="danger"
leftIcon="stop"
loading={clockOut.isPending}
onPress={handleClockOut}
/>
<Pressable
accessible
accessibilityRole="button"
accessibilityState={{ expanded: optionsExpanded }}
onPress={() => setOptionsExpanded((open) => !open)}
style={({ pressed }) => [
styles.optionsToggle,
pressed && styles.optionsTogglePressed,
]}
>
<View style={styles.optionsToggleText}>
<Text style={styles.optionsToggleLabel}>Edit timer details</Text>
<Text style={styles.optionsToggleSummary}>
Started {formatDateTime(runningStartedAt)}
</Text>
</View>
<Text style={styles.optionsChevron}>{optionsExpanded ? "" : "+"}</Text>
</Pressable>
{optionsExpanded ? <View style={styles.formSection}>
<Input
label="What are you working on?"
value={description}
@@ -544,79 +502,49 @@ export function TimeClockPanel({
}
returnKeyType="done"
/>
<Button
title={clockOut.isPending ? "Stopping…" : "Stop & save"}
variant="danger"
loading={clockOut.isPending}
onPress={handleClockOut}
/>
</View>
</View> : null}
</>
) : (
<>
<TextInput
value={description}
onChangeText={setDescription}
placeholder="What are you working on?"
placeholderTextColor={colors.mutedForeground}
returnKeyType="done"
style={[styles.titleField, { color: colors.foreground }]}
/>
<View style={styles.idleFields}>
<Input
label="Description"
value={description}
onChangeText={setDescription}
placeholder="e.g. Client kickoff…"
returnKeyType="done"
style={styles.titleField}
containerStyle={styles.timerField}
/>
<View style={styles.setupSection}>
<Text style={styles.sectionLabel}>Client</Text>
{clients.length === 0 ? (
<Text style={styles.emptyClients}>
No clients yet you can still start the timer and assign a client later.
</Text>
) : (
<>
<View style={styles.chipWrap}>
<FilterChip
label="No client"
active={!clientId}
onPress={() => selectClient("")}
/>
{featuredClients.map((client) => renderClientChip(client))}
{moreClients.length > 0 ? (
<FilterChip
label={clientsExpanded ? "Show less" : "Show more"}
active={clientsExpanded}
onPress={() => setClientsExpanded((open) => !open)}
/>
) : null}
</View>
{clientsExpanded && moreClients.length > 0 ? (
<View style={[styles.chipWrap, styles.moreClientsWrap]}>
{moreClients.map((client) => renderClientChip(client))}
</View>
) : null}
</>
)}
</View>
<SelectField
label="Client"
placeholder="Select a client"
value={clientId}
options={[
{ label: "No client", value: "" },
...clients.map((client) => ({ label: client.name, value: client.id })),
]}
onValueChange={selectClient}
containerStyle={styles.timerField}
/>
<View style={styles.setupSection}>
<Text style={styles.sectionLabel}>Invoice (optional)</Text>
{!clientId ? (
<Text style={styles.emptyClients}>
No invoice for now. Add a client and invoice later if this becomes billable.
</Text>
) : (
<View style={styles.chipWrap}>
<FilterChip label="Entry only" active={!invoiceId} onPress={() => setInvoiceId("")} />
{billableInvoices.map((invoice) => {
const label = `${invoice.invoicePrefix ?? "#"}${invoice.invoiceNumber}`;
return (
<FilterChip
key={invoice.id}
label={label}
active={invoiceId === invoice.id}
onPress={() => setInvoiceId(invoice.id)}
/>
);
})}
<SelectField
label="Invoice (optional)"
placeholder={clientId ? "Select an invoice" : "Choose a client first"}
value={clientId ? invoiceId : "__client_required__"}
disabled={!clientId}
options={[
{ label: "Entry only — no invoice", value: "" },
...billableInvoices.map((invoice) => ({
label: `${invoice.invoicePrefix ?? "#"}${invoice.invoiceNumber}`,
value: invoice.id,
})),
]}
onValueChange={selectInvoice}
containerStyle={styles.timerField}
/>
</View>
)}
</View>
<View style={styles.setupSection}>
<Pressable
@@ -736,9 +664,8 @@ export function TimeClockPanel({
)}
</GlassSurface>
{todayEntries.length > 0 ? (
<Card title="Today's entries">
{todayEntries.map((entry) => {
<Card title={`Today · ${todayHours.toFixed(2)}h`}>
{todayEntries.length > 0 ? todayEntries.map((entry) => {
const invoiceLabel = entry.invoice
? `${entry.invoice.invoicePrefix ?? "#"}${entry.invoice.invoiceNumber}`
: null;
@@ -783,9 +710,20 @@ export function TimeClockPanel({
</View>
</SwipeableRow>
);
})}
</Card>
) : null}
}) : (
<View style={styles.todayEmpty}>
<Text style={styles.todayEmptyTitle}>No time logged yet</Text>
<Text style={styles.todayEmptyCopy}>
Start your first timer or open history to add an entry manually.
</Text>
</View>
)}
<Button
title="View time history"
variant="secondary"
onPress={() => router.push("/(app)/more/time-entries")}
/>
</Card>
<TimeEntryEditSheet
entryId={editEntryId}
@@ -857,25 +795,45 @@ const createTimeClockStyles = (colors: ThemeColors, isDark: boolean) =>
},
setupCard: {
padding: spacing.lg,
gap: spacing.lg,
gap: spacing.md,
},
cardTitle: {
fontSize: 16,
idleIntro: {
gap: spacing.xs,
paddingBottom: spacing.xs,
},
idleEyebrow: {
fontSize: 11,
fontFamily: fonts.bodySemiBold,
color: colors.mutedForeground,
textTransform: "uppercase",
letterSpacing: 0.7,
},
idleTitle: {
fontSize: 22,
lineHeight: 28,
fontFamily: fonts.heading,
color: colors.foreground,
},
idleCopy: {
fontSize: 13,
lineHeight: 18,
fontFamily: fonts.body,
color: colors.mutedForeground,
},
formSection: {
gap: spacing.md,
},
titleField: {
fontSize: 18,
fontFamily: fonts.bodyMedium,
minHeight: 48,
paddingVertical: spacing.xs,
},
idleFields: {
gap: spacing.md,
},
timerField: {
gap: 6,
},
setupSection: {
gap: spacing.sm,
paddingTop: spacing.lg,
},
sectionLabel: {
fontSize: 11,
@@ -892,9 +850,6 @@ const createTimeClockStyles = (colors: ThemeColors, isDark: boolean) =>
flexWrap: "wrap",
gap: spacing.sm,
},
moreClientsWrap: {
paddingTop: spacing.xs,
},
emptyClients: {
fontSize: 14,
fontFamily: fonts.body,
@@ -996,4 +951,23 @@ const createTimeClockStyles = (colors: ThemeColors, isDark: boolean) =>
color: colors.foreground,
fontSize: 14,
},
todayEmpty: {
alignItems: "center",
gap: spacing.xs,
paddingVertical: spacing.lg,
paddingHorizontal: spacing.md,
},
todayEmptyTitle: {
fontFamily: fonts.bodySemiBold,
color: colors.foreground,
fontSize: 14,
textAlign: "center",
},
todayEmptyCopy: {
fontFamily: fonts.body,
color: colors.mutedForeground,
fontSize: 13,
lineHeight: 18,
textAlign: "center",
},
});
@@ -62,7 +62,12 @@ export function DateTimeField({
<View style={styles.wrapper}>
<Text style={[styles.label, { color: colors.mutedForeground }]}>{label}</Text>
<Pressable
accessible
accessibilityLabel={`${label}, ${
mode === "date" ? formatDate(value) : formatDateTime(value)
}`}
accessibilityRole="button"
accessibilityState={{ expanded: open }}
onPress={openPicker}
style={({ pressed }) => [
styles.trigger,
+5 -1
View File
@@ -3,7 +3,9 @@ import {
Text,
TextInput,
View,
type StyleProp,
type TextInputProps,
type ViewStyle,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
@@ -17,6 +19,7 @@ type InputProps = TextInputProps & {
leftIcon?: keyof typeof Ionicons.glyphMap;
labelAccessory?: React.ReactNode;
hint?: string;
containerStyle?: StyleProp<ViewStyle>;
};
export function Input({
@@ -26,13 +29,14 @@ export function Input({
leftIcon,
labelAccessory,
hint,
containerStyle,
style,
...props
}: InputProps) {
const { colors } = useAppTheme();
return (
<View style={styles.wrapper}>
<View style={[styles.wrapper, containerStyle]}>
<View style={styles.labelRow}>
<Text style={[styles.label, { color: colors.foreground }]}>
{label}
+19 -5
View File
@@ -7,6 +7,8 @@ import {
StyleSheet,
Text,
View,
type StyleProp,
type ViewStyle,
} from "react-native";
import { fonts, radii, spacing } from "@/constants/theme";
@@ -26,6 +28,8 @@ type SelectFieldProps = {
required?: boolean;
error?: string;
onValueChange: (value: string) => void;
onBlur?: () => void;
containerStyle?: StyleProp<ViewStyle>;
};
export function SelectField({
@@ -37,19 +41,29 @@ export function SelectField({
required,
error,
onValueChange,
onBlur,
containerStyle,
}: SelectFieldProps) {
const { colors } = useAppTheme();
const [open, setOpen] = useState(false);
const selected = options.find((option) => option.value === value);
function close() {
setOpen(false);
onBlur?.();
}
return (
<View style={styles.wrapper}>
<View style={[styles.wrapper, containerStyle]}>
<Text style={[styles.label, { color: colors.foreground }]}>
{label}
{required ? <Text style={{ color: colors.destructive }}> *</Text> : null}
</Text>
<Pressable
accessible
accessibilityLabel={`${label}, ${selected?.label ?? placeholder}`}
accessibilityRole="button"
accessibilityState={{ disabled: Boolean(disabled), expanded: open }}
disabled={disabled}
onPress={() => setOpen(true)}
style={({ pressed }) => [
@@ -77,18 +91,18 @@ export function SelectField({
<Modal
animationType="slide"
onRequestClose={() => setOpen(false)}
onRequestClose={close}
transparent
visible={open}
>
<Pressable style={styles.backdrop} onPress={() => setOpen(false)}>
<Pressable style={styles.backdrop} onPress={close}>
<Pressable
style={[styles.sheet, { backgroundColor: colors.background }]}
onPress={(event) => event.stopPropagation()}
>
<View style={[styles.sheetHeader, { borderBottomColor: colors.border }]}>
<Text style={[styles.sheetTitle, { color: colors.foreground }]}>{label}</Text>
<Pressable accessibilityRole="button" onPress={() => setOpen(false)}>
<Pressable accessibilityRole="button" onPress={close}>
<Text style={[styles.done, { color: colors.primary }]}>Done</Text>
</Pressable>
</View>
@@ -101,7 +115,7 @@ export function SelectField({
accessibilityRole="button"
onPress={() => {
onValueChange(option.value);
setOpen(false);
close();
}}
style={({ pressed }) => [
styles.option,
+56
View File
@@ -0,0 +1,56 @@
const DARK_ACTION_FOREGROUND = "#18181B";
const LIGHT_ACTION_FOREGROUND = "#FFFFFF";
const MIN_TEXT_CONTRAST = 4.5;
function parseHexColor(color: string): [number, number, number] | null {
const value = color.trim().replace(/^#/, "");
const expanded =
value.length === 3
? value
.split("")
.map((character) => character.repeat(2))
.join("")
: value.slice(0, 6);
if (expanded.length !== 6 || !/^[0-9a-f]+$/i.test(expanded)) return null;
return [
Number.parseInt(expanded.slice(0, 2), 16),
Number.parseInt(expanded.slice(2, 4), 16),
Number.parseInt(expanded.slice(4, 6), 16),
];
}
function luminance(color: string): number | null {
const rgb = parseHexColor(color);
if (!rgb) return null;
const channels = rgb.map((channel) => {
const value = channel / 255;
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * channels[0]! + 0.7152 * channels[1]! + 0.0722 * channels[2]!;
}
function contrastRatio(foreground: string, background: string): number | null {
const foregroundLuminance = luminance(foreground);
const backgroundLuminance = luminance(background);
if (foregroundLuminance == null || backgroundLuminance == null) return null;
const lighter = Math.max(foregroundLuminance, backgroundLuminance);
const darker = Math.min(foregroundLuminance, backgroundLuminance);
return (lighter + 0.05) / (darker + 0.05);
}
/** Chooses a readable action label/icon color while preserving a valid requested color. */
export function resolveActionForeground(background: string, requested: string): string {
const requestedContrast = contrastRatio(requested, background);
if (requestedContrast == null || requestedContrast >= MIN_TEXT_CONTRAST) {
return requested;
}
const darkContrast = contrastRatio(DARK_ACTION_FOREGROUND, background) ?? 0;
const lightContrast = contrastRatio(LIGHT_ACTION_FOREGROUND, background) ?? 0;
return darkContrast >= lightContrast ? DARK_ACTION_FOREGROUND : LIGHT_ACTION_FOREGROUND;
}
+35 -37
View File
@@ -11,6 +11,18 @@ const CHUNK_MARKER = "\u0001ba-chunks:";
const SESSION_TOKEN_COOKIE_PART =
/(?:^|;\s*)(?:__Secure-)?[^=]*session_token=([^;]+)/;
const AUTH_COOKIE_DEBUG = process.env.EXPO_PUBLIC_AUTH_COOKIE_DEBUG === "1";
const lastAuthCookieDebugState = new Map<string, string>();
function debugAuthCookie(event: string, storagePrefix: string, details: Record<string, unknown>) {
if (!AUTH_COOKIE_DEBUG) return;
const key = `${event}:${storagePrefix}`;
const state = JSON.stringify(details);
if (lastAuthCookieDebugState.get(key) === state) return;
lastAuthCookieDebugState.set(key, state);
console.info(`[auth-cookie] ${event}`, { storagePrefix, ...details });
}
function readSecureStoreValueSync(key: string): string | null {
const value = SecureStore.getItem(key);
@@ -56,25 +68,19 @@ export function getAuthCookie(
).getCookie?.();
if (fromClient?.trim()) {
const cookie = fromClient.trim();
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] using client cookie", {
storagePrefix,
length: cookie.length,
names: cookieNames(cookie),
});
}
debugAuthCookie("using client cookie", storagePrefix, {
length: cookie.length,
names: cookieNames(cookie),
});
return cookie;
}
const fromPrefix = readStoredCookie(storagePrefix);
if (fromPrefix) {
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] using stored cookie", {
storagePrefix,
length: fromPrefix.length,
names: cookieNames(fromPrefix),
});
}
debugAuthCookie("using stored cookie", storagePrefix, {
length: fromPrefix.length,
names: cookieNames(fromPrefix),
});
return fromPrefix;
}
@@ -82,18 +88,15 @@ export function getAuthCookie(
storagePrefix === GUEST_AUTH_STORAGE_PREFIX
? null
: readStoredCookie(GUEST_AUTH_STORAGE_PREFIX);
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] resolved tRPC cookie", {
storagePrefix,
fallbackPrefix:
fromGuest && storagePrefix !== GUEST_AUTH_STORAGE_PREFIX
? GUEST_AUTH_STORAGE_PREFIX
: null,
hasCookie: Boolean(fromGuest),
length: fromGuest?.length ?? 0,
names: fromGuest ? cookieNames(fromGuest) : [],
});
}
debugAuthCookie("resolved tRPC cookie", storagePrefix, {
fallbackPrefix:
fromGuest && storagePrefix !== GUEST_AUTH_STORAGE_PREFIX
? GUEST_AUTH_STORAGE_PREFIX
: null,
hasCookie: Boolean(fromGuest),
length: fromGuest?.length ?? 0,
names: fromGuest ? cookieNames(fromGuest) : [],
});
return fromGuest;
}
@@ -103,21 +106,16 @@ export function getAuthCookieHeaders(
): Record<string, string> {
const cookie = getAuthCookie(authClient, storagePrefix);
if (!cookie) {
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] no tRPC auth cookie", { storagePrefix });
}
debugAuthCookie("no tRPC auth cookie", storagePrefix, {});
return {};
}
const sessionToken = cookie.match(SESSION_TOKEN_COOKIE_PART)?.[1];
if (AUTH_COOKIE_DEBUG) {
console.info("[auth-cookie] sending tRPC auth headers", {
storagePrefix,
cookieLength: cookie.length,
cookieNames: cookieNames(cookie),
hasSessionTokenHeader: Boolean(sessionToken),
});
}
debugAuthCookie("sending tRPC auth headers", storagePrefix, {
cookieLength: cookie.length,
cookieNames: cookieNames(cookie),
hasSessionTokenHeader: Boolean(sessionToken),
});
return {
cookie,
Cookie: cookie,
+8 -3
View File
@@ -1,7 +1,12 @@
/** Matches web invoice-form default numbering. */
export function generateInvoiceNumber(): string {
const date = new Date().toISOString().slice(0, 10).replace(/-/g, "");
return `INV-${date}-${String(Date.now()).slice(-6)}`;
export function generateInvoiceNumber(now = new Date()): string {
const date = [
now.getFullYear(),
String(now.getMonth() + 1).padStart(2, "0"),
String(now.getDate()).padStart(2, "0"),
].join("");
return `INV-${date}-${String(now.getTime()).slice(-6)}`;
}
export function defaultDueDate(issueDate: Date): Date {
+1 -4
View File
@@ -6,9 +6,6 @@ import { spacing } from "@/constants/theme";
/** Standard UITabBar content height (home indicator is separate). */
const IOS_TAB_BAR_HEIGHT = 49;
/** Trim extra inset so scroll content sits closer to the tab bar. */
const TAB_BAR_PADDING_TRIM = spacing.lg;
/**
* Pixels between the bottom of the safe-area layout frame and the window bottom.
*/
@@ -39,7 +36,7 @@ export function useTabBarScrollPadding(): number {
const tabBar = useNativeTabBarHeight();
const clearance = tabBar + homeIndicator;
return Math.max(spacing.xs, clearance - TAB_BAR_PADDING_TRIM);
return clearance + spacing.sm;
}
/** Bottom offset for floating action buttons above the tab bar. */
@@ -10,7 +10,9 @@ import {
import { fetchAuthCapabilities } from "../lib/auth-capabilities";
import { EXPENSE_CATEGORIES as appExpenseCategories } from "../lib/expense-categories";
import { getInvoiceStatus } from "../lib/invoice-status";
import { generateInvoiceNumber as generateMobileInvoiceNumber } from "../lib/invoice-number";
import { formatElapsedSeconds as formatAppElapsedSeconds } from "../lib/time-clock";
import { generateInvoiceNumber as generateWebInvoiceNumber } from "../../web/src/lib/draft-invoice";
import { safeCallbackPath } from "../../web/src/lib/safe-callback-url";
import {
normalizeOptionalId,
@@ -47,6 +49,13 @@ describe("auth contract smoke checks", () => {
});
describe("invoice parity", () => {
test("web and mobile use the device-local date in invoice numbers", () => {
const lateLocalEvening = new Date(2026, 7, 16, 23, 30, 0, 123);
expect(generateMobileInvoiceNumber(lateLocalEvening)).toStartWith("INV-20260816-");
expect(generateWebInvoiceNumber(lateLocalEvening)).toStartWith("INV-20260816-");
});
test("web and mobile agree on draft, paid, sent, and overdue states", () => {
const today = new Date();
today.setHours(0, 0, 0, 0);
+19
View File
@@ -0,0 +1,19 @@
/// <reference types="bun" />
import { describe, expect, test } from "bun:test";
import { resolveActionForeground } from "../lib/action-contrast";
describe("swipe action contrast", () => {
test("uses dark content on bright dark-mode action colors", () => {
expect(resolveActionForeground("#FAFAFA", "#FFFFFF")).toBe("#18181B");
expect(resolveActionForeground("#A1A1AA", "#FFFFFF")).toBe("#18181B");
expect(resolveActionForeground("#4ADE80", "#FFFFFF")).toBe("#18181B");
expect(resolveActionForeground("#FBBF24", "#FFFFFF")).toBe("#18181B");
expect(resolveActionForeground("#F87171", "#FFFFFF")).toBe("#18181B");
});
test("keeps white content on the light-mode primary action", () => {
expect(resolveActionForeground("#18181B", "#FFFFFF")).toBe("#FFFFFF");
});
});