Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions apps/frontend/src/components/NearbyVenues.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Link } from '@tanstack/react-router'

import { HarpIcon } from '#/components/HarpIcon'
import { OpenStatusChip } from '#/components/OpenStatusChip'
import { formatOpeningHours } from '#/lib/format-opening-hours'
import { formatPrice } from '#/lib/format-price'
import { useUserTimeZone } from '#/lib/use-user-time-zone'
Expand Down Expand Up @@ -36,8 +37,14 @@ export function NearbyVenueRow({
}) {
return (
<>
<span className="flex items-baseline justify-between gap-3">
<span className="font-semibold">{venue.name}</span>
<span className="flex items-center justify-between gap-3">
<span className="flex min-w-0 flex-wrap items-center gap-2">
<span className="font-semibold">{venue.name}</span>
<OpenStatusChip
openingHours={venue.openingHours}
timeZone={timeZone}
/>
</span>
{venue.averageRating != null && (
<span
title={`Average rating ${venue.averageRating.toFixed(1)} out of 5 from ${
Expand Down
55 changes: 55 additions & 0 deletions apps/frontend/src/components/OpenStatusChip.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { getOpenStatus } from '#/lib/opening-hours'
import { useNow } from '#/lib/use-now'
import type { OpeningHoursLike, OpenStatus } from '#/lib/opening-hours'

const STATUS_LABELS: Record<OpenStatus, string> = {
open: 'Open now',
closed: 'Closed',
unknown: 'Hours unknown',
}

const STATUS_TITLES: Record<OpenStatus, string> = {
open: 'Open right now',
closed: 'Closed right now',
unknown: 'No opening hours available',
}

const STATUS_STYLES: Record<OpenStatus, string> = {
open: 'border-emerald-600/30 bg-emerald-500/15 text-(--sea-ink)',
closed: 'border-rose-600/30 bg-rose-500/15 text-(--sea-ink)',
unknown: 'border-(--line) bg-(--chip-bg) text-(--sea-ink-soft)',
}

const DOT_STYLES: Record<OpenStatus, string> = {
open: 'bg-emerald-500',
closed: 'bg-rose-500',
unknown: 'bg-(--sea-ink-soft)',
}

export function OpenStatusChip({
openingHours,
timeZone = 'Europe/Oslo',
className = '',
}: {
openingHours: readonly OpeningHoursLike[] | null | undefined
timeZone?: string
className?: string
}) {
const now = useNow()
const status = getOpenStatus(openingHours, timeZone, now)

return (
<span
title={STATUS_TITLES[status]}
className={`inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-bold ${STATUS_STYLES[status]} ${className}`.trim()}
>
<span
aria-hidden="true"
className={`size-1.5 rounded-full ${DOT_STYLES[status]}`}
/>
{STATUS_LABELS[status]}
</span>
)
}

export default OpenStatusChip
10 changes: 10 additions & 0 deletions apps/frontend/src/components/SearchBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import { useNavigate, useSearch } from '@tanstack/react-router'
import { useEffect, useId, useMemo, useState } from 'react'
import { CountryLabel } from '#/components/CountryLabel'
import { HarpIcon } from '#/components/HarpIcon'
import { OpenStatusChip } from '#/components/OpenStatusChip'
import type { FormEvent, KeyboardEvent } from 'react'

import { graphqlFetch } from '../graphql/client'
import { formatPrice } from '../lib/format-price'
import { searchFilterVariables } from '../lib/search-filters'
import type { SearchQueryParams } from '../lib/search-filters'
import { useDebounce } from '../lib/use-debounce'
import { useUserTimeZone } from '../lib/use-user-time-zone'
import type { Coordinates } from '../lib/location'
import type { SearchFilters, SearchResult } from '../types/search'

Expand Down Expand Up @@ -122,6 +124,7 @@ export function SearchBox({
const searchTerm = useSearch({ from, select: (search) => search.q })
const inputId = useId()
const listId = useId()
const timeZone = useUserTimeZone()

const term = searchTerm ?? ''
// The URL is the source of truth for the term, but the request should only
Expand Down Expand Up @@ -337,6 +340,13 @@ export function SearchBox({
<span className="ml-2 rounded-full px-1.5 py-0.5 text-[0.65rem] font-bold tracking-wide uppercase text-(--sea-ink-soft)">
{typeLabel(result)}
</span>
{result.type === 'venue' && (
<OpenStatusChip
openingHours={result.openingHours}
timeZone={timeZone}
className="ml-2"
/>
)}
</span>
{result.averageRating != null && (
<span
Expand Down
9 changes: 8 additions & 1 deletion apps/frontend/src/components/ViewVenue.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { IconRouteSquare } from '@tabler/icons-react'
import { HarpIcon } from '#/components/HarpIcon'
import { OpenStatusChip } from '#/components/OpenStatusChip'
import {
formatOpeningDays,
formatOpeningTime,
Expand All @@ -22,7 +23,13 @@ export function ViewVenue({
<article className="rounded-2xl bg-(--surface-strong) p-5 text-(--sea-ink)">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h2 className="mt-1 text-xl font-extrabold">{venue.name}</h2>
<div className="flex flex-wrap items-center gap-2">
<h2 className="mt-1 text-xl font-extrabold">{venue.name}</h2>
<OpenStatusChip
openingHours={venue.openingHours}
timeZone={timeZone}
/>
</div>
</div>
{venue.averageRating != null && (
<p
Expand Down
40 changes: 40 additions & 0 deletions apps/frontend/src/components/__tests__/OpenStatusChip.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'

import { OpenStatusChip } from '../OpenStatusChip'

const weekdayHours = {
days: ['MON', 'TUE', 'WED', 'THU', 'FRI'],
opening: '2026-10-01T14:00:00.000Z',
closing: '2026-10-02T02:00:00.000Z',
}

describe('OpenStatusChip', () => {
afterEach(() => {
vi.useRealTimers()
})

it('shows when a venue is open', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-10-05T15:00:00.000Z'))

render(<OpenStatusChip openingHours={[weekdayHours]} timeZone="UTC" />)

expect(screen.getByText('Open now')).toBeInTheDocument()
})

it('shows when a venue is closed', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-10-05T03:00:00.000Z'))

render(<OpenStatusChip openingHours={[weekdayHours]} timeZone="UTC" />)

expect(screen.getByText('Closed')).toBeInTheDocument()
})

it('shows an unknown state when hours are missing', () => {
render(<OpenStatusChip openingHours={null} timeZone="UTC" />)

expect(screen.getByText('Hours unknown')).toBeInTheDocument()
})
})
85 changes: 85 additions & 0 deletions apps/frontend/src/lib/__tests__/opening-hours.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { describe, expect, it } from 'vitest'

import { getOpenStatus } from '../opening-hours'

const weekdayHours = {
days: ['MON', 'TUE', 'WED', 'THU', 'FRI'],
opening: '2026-10-01T14:00:00.000Z',
closing: '2026-10-02T02:00:00.000Z',
}

describe('getOpenStatus', () => {
it('returns open during a same-day interval', () => {
expect(
getOpenStatus(
[weekdayHours],
'UTC',
new Date('2026-10-05T15:00:00.000Z'),
),
).toBe('open')
})

it('returns closed before opening', () => {
expect(
getOpenStatus(
[weekdayHours],
'UTC',
new Date('2026-10-05T03:00:00.000Z'),
),
).toBe('closed')
})

it('returns open after midnight for the previous day schedule', () => {
expect(
getOpenStatus(
[weekdayHours],
'UTC',
new Date('2026-10-06T01:00:00.000Z'),
),
).toBe('open')
expect(
getOpenStatus(
[weekdayHours],
'UTC',
new Date('2026-10-03T01:00:00.000Z'),
),
).toBe('open')
})

it('returns closed after an overnight interval ends', () => {
expect(
getOpenStatus(
[weekdayHours],
'UTC',
new Date('2026-10-06T03:00:00.000Z'),
),
).toBe('closed')
})

it('returns open for a matching weekend schedule', () => {
expect(
getOpenStatus(
[
{
days: ['SAT', 'SUN'],
opening: '2026-10-01T12:00:00.000Z',
closing: '2026-10-01T23:00:00.000Z',
},
],
'UTC',
new Date('2026-10-04T15:00:00.000Z'),
),
).toBe('open')
})

it('returns unknown when no usable schedule exists', () => {
expect(getOpenStatus([], 'UTC', new Date())).toBe('unknown')
expect(
getOpenStatus(
[{ ...weekdayHours, days: [] }],
'UTC',
new Date('2026-10-05T15:00:00.000Z'),
),
).toBe('unknown')
})
})
116 changes: 116 additions & 0 deletions apps/frontend/src/lib/opening-hours.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { DAYS } from './days'
import type { Day } from './days'
import { formatOpeningTime } from './format-opening-hours'

/**
* Opening hours are stored as `timetz` values. The date part is only a
* reference and never shown, so we attach times to a fixed date in the
Expand All @@ -6,3 +10,115 @@
export function timeToIso(time: string): string {
return new Date(`2000-01-01T${time}:00+01:00`).toISOString()
}

export interface OpeningHoursLike {
days: string[]
opening: string
closing: string
}

export type OpenStatus = 'open' | 'closed' | 'unknown'

const localTimeFormatters = new Map<string, Intl.DateTimeFormat>()

function getLocalTimeFormatter(timeZone: string) {
const existing = localTimeFormatters.get(timeZone)

if (existing) return existing

const formatter = new Intl.DateTimeFormat('en-GB', {
timeZone,
weekday: 'short',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
})
localTimeFormatters.set(timeZone, formatter)

return formatter
}

function isDay(value: string): value is Day {
return (DAYS as readonly string[]).includes(value)
}

function getLocalDayAndMinutes(now: Date, timeZone: string) {
const parts = getLocalTimeFormatter(timeZone).formatToParts(now)
const day = (parts.find((part) => part.type === 'weekday')?.value ?? '')
.slice(0, 3)
.toUpperCase()
const hour = Number(parts.find((part) => part.type === 'hour')?.value)
const minute = Number(parts.find((part) => part.type === 'minute')?.value)

if (!isDay(day) || !Number.isFinite(hour) || !Number.isFinite(minute)) {
return null
}

return { day, minutes: hour * 60 + minute }
}

function timeToMinutes(iso: string, timeZone: string) {
try {
const [hour, minute] = formatOpeningTime(iso, timeZone)
.split(':')
.map(Number)

return Number.isFinite(hour) && Number.isFinite(minute)
? hour * 60 + minute
: null
} catch {
return null
}
}

/**
* Returns whether any opening-hours interval covers the current moment.
* Overnight intervals belong to the day they open, so the previous day's
* schedule is also checked for closures after midnight.
*/
export function getOpenStatus(
entries: readonly OpeningHoursLike[] | null | undefined,
timeZone = 'Europe/Oslo',
now = new Date(),
): OpenStatus {
if (!entries || entries.length === 0) return 'unknown'

const local = getLocalDayAndMinutes(now, timeZone)

if (!local) return 'unknown'

const todayIndex = DAYS.indexOf(local.day)
const yesterday = DAYS[(todayIndex + DAYS.length - 1) % DAYS.length]
let hasValidSchedule = false

for (const entry of entries) {
const days = entry.days.map((day) => day.toUpperCase())
const opening = timeToMinutes(entry.opening, timeZone)
const closing = timeToMinutes(entry.closing, timeZone)

if (opening === null || closing === null || !days.some(isDay)) {
continue
}

hasValidSchedule = true

const opensToday = days.includes(local.day)
const openedYesterday = days.includes(yesterday)

if (opening === closing) {
if (opensToday) return 'open'
continue
}

if (closing > opening) {
if (opensToday && local.minutes >= opening && local.minutes < closing) {
return 'open'
}
} else {
if (opensToday && local.minutes >= opening) return 'open'
if (openedYesterday && local.minutes < closing) return 'open'
}
}

return hasValidSchedule ? 'closed' : 'unknown'
}
Loading