Audit Log Date Filter
Audit log with a date range filter: a count of matching events, a reset, and an empty state when nothing falls in the period.
"use client"
import { useId, useState } from "react"
import {
endOfDay,
format,
isWithinInterval,
startOfDay,
subDays,
} from "date-fns"
import type { DateRange } from "react-day-picker"
import { DateRangePicker } from "@/components/controls/date-range-picker"
import { Text } from "@/components/text/text"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
Empty,
EmptyContent,
EmptyDescription,
EmptyHeader,
EmptyTitle,
} from "@/components/ui/empty"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
// The sample "today". It is a fixed date so the server and the browser
// render the same days; every other date here counts from it. In your app,
// read the real date where you load the data.
const TODAY = new Date(2026, 10, 17)
// The copy: change text here, not in the markup.
const COPY = {
title: "Audit log",
description: "Changes to your projects, team and access.",
dates: "Dates",
placeholder: "All activity",
reset: "Reset",
count: (shown: number, total: number, filtered: boolean) =>
`${shown} of ${total} events${filtered ? " in this period" : " across all dates"}`,
event: "Event",
actor: "By",
when: "When",
emptyTitle: "No activity in this period",
emptyText: "Choose another date range or reset the filter to see all events.",
showAll: "Show all activity",
} as const
function eventTime(daysAgo: number, hour: number, minute: number) {
const date = subDays(TODAY, daysAgo)
date.setHours(hour, minute, 0, 0)
return date
}
const EVENTS = [
{
id: "e01",
date: eventTime(0, 14, 42),
action: "Deployment promoted",
detail: "Website / Production",
actor: "Rowan Hall",
},
{
id: "e02",
date: eventTime(0, 11, 8),
action: "API key rotated",
detail: "Production access",
actor: "Alex Lane",
},
{
id: "e03",
date: eventTime(1, 17, 26),
action: "Member invited",
detail: "ines@studio.example",
actor: "Priya Das",
},
{
id: "e04",
date: eventTime(2, 9, 10),
action: "Role updated",
detail: "Ines Park / Editor",
actor: "Alex Lane",
},
{
id: "e05",
date: eventTime(4, 15, 5),
action: "Project created",
detail: "Autumn collection",
actor: "Rowan Hall",
},
{
id: "e06",
date: eventTime(6, 13, 22),
action: "Webhook updated",
detail: "Release notifications",
actor: "Priya Das",
},
{
id: "e07",
date: eventTime(9, 10, 34),
action: "Domain verified",
detail: "studio.example",
actor: "Rowan Hall",
},
{
id: "e08",
date: eventTime(13, 16, 50),
action: "Access removed",
detail: "Temporary review account",
actor: "Alex Lane",
},
{
id: "e09",
date: eventTime(18, 12, 16),
action: "Deployment rolled back",
detail: "Website / Production",
actor: "Priya Das",
},
{
id: "e10",
date: eventTime(24, 8, 45),
action: "Project transferred",
detail: "Studio archive",
actor: "Rowan Hall",
},
{
id: "e11",
date: eventTime(31, 14, 8),
action: "API key created",
detail: "Preview deployments",
actor: "Alex Lane",
},
{
id: "e12",
date: eventTime(45, 10, 0),
action: "Workspace created",
detail: "North Studio",
actor: "Priya Das",
},
] as const
/**
* An audit log with a date range filter: the table, the count above it and
* the empty state all follow the chosen dates. Reset and "Show all
* activity" clear the filter.
*
* The words live in `COPY` and the sample events in `EVENTS`.
*/
export default function AuditLogDateFilter() {
const id = useId()
const [range, setRange] = useState<DateRange | undefined>({
from: subDays(TODAY, 6),
to: TODAY,
})
const visible = range?.from
? EVENTS.filter((event) =>
isWithinInterval(event.date, {
start: startOfDay(range.from!),
end: endOfDay(range.to ?? range.from!),
})
)
: EVENTS
return (
<Card
role="region"
aria-labelledby={`${id}-title`}
className="mx-auto w-full max-w-2xl"
>
<CardHeader>
<CardTitle>
<h2 id={`${id}-title`}>{COPY.title}</h2>
</CardTitle>
<CardDescription>{COPY.description}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-6">
<div className="flex flex-wrap items-end gap-2">
<DateRangePicker
label={COPY.dates}
value={range}
onValueChange={setRange}
placeholder={COPY.placeholder}
className="w-auto"
/>
<Button
type="button"
variant="ghost"
disabled={!range?.from}
onClick={() => setRange(undefined)}
>
{COPY.reset}
</Button>
</div>
<Text size="sm" variant="muted" role="status">
{COPY.count(visible.length, EVENTS.length, Boolean(range?.from))}
</Text>
{visible.length ? (
<Table>
<TableHeader>
<TableRow>
<TableHead>{COPY.event}</TableHead>
<TableHead>{COPY.actor}</TableHead>
<TableHead className="text-right">{COPY.when}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{visible.map((event) => (
<TableRow key={event.id}>
<TableCell className="whitespace-normal">
<div className="font-medium">{event.action}</div>
<div className="text-muted-foreground">{event.detail}</div>
</TableCell>
<TableCell>{event.actor}</TableCell>
<TableCell className="text-right tabular-nums">
<time dateTime={format(event.date, "yyyy-MM-dd'T'HH:mm")}>
{format(event.date, "MMM d, yyyy · HH:mm")}
</time>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<Empty>
<EmptyHeader>
<EmptyTitle>{COPY.emptyTitle}</EmptyTitle>
<EmptyDescription>{COPY.emptyText}</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button
type="button"
variant="outline"
onClick={() => setRange(undefined)}
>
{COPY.showAll}
</Button>
</EmptyContent>
</Empty>
)}
</CardContent>
</Card>
)
}
"use client"
import { useId, useState, type ComponentProps, type ReactNode } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { CalendarBlankIcon } from "@phosphor-icons/react"
import { cn } from "cn"
import { format, isValid, parse } from "date-fns"
import { type DateRange } from "react-day-picker"
import { Controller, useForm, useWatch } from "react-hook-form"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Kbd } from "@/components/ui/kbd"
import {
Popover,
PopoverContent,
PopoverTitle,
PopoverTrigger,
} from "@/components/ui/popover"
type DateRangePickerProps = Omit<
ComponentProps<typeof Field>,
"children" | "defaultValue"
> & {
/** The field's label, tied to the button that opens the calendar. It also names the popup. */
label: ReactNode
/** The button's text before any range is applied. */
placeholder: ReactNode
/** Controlled with value + onValueChange, or seeded with defaultValue. */
value?: DateRange
/**
* The range applied at first, when the picker keeps the value itself.
* Make the dates in a client file: a Date passed down from a Server
* Component arrives as a fixed instant, and can read as the day before
* or after in the reader's time zone.
*/
defaultValue?: DateRange
/** Called with the range each time one is applied, and with `undefined` when it is cleared. */
onValueChange?: (range: DateRange | undefined) => void
/**
* date-fns pattern for the button's text. By default the date, and with
* `time` the date and the time.
*/
dateFormat?: string
/** How many months the calendar shows side by side; 1 by default. */
numberOfMonths?: number
/**
* Adds a start and an end time field, read in the reader's own time zone.
* Off by default: the range is then two days, each at midnight.
*/
time?: boolean
/** Opens the calendar on first render. */
defaultOpen?: boolean
}
// What the fields hold while a range is being chosen: text, as typed.
type Draft = {
startDate: string
startTime: string
endDate: string
endTime: string
}
// How the fields write a value, and the other forms they accept when typed.
const DATE_TEXT = "MMM dd, yyyy"
const TIME_TEXT = "hh:mm a"
const DATE_FORMATS = [
"MMM d, yyyy",
"MMM d yyyy",
"MMMM d, yyyy",
"M/d/yyyy",
"yyyy-MM-dd",
]
const TIME_FORMATS = ["h:mm a", "h:mma", "h a", "ha", "H:mm"]
// The picker's own words: change or translate them here.
const COPY = {
start: "Start",
end: "End",
startTime: "Start time",
endTime: "End time",
datePlaceholder: "Jan 05, 2026",
timePlaceholder: "1:00 PM",
clear: "Clear",
apply: "Apply",
errors: {
date: "Enter a date like Jan 5, 2026.",
time: "Enter a time like 1:00 PM.",
gap: "That time does not exist on this day.",
order: "The end is before the start.",
},
} as const
// A fixed day with no clock change, for reading a time by itself.
const PLAIN_DAY = new Date(2001, 0, 1)
/**
* The day a typed date names, at midnight; `undefined` when it is not a
* date. Only a four-digit year is taken: a year still being typed
* ("Jan 5, 2") and one with a digit too many ("Jan 5, 20266") both read as
* real years otherwise.
*/
function readDate(text: string) {
for (const pattern of DATE_FORMATS) {
const date = parse(text.trim(), pattern, PLAIN_DAY)
const year = date.getFullYear()
if (isValid(date) && year >= 1000 && year <= 9999) return date
}
return undefined
}
/** The hour and minute a typed time names; `undefined` when it is not a time. */
function readTime(text: string) {
for (const pattern of TIME_FORMATS) {
const date = parse(text.trim(), pattern, PLAIN_DAY)
if (isValid(date))
return { hours: date.getHours(), minutes: date.getMinutes() }
}
return undefined
}
/**
* A day at a time of day, in the reader's own zone; `undefined` when the
* clock skips that time on that day, as it does when daylight saving
* starts. When the clock repeats an hour, this is its first occurrence.
*/
function at(day: Date, clock: { hours: number; minutes: number }) {
const date = new Date(
day.getFullYear(),
day.getMonth(),
day.getDate(),
clock.hours,
clock.minutes
)
return date.getHours() === clock.hours && date.getMinutes() === clock.minutes
? date
: undefined
}
type Problem = { field: keyof Draft; message: string }
/**
* Reads the four fields into a range, or into the list of what is wrong
* with them. The schema and Apply both use it, so what validates is exactly
* what is applied.
*/
function readDraft(draft: Draft, time: boolean) {
const problems: Problem[] = []
const startDay = readDate(draft.startDate)
const endDay = readDate(draft.endDate)
if (!startDay)
problems.push({ field: "startDate", message: COPY.errors.date })
if (!endDay) problems.push({ field: "endDate", message: COPY.errors.date })
let from = startDay
let to = endDay
if (time) {
const startClock = readTime(draft.startTime)
const endClock = readTime(draft.endTime)
if (!startClock)
problems.push({ field: "startTime", message: COPY.errors.time })
if (!endClock)
problems.push({ field: "endTime", message: COPY.errors.time })
if (startDay && startClock) {
from = at(startDay, startClock)
if (!from) problems.push({ field: "startTime", message: COPY.errors.gap })
}
if (endDay && endClock) {
to = at(endDay, endClock)
if (!to) problems.push({ field: "endTime", message: COPY.errors.gap })
}
}
if (from && to && to < from)
problems.push({ field: "endDate", message: COPY.errors.order })
return problems.length || !from || !to
? { problems, range: undefined }
: { problems, range: { from, to } satisfies DateRange }
}
/** The fields' text for an applied range; empty when there is none. */
function toDraft(range: DateRange | undefined, time: boolean): Draft {
return {
startDate: range?.from ? format(range.from, DATE_TEXT) : "",
startTime: range?.from && time ? format(range.from, TIME_TEXT) : "",
endDate: range?.to ? format(range.to, DATE_TEXT) : "",
endTime: range?.to && time ? format(range.to, TIME_TEXT) : "",
}
}
/** The form's schema: every problem `readDraft` finds, on its own field. */
const draftSchema = (time: boolean) =>
z
.object({
startDate: z.string(),
startTime: z.string(),
endDate: z.string(),
endTime: z.string(),
})
.superRefine((draft, context) => {
for (const problem of readDraft(draft, time).problems) {
context.addIssue({
code: "custom",
path: [problem.field],
message: problem.message,
})
}
})
/**
* A labelled button that opens a date range picker in a popover and shows
* the applied range. Pick two days in the calendar, or type the start and
* end dates in the fields under it. Nothing changes until Apply, which
* Enter also triggers; a field that cannot be read says so and blocks
* Apply. Clear empties the range.
*
* With `time`, each end also has a time field, read in the reader's own
* time zone; without it the range is two days at midnight. With one month
* the popover is 280px wide, or as wide as the screen allows, and the
* calendar and the fields share that width. The picker's own words
* (Start, End, Clear, Apply and the error messages) live in `COPY`. Other
* props go to the Field.
*/
function DateRangePicker(pickerProps: DateRangePickerProps) {
const {
label,
placeholder,
value,
defaultValue,
onValueChange,
numberOfMonths = 1,
time = false,
dateFormat = time ? "LLL dd, y h:mm a" : "LLL dd, y",
defaultOpen = false,
className,
...props
} = pickerProps
const id = useId()
const [uncontrolled, setUncontrolled] = useState(defaultValue)
const controlled = Object.hasOwn(pickerProps, "value")
const range = controlled ? value : uncontrolled
const [open, setOpen] = useState(defaultOpen)
const [month, setMonth] = useState(range?.from ?? new Date())
const form = useForm<Draft>({
resolver: zodResolver(draftSchema(time)),
defaultValues: toDraft(range, time),
})
const draft = useWatch({ control: form.control })
// The days the calendar marks: whatever the two date fields read as now.
const shownFrom = readDate(draft.startDate ?? "")
const typedTo = readDate(draft.endDate ?? "")
// An end typed before the start is not drawn: the calendar would take its
// next pick from a range that runs backwards.
const shownTo =
shownFrom && typedTo && typedTo >= shownFrom ? typedTo : undefined
const anyText = Object.values(draft).some(Boolean)
// A time field's error counts only while the time fields are shown.
const { errors } = form.formState
const startErrors = [errors.startDate, time ? errors.startTime : undefined]
const endErrors = [errors.endDate, time ? errors.endTime : undefined]
const startWrong = startErrors.some(Boolean)
const endWrong = endErrors.some(Boolean)
// Once Apply has been tried, every change checks all four fields again:
// fixing the start also settles "the end is before the start".
function recheck() {
if (form.formState.isSubmitted) void form.trigger()
}
function write(field: keyof Draft, text: string) {
form.setValue(field, text, { shouldDirty: true })
}
// The calendar writes the days it is given into the two date fields. With
// `time`, an empty time field gets the start or the end of the day, once
// its own date is picked: a time with no date would look half-filled.
function pickDays(next: DateRange | undefined) {
write("startDate", next?.from ? format(next.from, DATE_TEXT) : "")
write("endDate", next?.to ? format(next.to, DATE_TEXT) : "")
if (time) {
if (next?.from && !form.getValues("startTime"))
write("startTime", "12:00 AM")
if (next?.to && !form.getValues("endTime")) write("endTime", "11:59 PM")
}
recheck()
}
function apply(values: Draft) {
const next = readDraft(values, time).range
if (!next) return
if (!controlled) setUncontrolled(next)
onValueChange?.(next)
setOpen(false)
}
// Clear empties the range straight away, with no Apply.
function clear() {
form.reset(toDraft(undefined, time))
if (!controlled) setUncontrolled(undefined)
onValueChange?.(undefined)
setOpen(false)
}
return (
<Field data-slot="date-range-picker" className={className} {...props}>
<FieldLabel htmlFor={id}>{label}</FieldLabel>
<Popover
open={open}
onOpenChange={(next) => {
// Opening starts again from the applied range.
if (next) {
form.reset(toDraft(range, time))
setMonth(range?.from ?? new Date())
}
setOpen(next)
}}
>
<PopoverTrigger
render={
<Button
variant="outline"
id={id}
className="justify-start px-2.5 font-normal"
/>
}
>
<CalendarBlankIcon data-icon="inline-start" />
{range?.from ? (
range.to ? (
<>
{format(range.from, dateFormat)} -{" "}
{format(range.to, dateFormat)}
</>
) : (
format(range.from, dateFormat)
)
) : (
<span>{placeholder}</span>
)}
</PopoverTrigger>
{/* 280px for one month, or the room the screen has: the popup
scrolls inside that, so nothing runs off a phone. More months
set their own width. */}
<PopoverContent
className={cn(
"max-h-(--available-height) max-w-(--available-width) overflow-y-auto",
numberOfMonths === 1 ? "w-70" : "w-auto"
)}
align="start"
>
<PopoverTitle className="sr-only">{label}</PopoverTitle>
{/* The calendar takes the popup's width, as the fields below do. */}
<Calendar
mode="range"
month={month}
onMonthChange={setMonth}
selected={shownFrom ? { from: shownFrom, to: shownTo } : undefined}
onSelect={pickDays}
numberOfMonths={numberOfMonths}
className="p-0"
classNames={{ root: "w-full" }}
/>
<form
className="grid gap-3"
noValidate
onSubmit={(event) => {
// The popup is a portal, so React would pass this submit on to
// a form the picker sits in. It ends here.
event.stopPropagation()
void form.handleSubmit(apply)(event)
}}
>
<Field data-invalid={startWrong}>
<FieldLabel htmlFor={`${id}-start`}>{COPY.start}</FieldLabel>
<div className="flex gap-2">
<Controller
control={form.control}
name="startDate"
render={({ field, fieldState }) => (
<Input
{...field}
id={`${id}-start`}
placeholder={COPY.datePlaceholder}
autoComplete="off"
spellCheck={false}
aria-invalid={fieldState.invalid}
aria-describedby={
startWrong ? `${id}-start-error` : undefined
}
onChange={(event) => {
field.onChange(event)
recheck()
// The calendar follows a date as soon as it reads.
const day = readDate(event.target.value)
if (day) setMonth(day)
}}
/>
)}
/>
{time ? (
<Controller
control={form.control}
name="startTime"
render={({ field, fieldState }) => (
<Input
{...field}
onChange={(event) => {
field.onChange(event)
recheck()
}}
aria-label={COPY.startTime}
placeholder={COPY.timePlaceholder}
autoComplete="off"
spellCheck={false}
aria-invalid={fieldState.invalid}
aria-describedby={
startWrong ? `${id}-start-error` : undefined
}
className="w-36"
/>
)}
/>
) : null}
</div>
<FieldError id={`${id}-start-error`} errors={startErrors} />
</Field>
<Field data-invalid={endWrong}>
<FieldLabel htmlFor={`${id}-end`}>{COPY.end}</FieldLabel>
<div className="flex gap-2">
<Controller
control={form.control}
name="endDate"
render={({ field, fieldState }) => (
<Input
{...field}
id={`${id}-end`}
onChange={(event) => {
field.onChange(event)
recheck()
}}
placeholder={COPY.datePlaceholder}
autoComplete="off"
spellCheck={false}
aria-invalid={fieldState.invalid}
aria-describedby={
endWrong ? `${id}-end-error` : undefined
}
/>
)}
/>
{time ? (
<Controller
control={form.control}
name="endTime"
render={({ field, fieldState }) => (
<Input
{...field}
onChange={(event) => {
field.onChange(event)
recheck()
}}
aria-label={COPY.endTime}
placeholder={COPY.timePlaceholder}
autoComplete="off"
spellCheck={false}
aria-invalid={fieldState.invalid}
aria-describedby={
endWrong ? `${id}-end-error` : undefined
}
className="w-36"
/>
)}
/>
) : null}
</div>
<FieldError id={`${id}-end-error`} errors={endErrors} />
</Field>
<div className="flex gap-2">
<Button
type="button"
variant="ghost"
disabled={!range?.from && !anyText}
onClick={clear}
>
{COPY.clear}
</Button>
<Button type="submit" variant="outline" className="flex-1">
{COPY.apply}
<Kbd aria-hidden="true">↵</Kbd>
</Button>
</div>
</form>
</PopoverContent>
</Popover>
</Field>
)
}
export { DateRangePicker }
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
// Paragraphs in body content and introductions. It has no width of its own:
// the layout sets the measure. The default sets the foreground color; muted
// steps it down. Over art or a colored ground, pass className="text-current"
// to keep the ink around it. The text under a section's title is
// SectionDescription.
const textVariants = cva("w-full min-w-0 text-balance", {
variants: {
/**
* The text color. `default` (the default) is `foreground`; `muted`
* is `muted-foreground`. For the ink of a colored ground or art, pass
* `className="text-current"`.
*/
variant: {
default: "text-foreground",
muted: "text-muted-foreground",
},
/**
* The text size and line height: `xs` 12px/20px for a footnote or fine
* print; `sm` 14px/24px for the line under a card or panel title; `md`
* (the default) 16px/28px for body copy; `lg` 18px/28px at every width;
* `xl` 18px/28px, then 20px/32px from `sm` for a hero introduction.
*/
size: {
xs: "text-xs/5",
sm: "text-sm/6",
md: "text-base/7",
lg: "text-lg/7",
xl: "text-lg/7 sm:text-xl/8",
},
/**
* Tabular figures: every digit takes the same width, so numbers line up
* in a column and a changing count does not shift the text.
*/
tabular: {
true: "tabular-nums",
false: "",
},
},
defaultVariants: { variant: "default", size: "md", tabular: false },
})
/**
* A paragraph in body content or an introduction, a `p` by default. For
* several paragraphs, pass `render={<div />}` and put your own `p` elements
* inside.
*
* The default is the `foreground` color at regular weight (400, inherited
* from the page unless a parent sets one), and the lines are balanced when it
* wraps. `size` sets the text and its line height: `xs` 12px/20px for a
* footnote or fine print; `sm` 14px/24px for the line under a card or panel
* title; `md` (the default) 16px/28px for body copy in cards, lists and rows;
* `lg` 18px/28px; or `xl` 18px/28px and 20px/32px from `sm` for a hero.
* `variant="muted"` uses the muted text color. On art or a colored ground,
* pass `className="text-current"` to keep the ink around it. `tabular` sets
* tabular figures for numbers that line up or change. The layout controls the
* text's width and spacing. The text under a section's title is
* `SectionDescription`.
*/
function Text({
className,
variant = "default",
size = "md",
tabular = false,
render,
...props
}: useRender.ComponentProps<"p"> & VariantProps<typeof textVariants>) {
return useRender({
defaultTagName: "p",
render,
state: { slot: "text", variant, size, tabular },
props: mergeProps<"p">(
{ className: cn(textVariants({ variant, size, tabular }), className) },
props
),
})
}
export { Text, textVariants }
Installation
npx shadcn@latest add @01orbital/audit-log-date-filterMake it yours
- Its words are in
COPYat the top ofcomponents/blocks/controls/audit-log-date-filter/index.tsx: change them there, not in the markup. TODAYandEVENTS, also at the top of the file, hold its lists and settings.
Built from
npm: date-fns, react-day-picker. The CLI installs them for you.
Built from these parts. The CLI adds each one that is missing and won't replace a file you already have unless you choose to:
The shadcn parts here are their Base UI versions, and this piece uses Base UI's API. A Radix version you already have won't work with it.
Last updated on