Habit Check-in
A weekly habit log with per-day status, a guarded check-in, and undo.
Install
First install? Set up the registry in your app.
npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add habit-check-inSource files
Expand a file to read the source the installer copies into your app.
components/blocks/habit-check-in/HabitCheckIn.tsx
import * as React from 'react'
import { View, type ViewProps } from 'react-native'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Text } from '@/components/ui/text'
import { WeekStrip, weekDateKeys, type WeekStripProps } from '@/components/ui/week-strip'
import { useAnnouncement } from '@/lib/accessibility'
import { cn } from '@/lib/utils'
const defaultLabels = {
progress: (logged: number, days: number) => `${logged} of ${days} days logged`,
logged: 'Logged',
open: 'No check-in logged',
chooseDay: 'Choose a day in this week.',
future: 'You can check in when this day arrives.',
unavailable: 'Check-in is currently unavailable.',
log: 'Log check-in',
undo: 'Undo check-in',
saving: 'Saving check-in…',
removing: 'Removing check-in…',
retry: 'Retry check-in update',
failed: 'Could not update this check-in. Your log is unchanged.',
confirmed: 'Check-in logged.',
removed: 'Check-in removed.',
}
type Change = { day: string; logged: boolean }
export interface HabitCheckInProps extends Omit<ViewProps, 'children'> {
className?: string
title: string
description?: string
/** A Gregorian date key in the displayed week. */
weekOf: string
weekStartsOn?: WeekStripProps['weekStartsOn']
/** The caller's complete log. Dates outside this week do not count towards its summary. */
loggedDays?: readonly string[]
day?: string | null
onDayChange?: (day: string) => void
/** Optional latest date the caller allows editing, in YYYY-MM-DD form. */
throughDate?: string
getUnavailableReason?: (day: string) => string | undefined
onLogChange: (day: string, logged: boolean) => void | boolean | Promise<void | boolean>
disabled?: boolean
locale?: string
labels?: Partial<typeof defaultLabels>
}
export function HabitCheckIn({
className,
title,
description,
weekOf,
weekStartsOn,
loggedDays = [],
day,
onDayChange,
throughDate,
getUnavailableReason,
onLogChange,
disabled = false,
locale,
labels,
...props
}: HabitCheckInProps) {
const copy = { ...defaultLabels, ...labels }
const [internalDay, setInternalDay] = React.useState<string>()
const [pending, setPending] = React.useState<Change>()
const [failed, setFailed] = React.useState<Change>()
const [confirmed, setConfirmed] = React.useState<Change>()
const request = React.useRef(false)
const days = React.useMemo(() => weekDateKeys(weekOf, weekStartsOn), [weekOf, weekStartsOn])
const history = new Set(loggedDays)
const count = days.filter((date) => history.has(date)).length
const selected = day === undefined ? (internalDay && days.includes(internalDay) ? internalDay : weekOf) : day
const shownDay = selected && days.includes(selected) ? selected : undefined
const logged = !!shownDay && history.has(shownDay)
const blockedDate = throughDate !== undefined && !weekDateKeys(throughDate, weekStartsOn).length
const unavailable = shownDay
? blockedDate
? copy.unavailable
: throughDate && shownDay > throughDate
? copy.future
: getUnavailableReason?.(shownDay)
: copy.chooseDay
const error =
shownDay && failed?.day === shownDay && failed.logged !== logged && !unavailable ? copy.failed : undefined
const result =
shownDay && confirmed?.day === shownDay && confirmed.logged === logged
? logged
? copy.confirmed
: copy.removed
: undefined
const label = pending
? pending.logged
? copy.saving
: copy.removing
: error
? copy.retry
: logged
? copy.undo
: copy.log
const selectedDateFormat = React.useMemo(
() =>
new Intl.DateTimeFormat(locale, {
timeZone: 'UTC',
calendar: 'gregory',
weekday: 'long',
month: 'short',
day: 'numeric',
}),
[locale],
)
React.useEffect(() => {
if (confirmed && confirmed.day !== shownDay) setConfirmed(undefined)
}, [confirmed, shownDay])
useAnnouncement(error || result)
async function change() {
if (!shownDay || unavailable || disabled || request.current) return
request.current = true
const attempt = { day: shownDay, logged: !logged }
setPending(attempt)
setFailed(undefined)
setConfirmed(undefined)
try {
if ((await onLogChange(attempt.day, attempt.logged)) === false) setFailed(attempt)
else setConfirmed(attempt)
} catch {
setFailed(attempt)
} finally {
request.current = false
setPending(undefined)
}
}
return (
<View {...props} className={cn('gap-4', className)}>
<View className="gap-1">
<Text size="xl" accessibilityRole="header">
{title}
</Text>
{description ? <Text variant="muted">{description}</Text> : null}
</View>
<View className="gap-2 rounded-xl border border-border bg-card p-3">
{days.length ? (
<Text size="sm" className="font-semibold">
{copy.progress(count, days.length)}
</Text>
) : null}
<WeekStrip
weekOf={weekOf}
weekStartsOn={weekStartsOn}
value={shownDay ?? null}
locale={locale}
disabled={disabled || !!pending}
getDateMarker={(date) => (history.has(date) ? copy.logged : undefined)}
onValueChange={(next) => {
if (request.current) return
if (day === undefined) setInternalDay(next)
onDayChange?.(next)
}}
/>
</View>
{shownDay ? (
<View className="gap-1">
<Text className="font-semibold">{selectedDateFormat.format(new Date(`${shownDay}T12:00:00Z`))}</Text>
<Text size="sm" variant="muted">
{logged ? copy.logged : copy.open}
</Text>
</View>
) : null}
{unavailable ? (
<Text size="sm" variant="muted">
{unavailable}
</Text>
) : null}
{error ? (
<Alert accessibilityRole="none" variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
) : null}
<Button
accessibilityLabel={label}
disabled={disabled || !!unavailable}
loading={!!pending}
variant={logged ? 'outline' : 'default'}
onPress={() => {
void change()
}}
>
{label}
</Button>
</View>
)
}
components/blocks/habit-check-in/index.ts
export { HabitCheckIn, type HabitCheckInProps } from './HabitCheckIn'