- 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
ICS import and export
Drop a .ics feed onto the calendar, then export what is on screen back out as a file.
An empty calendar and three buttons. "Import sample feed" parses a small
team feed — two offsites, a bank holiday, a weekly sync, a product demo — and
adds what it can, then lists what it refused and why. If none of them fall in
the range on screen — a single day, in a narrow box — the calendar moves to
the first one. Open or drop your own .ics and the same happens to it. The
third button is named for the view you are in, "Export visible week" or
"Export visible day", and serialises every event in that range back to a
file; with nothing in range it says so and downloads nothing. Either way the
result and the ICS text land under the grid, so the round trip is visible
without opening the download.
live·ICS import and export
"use client";
import { Button } from "@coss/ui/components/button";
import { cn } from "@coss/ui/lib/utils";
import {
type CalEvent,
eventsToICS,
expandRecurrence,
type ICSImportResult,
Kloq,
parseICS,
parseInstant,
rangeOfView,
useKloq,
useKloqStore,
} from "kloq";
import { type DragEvent, useRef, useState } from "react";
import { CodePanes } from "@/components/calendar/site/code-panes";
import { Bar } from "../parts";
import { sampleFeed } from "./data";
// without this the store starts from kloq's sample week
const EMPTY: CalEvent[] = [];
function download(text: string, name: string) {
const url = URL.createObjectURL(new Blob([text], { type: "text/calendar;charset=utf-8" }));
const a = Object.assign(document.createElement("a"), { href: url, download: name });
a.click();
URL.revokeObjectURL(url);
}
type Shown =
| {
kind: "import";
label: string;
text: string;
result: ICSImportResult;
added: number;
movedTo: string | null;
}
| { kind: "export"; label: string; text: string; count: number };
const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
const dayLabel = (d: Date) =>
d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" });
function IcsBar({ onShown }: { onShown: (shown: Shown) => void }) {
const store = useKloqStore();
const k = useKloq();
const file = useRef<HTMLInputElement>(null);
const [over, setOver] = useState(false);
// what the grid is showing right now: "day" in a narrow box, "week" in a wide one
const span = typeof k.viewSetting === "number" ? `${k.viewSetting} days` : k.viewSetting;
const inView = (e: CalEvent) => expandRecurrence(e, rangeOfView(k.view)).occurrences.length > 0;
const importText = (label: string, text: string) => {
const result = parseICS(text, { color: "amber" });
// UIDs become ids, so re-importing the same feed is a no-op rather than a duplicate
const fresh = result.events.filter((e) => !store.get(e.id));
store.batch(fresh.map((event) => ({ type: "add" as const, event })));
// an import that lands off-screen looks like nothing happened: go to the first event instead
const first = result.events.some(inView)
? null
: result.events
.map((e) => new Date(parseInstant(e.start)))
.sort((a, b) => a.getTime() - b.getTime())[0];
if (first) k.goToDate(first);
onShown({
kind: "import",
label,
text,
result,
added: fresh.length,
movedTo: first ? dayLabel(first) : null,
});
};
const importFile = async (picked: File | undefined) => {
if (picked) importText(picked.name, await picked.text());
};
const onDrop = (e: DragEvent) => {
e.preventDefault();
setOver(false);
void importFile(e.dataTransfer.files[0]);
};
const exportVisible = () => {
const visible = store.getSnapshot().filter(inView);
const text = eventsToICS(visible, { prodId: "kloq-docs" });
onShown({ kind: "export", label: `visible ${span}`, text, count: visible.length });
if (visible.length > 0) download(text, "kloq.ics");
};
return (
<Bar
className={cn("gap-x-2 transition-colors", over && "bg-accent")}
onDragOver={(e) => {
e.preventDefault();
setOver(true);
}}
onDragLeave={() => setOver(false)}
onDrop={onDrop}
>
<Button size="xs" variant="outline" onClick={() => importText("sample feed", sampleFeed())}>
Import sample feed
</Button>
<Button size="xs" variant="outline" onClick={() => file.current?.click()}>
Open your own .ics
</Button>
{/* a file picker has no primitive: the button above opens this one */}
<input
ref={file}
type="file"
accept=".ics,text/calendar"
aria-label="ICS file"
hidden
onChange={(e) => void importFile(e.target.files?.[0])}
/>
<Button size="xs" variant="outline" onClick={exportVisible}>
Export visible {span}
</Button>
<span>or drop a file on this bar</span>
</Bar>
);
}
function Outcome({ shown }: { shown: Shown | null }) {
if (!shown) return <p>nothing imported yet — the result and the ICS text land here</p>;
if (shown.kind === "export")
return shown.count > 0 ? (
<p>
<span className="text-success-foreground">✓</span> exported{" "}
<span className="text-foreground">kloq.ics</span> · {plural(shown.count, "event")} from the{" "}
{shown.label}
</p>
) : (
<p>nothing to export — the {shown.label} has no events</p>
);
const { result, added, movedTo } = shown;
return (
<>
<p>
{added > 0 ? <span className="text-success-foreground">✓ </span> : null}
<span className="text-foreground">{added} added</span> · {result.events.length - added}{" "}
already there · {result.skipped.length} skipped ·{" "}
{plural(result.warnings.length, "warning")}
{movedTo ? ` · showing ${movedTo}, the first of them` : ""}
</p>
{[...result.skipped, ...result.warnings].map((n, i) => (
<p key={i}>
<span className="text-foreground">{n.what}</span>
{n.uid ? ` (${n.uid})` : ""} — {n.reason}
</p>
))}
</>
);
}
export default function IcsImportExportExample() {
const [shown, setShown] = useState<Shown | null>(null);
return (
<div className="@container flex flex-col">
<div className="h-136">
<Kloq defaultEvents={EMPTY} persistence={false} designMode={false} storage={false}>
<IcsBar onShown={setShown} />
<Kloq.Toolbar />
</Kloq>
</div>
<Bar edge="top" role="status" className="min-h-24 flex-col items-start gap-y-1">
<Outcome shown={shown} />
</Bar>
{shown?.text ? (
<div className="max-h-64 overflow-y-auto border-t p-4">
<CodePanes
panes={[
{ title: shown.kind === "export" ? "kloq.ics" : shown.label, code: shown.text },
]}
/>
</div>
) : null}
</div>
);
}
import { resolveView } from "kloq";
const pad = (n: number) => String(n).padStart(2, "0");
const date = (d: Date) => `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}`;
const dateTime = (d: Date, hour: number, minute = 0) => `${date(d)}T${pad(hour)}${pad(minute)}00`;
const plus = (d: Date, days: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + days);
/**
* A small team feed anchored on the current week. It deliberately carries three things the
* importer refuses (a VALARM, a cancelled event, a vendor X- property) and one it approximates (TZID).
*/
export function sampleFeed(now: Date = new Date()): string {
const [mon, tue, , thu, fri] = resolveView("week", 1, now).days;
return [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//Acme//Team calendar//EN",
"X-WR-CALNAME:Acme · offsites & holidays",
"BEGIN:VEVENT",
"UID:offsite-q4@acme.example",
`DTSTART;VALUE=DATE:${date(plus(tue, 7))}`,
`DTEND;VALUE=DATE:${date(plus(thu, 7))}`,
"SUMMARY:Q4 planning offsite",
"LOCATION:The Hoxton\\, Southwark",
"DESCRIPTION:Two days\\, whole company. Bring the roadmap.",
"END:VEVENT",
"BEGIN:VEVENT",
"UID:demo@acme.example",
`DTSTART:${dateTime(thu, 15)}`,
`DTEND:${dateTime(thu, 16)}`,
"SUMMARY:Product demo",
"ORGANIZER:mailto:ryan@acme.example",
"ATTENDEE;CN=Sam Rivera;PARTSTAT=ACCEPTED:mailto:sam@acme.example",
"ATTENDEE;CN=Jules Okafor;ROLE=OPT-PARTICIPANT;PARTSTAT=TENTATIVE:mailto:jules@acme.example",
"URL:https://meet.example.com/demo",
"END:VEVENT",
"BEGIN:VEVENT",
"UID:bank-holiday@acme.example",
`DTSTART;VALUE=DATE:${date(plus(mon, 7))}`,
`DTEND;VALUE=DATE:${date(plus(mon, 8))}`,
"SUMMARY:Bank holiday",
"TRANSP:TRANSPARENT",
"END:VEVENT",
"BEGIN:VEVENT",
"UID:eng-sync@acme.example",
`DTSTART:${dateTime(tue, 11)}`,
`DTEND:${dateTime(tue, 11, 30)}`,
"RRULE:FREQ=WEEKLY;BYDAY=TU",
"SUMMARY:Engineering sync",
"BEGIN:VALARM",
"TRIGGER:-PT10M",
"ACTION:DISPLAY",
"END:VALARM",
"END:VEVENT",
"BEGIN:VEVENT",
"UID:vendor-lunch@acme.example",
`DTSTART:${dateTime(fri, 12, 30)}`,
`DTEND:${dateTime(fri, 13, 30)}`,
"SUMMARY:Vendor lunch",
"STATUS:CANCELLED",
"END:VEVENT",
"BEGIN:VEVENT",
"UID:dinner@acme.example",
`DTSTART;TZID=America/New_York:${dateTime(fri, 19)}`,
`DTEND;TZID=America/New_York:${dateTime(fri, 21)}`,
"SUMMARY:Founders' dinner",
"X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC",
"END:VEVENT",
"END:VCALENDAR",
].join("\r\n");
}
"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>
);
}
usesparseICSeventsToICSrangeOfViewdownloadICS
How it works
parseICS(text, { color })never throws. It returnseventsready for the store plusskipped(dropped, with a reason) andwarnings(kept, but approximated). The sample feed carries one of each kind on purpose: aVALARM(reminders are not imported), aSTATUS:CANCELLEDevent, anX-vendor property, and aDTSTART;TZID=…that is read as local wall-clock time and preserved ontimeZone. See ICS.- A
UIDbecomes the eventid, so importing the same feed twice is idempotent: the bar filters out ids the store already has and adds the rest with onestore.batch, which is one committed change and one undo step. - A dropped file is read with
File.text(); the drop zone is the whole bar, and the "Open your own .ics" button is the keyboard-reachable route to the same function. useKloq().viewSettingnames the button anduseKloq().view, throughrangeOfView, is the range it exports. Export keeps every event thatexpandRecurrenceplaces inside it (a series counts if any occurrence does; the master goes out with itsRRULE), and serialises them witheventsToICS, which folds the per-eventtoICSoutput into oneVCALENDAR. For a single event,downloadICS(event)does the download in one call.- The feed in
data.tsis built from the current week. After an import the bar checks the samerangeOfViewand callsk.goToDatewhen nothing landed in it. Times are floating local time; all-day events use date-only values with the exclusiveDTENDthe spec — andCalEvent— require.
Take it further
Copy and paste speak the same format: eventsToICS / parseClipboardEvents
are what ⌘C and ⌘V use, so events copied here paste
into any calendar app that accepts ICS, and back. Wire parseICS to a URL
fetch and you have a subscription; wire the export to onCommit and every
change streams out — see Optimistic sync.
Last updated
On This Page