Getting started
Examples
- 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
Registry
Core concepts
Customization
Optimistic server sync
Every change is committed to a fake server with latency and a reject switch; a rejection springs the block back to where it was.
Drag an event. It lands at once, pulses while the commit is on the wire, and
settles when the server answers. Now flip Reject writes and drag again: the
server refuses, the block springs back, and the log underneath records the
KloqChange that was sent and what came of it. The latency slider is the
round-trip; at 2000 ms you can move three things before the first one lands.
live·Optimistic server sync
loading
"use client";
import { Slider, SliderValue } from "@coss/ui/components/slider";
import { Switch } from "@coss/ui/components/switch";
import { cn } from "@coss/ui/lib/utils";
import { buildSeedEvents, Kloq, type KloqChange } from "kloq";
import { useId, useRef, useState, useSyncExternalStore } from "react";
import { Label } from "@/components/calendar/ui/label";
import { Bar, Dot } from "../parts";
import { FakeServer } from "./data";
const idsOf = (change: KloqChange): string[] => {
switch (change.type) {
case "add":
return [change.event.id];
case "update":
return [change.id];
case "batch":
return change.changes.flatMap(idsOf);
default:
return [];
}
};
export default function ServerSyncExample() {
const root = useRef<HTMLDivElement>(null);
const latencyLabel = useId();
const [server] = useState(() => new FakeServer());
const [seeds] = useState(() => buildSeedEvents());
const { latency, reject, inFlight, log } = useSyncExternalStore(
server.subscribe,
server.getState,
server.getState,
);
// every block renders `data-cal-event="<id>"`; kloq.css pulses the ones carrying `data-syncing`
const markSyncing = (ids: string[], on: boolean) => {
for (const id of ids)
for (const el of root.current?.querySelectorAll(`[data-cal-event="${CSS.escape(id)}"]`) ?? [])
el.toggleAttribute("data-syncing", on);
};
const onCommit = (change: KloqChange) => {
const ids = idsOf(change);
markSyncing(ids, true);
return server.commit(change).finally(() => markSyncing(ids, false));
};
return (
<div ref={root} className="@container flex flex-col">
<Bar>
<div className="w-44">
<Slider
aria-labelledby={latencyLabel}
min={0}
max={2000}
step={100}
value={latency}
onValueChange={(v) => server.setLatency(v as number)}
>
<div className="mb-2 flex items-center justify-between gap-2">
<Label size="sm" id={latencyLabel} render={<span />}>
Latency
</Label>
<SliderValue className="font-mono text-xs text-foreground tabular-nums">
{(_, values) => `${values[0]} ms`}
</SliderValue>
</div>
</Slider>
</div>
<Label size="sm">
Reject writes
<Switch checked={reject} onCheckedChange={(on) => server.setReject(on)} />
</Label>
<span role="status" className="ms-auto inline-flex items-center gap-2 tabular-nums">
<Dot live={inFlight > 0} />
{inFlight > 0 ? `syncing ${inFlight}…` : "idle"}
</span>
</Bar>
<div className="h-104">
<Kloq
defaultEvents={seeds}
onCommit={onCommit}
persistence={false}
storage={false}
designMode={false}
>
<Kloq.Toolbar />
</Kloq>
</div>
<Bar
edge="top"
role="log"
aria-label="Commits"
className="min-h-24 flex-col items-start gap-y-1 tabular-nums"
>
{log.length === 0 && (
<p>no commits yet — drag an event, then flip the switch and drag again</p>
)}
{log.map((entry) => (
<p key={entry.id} className="flex gap-3">
<span>#{entry.id}</span>
<span className="text-foreground">{entry.label}</span>
<span className={cn(!entry.ok && "text-destructive-foreground")}>
{entry.ok ? "ok" : "rejected → reverted"}
</span>
</p>
))}
</Bar>
</div>
);
}
import type { KloqChange } from "kloq";
export interface CommitEntry {
id: number;
label: string;
ok: boolean;
}
export interface ServerState {
latency: number;
reject: boolean;
inFlight: number;
log: CommitEntry[];
}
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
/** `update seed-design`, `batch ×3` — what one commit is, in the log. */
export function describeChange(change: KloqChange): string {
switch (change.type) {
case "add":
return `add ${change.event.id}`;
case "update":
return `update ${change.id}`;
case "remove":
return `remove ${change.event.id}`;
case "batch":
return `batch ×${change.changes.length}`;
case "reset":
return "reset";
}
}
/** A stand-in for your API: one round-trip per commit, with a latency knob and a reject switch. */
export class FakeServer {
private state: ServerState = { latency: 600, reject: false, inFlight: 0, log: [] };
private seq = 0;
private listeners = new Set<() => void>();
subscribe = (listener: () => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
};
getState = () => this.state;
setLatency(latency: number) {
this.set({ latency });
}
setReject(reject: boolean) {
this.set({ reject });
}
/** Rejecting is what makes kloq revert — the thrown error is the whole protocol. */
async commit(change: KloqChange): Promise<void> {
this.set({ inFlight: this.state.inFlight + 1 });
await sleep(this.state.latency);
// kloq ignores the promise of a reset (nothing to revert to), so a reset never fails
const ok = change.type === "reset" || !this.state.reject;
const entry = { id: ++this.seq, label: describeChange(change), ok };
this.set({ inFlight: this.state.inFlight - 1, log: [entry, ...this.state.log].slice(0, 4) });
if (!ok) throw new Error(`server rejected ${entry.label}`);
}
private set(patch: Partial<ServerState>) {
this.state = { ...this.state, ...patch };
for (const listener of this.listeners) listener();
}
}
"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>
);
}
usesonCommitKloqChangedefaultEvents
How it works
onCommitis the seam. kloq calls it with every committed change — a drag, a resize, a create, a delete, a paste — after applying it. Return a promise and the change stands if it resolves; reject and the store reverts, FLIPping the affected blocks back with the cancel spring. That is the whole protocol: the example'sonCommitjust returnsserver.commit(change). See Optimistic sync.FakeServerindata.tsstands in for your API.commitwaitslatencymilliseconds, then throws when the switch is on. It also keeps a small state object — in-flight count, last four results — that the strip reads throughuseSyncExternalStore, so nothing here is React-specific on the server side.- The pulse is one attribute. Every block renders
data-cal-event="<id>";markSyncingsetsdata-syncingon the blocks named by the change while the promise is pending, and kloq's stylesheet animates that selector. The ids come straight off the change:event.idfor anadd,idfor anupdate, the union for abatch. Aremovehas no block left to mark. - The store is uncontrolled —
defaultEventsseeds it,persistence={false}keeps it in memory — so undo, redo and the revert all live inside kloq. The sameonCommitworks unchanged on a controlledeventsarray; there the revert arrives as a call toonEventsChangewith the previous array. See Controlled state. - One wrinkle worth knowing: kloq ignores the promise of a
reset(there is nothing to revert to), so the fake server never rejects one. Reset from the toolbar and the log showsreset okeven with the switch on.
Take it further
- Swap
server.commitfor a route handler:fetch("/api/events", { method: "POST", body: JSON.stringify(change) })andthrowwhen!res.ok. Theupdatevariant carries bothpatchandprev, so a PATCH request and anIf-Matchheader are both a field read away. - A
batchis one change and one request. Applychangesin order inside a transaction and the paste either lands whole or springs back whole. - Tell the user. The revert is visible, but a toast on the catch — before re-throwing — says why; the demo does exactly that.
Last updated
On This Page