- Examples
- Booking calendar
- Team calendar
- Room booking
- Shift scheduler
- Conference agenda
- Calendar in an app layout
- Optimistic server sync
- Lazy-load by date range
- View and date in the URL
- Custom persistence adapter
- ICS import and export
- Custom event rendering
- Multiple time zones
- Linked month and day views
- Recurring events (RRULE)
- Custom ⌘K commands
- Natural-language event entry
Natural-language event entry
Type "lunch with Sam tomorrow 1pm" into a box above the grid; the parser underlines what it understood and the event lands.
A time-blocking planner: one line of text above the grid. As you type, the parser claims the phrases it understands — a day, a time or range, a duration, a place, an email — and the box marks each one in place, every kind with its own underline style and tint. A phrase that was read and then overruled is struck through instead. The row underneath reads the draft back: title, resolved when, and every claimed span with its kind. Enter commits it to the calendar and moves the view to that day.
Try the four phrases, or write your own.
live·Natural-language event entry
"use client";
import { Button } from "@coss/ui/components/button";
import { Input } from "@coss/ui/components/input";
import { Kbd } from "@coss/ui/components/kbd";
import { cn } from "@coss/ui/lib/utils";
import {
type CalEvent,
formatInstant,
highlightSegments,
Kloq,
newEventId,
parseQuickAdd,
QUICK_ADD_KINDS,
quickAddPreview,
toDateOnlyString,
useKloq,
useKloqStore,
} from "kloq";
import { useLayoutEffect, useMemo, useRef, useState } from "react";
import { Bar } from "../parts";
import { EVENTS, PHRASES } from "./data";
// each kind's own underline style and tint come from `QUICK_ADD_KINDS[kind].mark`
const MARK = "rounded-xs underline decoration-2 underline-offset-4";
const dayAfter = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1);
function Planner() {
const store = useKloqStore();
const k = useKloq();
const inputRef = useRef<HTMLInputElement>(null);
const mirrorRef = useRef<HTMLDivElement>(null);
const [text, setText] = useState("");
const [added, setAdded] = useState<string | null>(null);
const { result, preview } = useMemo(() => {
const now = new Date();
const result = parseQuickAdd(text, now, { defaultDurationMin: 60 });
return { result, preview: quickAddPreview(result, now) };
}, [text]);
const segments = highlightSegments(text, result.tokens, result.ignored);
// the mirror takes its box and type from the input it lies on, so it tracks whatever the Input renders
useLayoutEffect(() => {
const input = inputRef.current;
const mirror = mirrorRef.current;
if (!input || !mirror) return;
const fit = () => {
const s = getComputedStyle(input);
const frame = mirror.offsetParent?.getBoundingClientRect();
const box = input.getBoundingClientRect();
Object.assign(mirror.style, {
left: `${box.left - (frame?.left ?? 0)}px`,
top: `${box.top - (frame?.top ?? 0)}px`,
width: `${box.width}px`,
height: `${box.height}px`,
padding: s.padding,
font: s.font,
letterSpacing: s.letterSpacing,
lineHeight: s.lineHeight,
});
};
fit();
const watch = new ResizeObserver(fit);
watch.observe(input);
return () => watch.disconnect();
}, []);
// a sentence wider than the box scrolls inside the input; the mirror has to follow it
const follow = () => {
if (mirrorRef.current && inputRef.current)
mirrorRef.current.scrollLeft = inputRef.current.scrollLeft;
};
const commit = () => {
if (!result.start || !result.end) return;
const base = {
id: newEventId(),
title: preview.title,
color: "emerald" as const,
...(result.location ? { location: result.location } : {}),
...(result.attendees.length
? { attendees: result.attendees.map((email) => ({ email })) }
: {}),
};
// the parser's all-day `end` is the inclusive last day; the store's is exclusive
const event: CalEvent = result.allDay
? {
...base,
allDay: true,
start: toDateOnlyString(result.start),
end: toDateOnlyString(dayAfter(result.end)),
}
: { ...base, start: formatInstant(result.start), end: formatInstant(result.end) };
store.add(event);
k.goToDate(result.start);
setAdded(`${preview.title} · ${preview.when}`);
setText("");
};
return (
<>
<div className="relative border-b px-4 py-2.5">
<Input
ref={inputRef}
nativeInput
value={text}
onChange={(e) => setText(e.target.value)}
onScroll={follow}
onKeyUp={follow}
onSelect={follow}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.nativeEvent.isComposing) {
e.preventDefault();
commit();
} else if (e.key === "Escape") setText("");
}}
placeholder="What are you planning? — “gym tomorrow morning for 45 mins”"
aria-label="Plan an event in plain English"
autoComplete="off"
spellCheck={false}
/>
<div
ref={mirrorRef}
aria-hidden
className="pointer-events-none absolute overflow-hidden whitespace-pre text-transparent"
>
{segments.map((s, i) => (
<span
key={i}
className={cn(
// read, then overruled — a length beside an explicit range, say — is struck through, in no kind's colour
s.ignored &&
"rounded-xs bg-muted line-through decoration-muted-foreground decoration-2",
!s.ignored && s.kind && MARK,
!s.ignored && s.kind && QUICK_ADD_KINDS[s.kind].mark,
)}
>
{s.text}
</span>
))}
</div>
</div>
<Bar className="tabular-nums">
{text.trim() ? (
<>
<span className="text-foreground">{preview.title}</span>
<span>{preview.when}</span>
{preview.chips.map((chip) => (
<span key={chip}>· {chip}</span>
))}
{result.tokens.map((t) => (
<span key={t.start}>
<span className={cn("px-0.5", MARK, QUICK_ADD_KINDS[t.kind].mark)}>
{QUICK_ADD_KINDS[t.kind].label}
</span>{" "}
<span className="text-foreground">“{t.text}”</span>
</span>
))}
{result.ignored.map((t) => (
<span key={t.start}>
ignored <s>“{t.text}”</s>
</span>
))}
<span className="ms-auto inline-flex items-center gap-1.5">
<Kbd>↵</Kbd> add
</span>
</>
) : (
<>
{PHRASES.map((phrase) => (
<Button
key={phrase}
variant="outline"
size="xs"
className="max-w-full"
onClick={() => {
setText(phrase);
inputRef.current?.focus();
}}
>
<span className="min-w-0 truncate">{phrase}</span>
</Button>
))}
{added ? (
<span role="status" className="ms-auto text-foreground">
<span className="text-success-foreground">✓</span> {added}
</span>
) : null}
</>
)}
</Bar>
</>
);
}
export default function QuickAddPlannerExample() {
return (
<div className="@container flex flex-col">
<div className="h-136">
<Kloq defaultEvents={EVENTS} persistence={false} designMode={false} storage={false}>
<Planner />
<Kloq.Toolbar />
</Kloq>
</div>
</div>
);
}
import { type CalEvent, instantAt, resolveView } from "kloq";
/** Each phrase exercises a different part of the grammar; the last one has a length the range overrules. */
export const PHRASES = [
"Deep work tomorrow from 9 to 11",
"Lunch with Sam friday 1pm at Dishoom",
"Sync tuesday 2-3pm with jo@acme.com",
"Retro thursday 2-3pm for 45 mins",
];
/** A light week so the planner has something to slot around. */
export function buildWeek(now: Date = new Date()): CalEvent[] {
const week = resolveView("week", 1, now);
const at = (day: number, hour: number, minute = 0) => instantAt(week, day, hour * 60 + minute);
return [
{
id: "standup",
title: "Standup",
color: "blue",
start: at(0, 9, 30),
end: at(0, 9, 45),
rrule: "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR",
},
{ id: "design", title: "Design review", color: "violet", start: at(1, 14), end: at(1, 15) },
{ id: "interview", title: "Interview", color: "rose", start: at(3, 11), end: at(3, 11, 45) },
];
}
export const EVENTS = buildWeek();
"use client";
import { Button } from "@coss/ui/components/button";
import { cn } from "@coss/ui/lib/utils";
import { formatViewTitle, useIsClient, useKloq } from "kloq";
import { ChevronLeft, ChevronRight } from "lucide-react";
import type { ComponentProps } from "react";
/** The strip an example hangs its controls and readouts on; same box as `Kloq.Toolbar`. */
export function Bar({
edge = "bottom",
className,
...props
}: ComponentProps<"div"> & { edge?: "top" | "bottom" }) {
return (
<div
{...props}
className={cn(
"flex min-h-11 shrink-0 flex-wrap items-center gap-x-4 gap-y-2 px-4 py-2.5 font-mono text-xs text-muted-foreground",
edge === "bottom" ? "border-b" : "border-t",
className,
)}
/>
);
}
export function Dot({ live, className, ...props }: ComponentProps<"span"> & { live?: boolean }) {
return (
<span
aria-hidden
{...props}
className={cn(
"size-1.5 shrink-0 rounded-full",
live ? "bg-brand motion-safe:animate-pulse" : "bg-border",
className,
)}
/>
);
}
/** Previous / next / today for a calendar whose view is fixed. Must render inside `<Kloq>`. */
export function Nav({ locale }: { locale?: string }) {
const k = useKloq();
const isClient = useIsClient();
return (
<div className="flex min-w-0 items-center gap-1">
<Button variant="ghost" size="icon-xs" aria-label="Previous" onClick={() => k.step(-1)}>
<ChevronLeft />
</Button>
<Button variant="ghost" size="icon-xs" aria-label="Next" onClick={() => k.step(1)}>
<ChevronRight />
</Button>
<Button
variant="ghost"
size="xs"
className={cn(k.atToday && "text-muted-foreground")}
onClick={k.goToday}
>
Today
</Button>
<span className="ms-1 truncate text-sm font-medium text-foreground tabular-nums sm:text-xs">
{isClient ? formatViewTitle(k.view, locale, { short: k.narrow }) : null}
</span>
</div>
);
}
usesparseQuickAddhighlightSegmentsQUICK_ADD_KINDSquickAddPreviewuseKloqStore
How it works
parseQuickAdd(text, now, { defaultDurationMin })runs on every keystroke, in auseMemokeyed on the text.nowis an argument, not something the parser reads, so the parse is deterministic; the planner passes a freshnew Date()each time so "tomorrow" is always tomorrow. The grammar is on Quick add.highlightSegments(text, result.tokens, result.ignored)interleaves the input with its tokens; a segment fromresult.ignoredcarriesignored: true, and each kind's look comes fromQUICK_ADD_KINDS[kind].mark. Concatenating the segments reproduces the input exactly, so the planner draws them in a transparent-text mirror laid over theInput— the underline sits under the characters that were understood. The mirror takes its box, padding and type from the input's computed style, so it follows whatever the primitive renders, and copies itsscrollLeftso it stays aligned once a sentence is wider than the box.quickAddPreview(result, now)folds the result into one line: a title that is never blank, a formatted when, and chips for location and attendees.- The planner is a child of
<Kloq>, which is what lets it calluseKloqStore()anduseKloq(). On Enter it builds aCalEventthe same way the built-in ⌘K quick add does —formatInstantfor timed events,toDateOnlyStringwith an exclusive end for all-day ones (the parser's all-dayendis inclusive) — thenstore.add(event)andk.goToDate(start). The event shapes are on Events. - A time with no day resolves to today, or tomorrow if that time has passed;
a day with no time is an all-day event. A range is authoritative: in "retro
thursday 2-3pm for 45 mins" the length is struck through and kept out of the
title. A bare number needs
at,fromor a meridiem before it counts as a time, so "sprint 2 to 4" stays a title; once it counts, 1–6 read as afternoon and 7–11 as morning unless a cue such as "dinner" says evening. "in 10 minutes" is an offset from now, adjacent lengths add up ("for 1 hour 30 mins"), andin <place>is a location only for room-like forms — "in room 4" is one, "lunch in Soho" keeps Soho in the title.
Take it further
kloq exports the same field it uses inside ⌘K as QuickAddInput,
if you would rather not draw the mirror yourself. With a controlled events
array the commit becomes onEventsChange([...events, event]) and the parser
result can be sent to a server before it lands — see
Controlled state.
Last updated
On This Page