Merchant Hours
Weekly opening hours with breaks, overnight windows, dated overrides and a local current status.
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 merchant-hoursSource files
Expand a file to read the source the installer copies into your app.
components/blocks/merchant-hours/MerchantHours.tsx
import { useMemo } from 'react'
import { View, type ViewProps } from 'react-native'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Text } from '@/components/ui/text'
import { useAnnouncement } from '@/lib/accessibility'
import { cn } from '@/lib/utils'
import {
merchantDate,
merchantWeekdays,
resolveMerchantHours,
validMerchantWindows,
weekdayFor,
type MerchantHoursOverrides,
type MerchantHoursWindow,
type MerchantLocalTime,
type MerchantWeeklyHours,
} from './hours'
interface MerchantHoursLabels {
regular: string
special: string
open: string
closedNow: string
unknown: string
closes: string
opens: string
overnight: string
closed: string
allDay: string
directions: string
}
export interface MerchantHoursProps extends Omit<ViewProps, 'children'> {
className?: string
title?: string
weekly?: MerchantWeeklyHours
overrides?: MerchantHoursOverrides
/** Supply this from the location's clock, not from the phone's local wall time. */
localNow?: MerchantLocalTime
locale?: string
timeZoneLabel?: string
labels?: Partial<MerchantHoursLabels>
onDirections?: () => void
}
const noOverrides: MerchantHoursOverrides = {}
function dateFormat(locale?: string) {
let resolvedLocale: string | undefined
try {
resolvedLocale = (locale && Intl.getCanonicalLocales(locale)[0]) || undefined
} catch {
// A malformed optional locale should not obscure the store's posted hours.
}
return {
time: new Intl.DateTimeFormat(resolvedLocale, { timeZone: 'UTC', hour: 'numeric', minute: '2-digit' }),
weekday: new Intl.DateTimeFormat(resolvedLocale, { timeZone: 'UTC', weekday: 'long' }),
date: new Intl.DateTimeFormat(resolvedLocale, { timeZone: 'UTC', month: 'short', day: 'numeric', year: 'numeric' }),
}
}
export function MerchantHours({
className,
title = 'Store hours',
weekly,
overrides = noOverrides,
localNow,
locale,
timeZoneLabel,
labels,
onDirections,
...props
}: MerchantHoursProps) {
const format = useMemo(() => dateFormat(locale), [locale])
const availability = useMemo(() => resolveMerchantHours(weekly, overrides, localNow), [weekly, overrides, localNow])
const today = localNow && merchantDate(localNow.date)
const weekday = today ? weekdayFor(today) : undefined
const overrideDates = Object.keys(overrides)
.map((date) => ({ key: date, date: merchantDate(date) }))
.filter((entry): entry is { key: string; date: Date } => Boolean(entry.date && (!today || entry.date >= today)))
.sort((first, second) => first.date.valueOf() - second.date.valueOf())
function time(minute: number) {
return format.time.format(new Date(Date.UTC(2024, 0, 1, 0, minute)))
}
function describeMoment(moment: MerchantLocalTime) {
if (moment.date === localNow?.date) return time(moment.minute)
const date = merchantDate(moment.date)
return `${date ? format.date.format(date) : moment.date}, ${time(moment.minute)}`
}
function describeWindows(windows: readonly MerchantHoursWindow[] | undefined) {
const sorted = validMerchantWindows(windows)
if (sorted.length === 0) return labels?.closed ?? 'Closed'
if (sorted.some(({ opens, closes }) => opens === 0 && closes === 1440)) return labels?.allDay ?? 'Open 24 hours'
return sorted
.map(({ opens, closes }) => {
const overnight = closes < opens || closes === 1440
return `${time(opens)}–${time(closes)}${overnight ? ` (${labels?.overnight ?? 'next day'})` : ''}`
})
.join('\n')
}
const status =
availability.state === 'open'
? (labels?.open ?? 'Open now')
: availability.state === 'closed'
? (labels?.closedNow ?? 'Closed now')
: (labels?.unknown ?? 'Current hours unavailable')
const transition =
availability.state === 'open' && availability.closes
? `${labels?.closes ?? 'Closes at'} ${describeMoment(availability.closes)}`
: availability.state === 'closed' && availability.next
? `${labels?.opens ?? 'Opens at'} ${describeMoment(availability.next)}`
: undefined
useAnnouncement(transition ? `${status}. ${transition}` : status)
return (
<View {...props} className={cn('gap-[16px]', className)}>
<View className="gap-[4px]">
<Text size="title" accessibilityRole="header">
{title}
</Text>
{timeZoneLabel ? (
<Text size="sm" variant="muted">
{timeZoneLabel}
</Text>
) : null}
</View>
<View className="gap-[8px] rounded-lg border border-border bg-card p-[16px]">
<View className="items-start">
<Badge variant={availability.state === 'open' ? 'success' : 'secondary'}>{status}</Badge>
</View>
{transition ? <Text className="font-medium text-card-foreground">{transition}</Text> : null}
</View>
{overrideDates.length ? (
<View className="gap-[8px]">
<Text accessibilityRole="header" className="font-semibold">
{labels?.special ?? 'Special hours'}
</Text>
{overrideDates.map(({ key, date }) => (
<View key={key} className="gap-[4px] border-b border-border py-[8px]">
<Text className="font-medium">{format.date.format(date)}</Text>
{overrides[key].label ? (
<Text size="sm" variant="muted">
{overrides[key].label}
</Text>
) : null}
<Text size="sm">{describeWindows(overrides[key].windows)}</Text>
</View>
))}
</View>
) : null}
{weekly ? (
<View className="gap-[8px]">
<Text accessibilityRole="header" className="font-semibold">
{labels?.regular ?? 'Regular hours'}
</Text>
{merchantWeekdays.map((day, index) => (
<View
key={day}
className="flex-row flex-wrap items-start justify-between gap-[8px] border-b border-border py-[8px]"
>
<Text className={cn('min-w-[100px] shrink', weekday === day && 'font-semibold')}>
{format.weekday.format(new Date(Date.UTC(2024, 0, index + 1)))}
</Text>
<Text size="sm" variant="muted" className="shrink">
{describeWindows(weekly[day])}
</Text>
</View>
))}
</View>
) : null}
{onDirections ? (
<Button variant="outline" onPress={onDirections}>
{labels?.directions ?? 'Get directions'}
</Button>
) : null}
</View>
)
}
components/blocks/merchant-hours/hours.ts
export const merchantWeekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] as const
export type MerchantWeekday = (typeof merchantWeekdays)[number]
/** Minutes from local midnight. A closing minute below opening continues into the next day. */
export interface MerchantHoursWindow {
opens: number
closes: number
}
export type MerchantWeeklyHours = Partial<Record<MerchantWeekday, readonly MerchantHoursWindow[]>>
export interface MerchantHoursOverride {
label?: string
/** Replaces the entire local date, including any window that would otherwise continue from yesterday. */
windows: readonly MerchantHoursWindow[]
}
export type MerchantHoursOverrides = Readonly<Record<string, MerchantHoursOverride>>
export interface MerchantLocalTime {
/** Calendar date at the business, YYYY-MM-DD. */
date: string
/** The business's local clock, expressed in minutes since midnight. */
minute: number
}
export type MerchantHoursAvailability =
{ state: 'unknown' } | { state: 'open'; closes?: MerchantLocalTime } | { state: 'closed'; next?: MerchantLocalTime }
const MINUTES_PER_DAY = 1440
const MILLIS_PER_DAY = 86_400_000
export function merchantDate(date: string): Date | undefined {
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return
// UTC is a calendar-arithmetic carrier. No device time zone conversion is performed.
const calendarDay = new Date(`${date}T00:00:00Z`)
if (Number.isFinite(calendarDay.valueOf()) && isoDate(calendarDay) === date) return calendarDay
}
function isoDate(day: Date) {
return day.toISOString().split('T')[0]
}
export function weekdayFor(day: Date): MerchantWeekday {
return merchantWeekdays[(day.getUTCDay() + 6) % 7]
}
export function validMerchantWindows(windows: readonly MerchantHoursWindow[] | undefined) {
return (windows ?? [])
.filter(
({ opens, closes }) =>
Number.isInteger(opens) &&
Number.isInteger(closes) &&
opens >= 0 &&
opens < MINUTES_PER_DAY &&
closes >= 0 &&
closes <= MINUTES_PER_DAY &&
opens !== closes,
)
.sort((first, second) => first.opens - second.opens)
}
function offsetDate(day: Date, offset: number) {
return new Date(day.valueOf() + offset * MILLIS_PER_DAY)
}
function toLocalTime(day: Date, offsetMinutes: number): MerchantLocalTime {
const offset = Math.floor(offsetMinutes / MINUTES_PER_DAY)
return { date: isoDate(offsetDate(day, offset)), minute: offsetMinutes - offset * MINUTES_PER_DAY }
}
export function resolveMerchantHours(
weekly: MerchantWeeklyHours | undefined,
overrides: MerchantHoursOverrides,
localNow: MerchantLocalTime | undefined,
): MerchantHoursAvailability {
const today = localNow && merchantDate(localNow.date)
if (
!weekly ||
!localNow ||
!today ||
!Number.isInteger(localNow.minute) ||
localNow.minute < 0 ||
localNow.minute >= MINUTES_PER_DAY
) {
return { state: 'unknown' }
}
const normalHours = merchantWeekdays.map((weekday) => validMerchantWindows(weekly[weekday]))
const recurring = normalHours.some((windows) => windows.length > 0)
const overrideOffsets = Object.keys(overrides)
.map(merchantDate)
.filter((date): date is Date => Boolean(date && date >= today))
.map((date) => (date.valueOf() - today.valueOf()) / MILLIS_PER_DAY)
// Each exception can suppress at most one occurrence of a recurring weekday.
const horizon = 7 * (overrideOffsets.length + 1)
const offsets = recurring
? Array.from({ length: horizon + 2 }, (_, index) => index - 1)
: [...new Set([-1, 0, ...overrideOffsets])]
const intervals = offsets
.flatMap((offset) => {
const day = offsetDate(today, offset)
const override = overrides[isoDate(day)]
const windows = override ? validMerchantWindows(override.windows) : normalHours[(day.getUTCDay() + 6) % 7]
return windows.map(({ opens, closes }) => ({
start: offset * MINUTES_PER_DAY + opens,
end:
offset * MINUTES_PER_DAY +
(closes > opens
? closes
: overrides[isoDate(offsetDate(day, 1))]
? MINUTES_PER_DAY
: MINUTES_PER_DAY + closes),
}))
})
.sort((first, second) => first.start - second.start)
const merged: typeof intervals = []
for (const interval of intervals) {
const last = merged.at(-1)
if (last && interval.start <= last.end) last.end = Math.max(last.end, interval.end)
else merged.push(interval)
}
const current = merged.find(({ start, end }) => start <= localNow.minute && localNow.minute < end)
if (current) {
// The artificial end of a 24/7 forecast is not a real closing time.
return recurring && current.end >= (horizon + 1) * MINUTES_PER_DAY
? { state: 'open' }
: { state: 'open', closes: toLocalTime(today, current.end) }
}
const next = merged.find(({ start }) => start > localNow.minute)
return next ? { state: 'closed', next: toLocalTime(today, next.start) } : { state: 'closed' }
}
components/blocks/merchant-hours/index.ts
export { MerchantHours, type MerchantHoursProps } from './MerchantHours'
export { resolveMerchantHours } from './hours'
export type {
MerchantHoursAvailability,
MerchantHoursOverride,
MerchantHoursOverrides,
MerchantHoursWindow,
MerchantLocalTime,
MerchantWeekday,
MerchantWeeklyHours,
} from './hours'