# Timeline

What happened to one record, newest first and grouped by day: who did it, what changed from what to what, and the comment or email behind it. Long feeds fold behind "Show earlier events".

{/* Generated by scripts/build-ui-catalog.mjs from src/ui-catalog/. Do not edit. */}

What happened to one record, newest first and grouped by day: who did it, what changed from what to what, and the comment or email behind it. Long feeds fold behind "Show earlier events".

## When to use it

**Use it when:** The user asks what happened to one record (a deal, a ticket, an order): who did what and when, in order. Comments, emails, status moves and field changes, grouped by day.

**Use something else when:** The record's current state matters more than its history (entity card). Events across many records (records list or table). A trend in numbers over time (chart).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | As soon as the card shows. The agent goes on. Opening an event is your app's job. |

## States

Besides its data, the template draws these as itself, with `mountState()`. Pick one on the preview with **State**.

| State | When it shows |
| --- | --- |
| Loading | While the card loads again in place, for example after Try again. While execute runs, the SDK shows its own loader. |
| Empty | execute found no events for the record. The card says so and the agent explains why. |
| Error | execute returned the failure as data, so the agent can explain it. Try again loads in place. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
```

The hosted action and the in-page handler below show each case. The state types are `LoadingState`, `EmptyState` and `ErrorState` in fs-kit.

## Data

### TimelineData

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` | Default: clock. |
| `events` | `TimelineEvent[]` | In any order: the card sorts them newest first and groups them by day. |
| `visible` (optional) | `number` | How many events show before "Show N earlier events". Default: 5. |
| `footnote` (optional) | `string` | Short note on the left of the footer, e.g. "Last 30 days". |
| `link` (optional) | `{ label: string; href: string }` | A footer link to the full history in your app. |

### TimelineEvent

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | Your event's id: actions.open gets the event back. |
| `kind` | `TimelineKind` | Sets the icon and its tone: created, updated, comment, status, email, call or system. |
| `actor` (optional) | `string` | Who did it, by name. Leave it out for events your system made. |
| `actorAvatarUrl` (optional) | `string` | A photo for the actor's avatar. Falls back to initials. |
| `action` | `string` | What happened, after the actor's name: "moved the deal to Negotiation". Without an actor, the whole sentence. |
| `at` | `string` | When, as an ISO 8601 time. Shown relative ("2 hours ago"), the exact time on hover. |
| `detail` (optional) | `string` | A comment's text, an email's subject or a call's note. Up to three lines show. |
| `changes` (optional) | `TimelineChange[]` | Field changes, drawn as old value, arrow, new value. |
| `linkLabel` (optional) | `string` | Shows a link on this event, e.g. "Open email". With href it goes there; without, it calls actions.open. |
| `href` (optional) | `string` | Where the event's link goes in your app. |

### TimelineChange

| Field | Type | Notes |
| --- | --- | --- |
| `field` | `string` | The field's name, e.g. "Stage". |
| `from` (optional) | `string` | The old value. Leave it out when the field was empty. |
| `to` | `string` | The new value. |

### TimelineActions

| Field | Type | Notes |
| --- | --- | --- |
| `open()` (optional) | `(event: TimelineEvent) => void` | An event's link was clicked and the event has no href. Open it in your app. |

## Install

Copy the template and the shared kit into your code: `agent/ui/` in an agent repo, or anywhere in your app. The template imports only `./fs-kit.js`. Then wire it up from the hosted action or the in-page handler.

- Hosted action: [TypeScript](/ui-catalog/files/ts/usage/timeline.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/timeline.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/timeline.component.ts), [JavaScript](/ui-catalog/files/js/usage/timeline.component.js)
- timeline: [TypeScript](/ui-catalog/files/ts/timeline.ts), [JavaScript](/ui-catalog/files/js/timeline.js)
- fs-kit: [TypeScript](/ui-catalog/files/ts/fs-kit.ts), [JavaScript](/ui-catalog/files/js/fs-kit.js)

The hosted action needs an agent repo with one folder per action (`agent/actions/<action_key>/index.ts`). If your repo keeps its actions in `agent/actions/index.ts`, use the in-page handler: it runs the same template in your app.

All templates in machine-readable form: [/ui-catalog/catalog.json](/ui-catalog/catalog.json).

## Code

### Hosted action

```ts title="agent/actions/show_deal_activity/index.ts"
// agent/actions/show_deal_activity/index.ts: a hosted action.
// Copy the template (timeline.ts) and fs-kit.ts into agent/ui/.

type Result = TimelineData | { error: string };

// Your activity types, mapped to the card's kinds (icon and tone).
const KINDS: Record<string, TimelineKind> = {
  note: "comment", email_sent: "email", email_received: "email", call: "call",
  stage_changed: "status", field_changed: "updated", created: "created",
};

export async function execute(args: { dealId: string }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch(`/api/deals/${encodeURIComponent(args.dealId)}/activity?limit=20`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The deal's activity didn't load (${res.status}). Nothing changed.` };
  const { deal, activity } = await res.json();
  // Return every event the card shows: the agent reads this, not the card.
  return {
    title: `${deal.name} · ${deal.company}`,
    subtitle: `Deal activity · ${deal.stage}`,
    icon: "briefcase",
    events: activity.map((a: any): TimelineEvent => ({
      id: a.id,
      kind: KINDS[a.type] ?? "system",
      actor: a.user?.name,
      actorAvatarUrl: a.user?.photoUrl,
      action: a.summary,
      at: a.createdAt,
      detail: a.body ?? a.subject,
      changes: a.changes?.map((c: any) => ({ field: c.label, from: c.oldValue ?? undefined, to: c.newValue })),
      linkLabel: a.type.startsWith("email") ? "Open email" : undefined,
      href: a.type.startsWith("email") ? `/deals/${deal.id}/emails/${a.emailId}` : undefined,
    })),
    link: { label: "Open deal", href: `/deals/${deal.id}` },
  };
}

// Read-only in every case: the card reports displayed(result), so the agent reads the data and goes on.
export function render(result: Result, ctx: RenderContext) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Deal activity", state: { kind: "error", text: result.error } });
  } else if (result.events.length === 0) {
    mountState({ root, head, title: result.title, state: { kind: "empty", icon: "clock", title: "No activity yet", text: "Emails, calls, notes and stage changes show up here." } });
  } else {
    mount({ root, head, data: result, api: { displayed: () => ctx.card.displayed(result) } });
    return;
  }
  ctx.card.displayed(result); // the agent reads what it shows, or the error to explain
}
```

```js title="agent/actions/show_deal_activity/index.js"
// agent/actions/show_deal_activity/index.js: a hosted action.
// Copy the template (timeline.ts) and fs-kit.ts into agent/ui/.

// Your activity types, mapped to the card's kinds (icon and tone).
const KINDS = {
  note: "comment", email_sent: "email", email_received: "email", call: "call",
  stage_changed: "status", field_changed: "updated", created: "created",
};

export async function execute(args, ctx) {
  const res = await ctx.fetch(`/api/deals/${encodeURIComponent(args.dealId)}/activity?limit=20`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The deal's activity didn't load (${res.status}). Nothing changed.` };
  const { deal, activity } = await res.json();
  // Return every event the card shows: the agent reads this, not the card.
  return {
    title: `${deal.name} · ${deal.company}`,
    subtitle: `Deal activity · ${deal.stage}`,
    icon: "briefcase",
    events: activity.map((a) => ({
      id: a.id,
      kind: KINDS[a.type] ?? "system",
      actor: a.user?.name,
      actorAvatarUrl: a.user?.photoUrl,
      action: a.summary,
      at: a.createdAt,
      detail: a.body ?? a.subject,
      changes: a.changes?.map((c) => ({ field: c.label, from: c.oldValue ?? undefined, to: c.newValue })),
      linkLabel: a.type.startsWith("email") ? "Open email" : undefined,
      href: a.type.startsWith("email") ? `/deals/${deal.id}/emails/${a.emailId}` : undefined,
    })),
    link: { label: "Open deal", href: `/deals/${deal.id}` },
  };
}

// Read-only in every case: the card reports displayed(result), so the agent reads the data and goes on.
export function render(result, ctx) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Deal activity", state: { kind: "error", text: result.error } });
  } else if (result.events.length === 0) {
    mountState({ root, head, title: result.title, state: { kind: "empty", icon: "clock", title: "No activity yet", text: "Emails, calls, notes and stage changes show up here." } });
  } else {
    mount({ root, head, data: result, api: { displayed: () => ctx.card.displayed(result) } });
    return;
  }
  ctx.card.displayed(result); // the agent reads what it shows, or the error to explain
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page action handler: the template runs in your page.

type Result = TimelineData | { error: string };

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    show_deal_activity: {
      // Return every event the card shows: the agent reads this, not the card.
      // A failure goes back as data too, so the agent can explain it.
      execute: async ({ dealId }: { dealId: string }): Promise<Result> =>
        loadDealActivity(dealId).catch(() => ({ error: "The deal's activity didn't load. Nothing changed." })),

      // Read-only: declares readyState only. The agent goes on as soon as the card reports it's shown.
      renderComponent: ({ data, host, header, readyState }: ComponentContext<Result>) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result: Result): void => {
          if (!("error" in result)) {
            return void mount({
              root: host, head: header, data: result, api: { displayed: () => shown(result) },
              // Events with a link label and no href come here: open them with your router, no page reload.
              actions: { open: (event) => router.push(`/activity/${event.id}`) },
            });
          }
          mountState({
            root: host, head: header, title: "Deal activity",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it loads, then the feed (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Deal activity", state: { kind: "loading", label: "Loading activity…" } });
                show(await loadDealActivity(currentDealId()).catch(() => ({ error: "Still not loading. Try again in a minute." })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

```js title="in-page handler.js"
// An in-page action handler: the template runs in your page.

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    show_deal_activity: {
      // Return every event the card shows: the agent reads this, not the card.
      // A failure goes back as data too, so the agent can explain it.
      execute: async ({ dealId }) =>
        loadDealActivity(dealId).catch(() => ({ error: "The deal's activity didn't load. Nothing changed." })),

      // Read-only: declares readyState only. The agent goes on as soon as the card reports it's shown.
      renderComponent: ({ data, host, header, readyState }) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result) => {
          if (!("error" in result)) {
            return void mount({
              root: host, head: header, data: result, api: { displayed: () => shown(result) },
              // Events with a link label and no href come here: open them with your router, no page reload.
              actions: { open: (event) => router.push(`/activity/${event.id}`) },
            });
          }
          mountState({
            root: host, head: header, title: "Deal activity",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it loads, then the feed (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Deal activity", state: { kind: "loading", label: "Loading activity…" } });
                show(await loadDealActivity(currentDealId()).catch(() => ({ error: "Still not loading. Try again in a minute." })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

### timeline

```ts title="agent/ui/timeline.ts"
// Template: timeline. A read-only chat card with what happened to one record, newest first, grouped by day.

export const meta = {
  id: "timeline",
  title: "Timeline",
  surface: "card",
  kind: "read-only",
  mobile: "same",
  whenToUse: "The user asks what happened to one record (a deal, a ticket, an order): who did what and when, in order. Comments, emails, status moves and field changes, grouped by day.",
  whenNotToUse: "The record's current state matters more than its history (entity card). Events across many records (records list or table). A trend in numbers over time (chart).",
};

const CSS = `
.fsk-tl { container-type: inline-size; }
.fsk-tl .fsk-head > div { flex: 1; min-width: 0; }
.fsk-tl .fsk-tl-day + .fsk-tl-day { margin-top: 6px; }
.fsk-tl .fsk-tl-dayhead {
  display: flex; align-items: center; gap: 10px; margin: 0 0 4px; font-size: .79em; font-weight: 600; color: var(--k-text-2);
  letter-spacing: .01em;
}
.fsk-tl .fsk-tl-dayhead::after { content: ""; flex: 1; height: 1px; background: var(--k-divider); }
.fsk-tl .fsk-tl-list { margin: 0; padding: 0; list-style: none; }
.fsk-tl .fsk-tl-ev {
  position: relative; display: grid; grid-template-columns: 28px minmax(0, 1fr); column-gap: 10px; padding: 7px 0 9px;
  border-radius: var(--k-r-md); outline: none;
}
.fsk-tl .fsk-tl-ev:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
/* The rail: from under this event's avatar down to the next one. */
.fsk-tl .fsk-tl-ev:not(:last-child)::before {
  content: ""; position: absolute; left: 13.5px; top: 41px; bottom: -5px; width: 1px; background: var(--k-divider);
}
.fsk-tl .fsk-tl-ev--new { animation: fsk-in .3s var(--k-ease) both; }
.fsk-tl .fsk-tl-node { position: relative; width: 28px; height: 28px; }
.fsk-tl .fsk-tl-node .fsk-avatar { box-shadow: 0 0 0 2px var(--k-paper); }
.fsk-tl .fsk-tl-sys {
  display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%;
  color: color-mix(in srgb, var(--tone) 80%, var(--k-text)); background: color-mix(in srgb, var(--tone) 12%, var(--k-paper));
  box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--tone) 22%, var(--k-paper)), 0 0 0 2px var(--k-paper);
}
.fsk-tl .fsk-tl-badge {
  position: absolute; right: -6px; bottom: -4px; display: grid; place-items: center; width: 15px; height: 15px; border-radius: 50%;
  color: var(--k-paper); background: var(--tone); box-shadow: 0 0 0 2px var(--k-paper);
}
.fsk-tl [data-tone="primary"] { --tone: var(--k-primary); }
.fsk-tl [data-tone="success"] { --tone: var(--k-success); }
.fsk-tl [data-tone="warning"] { --tone: var(--k-warning); }
.fsk-tl [data-tone="neutral"] { --tone: var(--k-text-2); }
.fsk-tl .fsk-tl-body { min-width: 0; }
.fsk-tl .fsk-tl-line { display: flex; align-items: baseline; gap: 8px; margin: 0; min-height: 28px; padding-top: 4px; line-height: 1.4; }
.fsk-tl .fsk-tl-what { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.fsk-tl .fsk-tl-who { font-weight: 600; }
.fsk-tl .fsk-tl-time { flex: none; font-size: .79em; color: var(--k-text-2); white-space: nowrap; cursor: default; }
.fsk-tl .fsk-tl-changes { display: grid; gap: 3px; margin: 5px 0 0; padding: 0; list-style: none; font-size: .86em; }
.fsk-tl .fsk-tl-change { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 6px; min-width: 0; }
.fsk-tl .fsk-tl-field { color: var(--k-text-2); }
.fsk-tl .fsk-tl-from { color: var(--k-text-2); text-decoration: line-through; text-decoration-color: color-mix(in srgb, var(--k-text-2) 60%, transparent); }
.fsk-tl .fsk-tl-arrow { color: var(--k-text-2); opacity: .8; }
.fsk-tl .fsk-tl-to {
  padding: 0 6px; border-radius: min(var(--k-r), 6px); font-weight: 550;
  color: color-mix(in srgb, var(--k-primary) 70%, var(--k-text)); background: var(--k-tint);
}
.fsk-tl .fsk-tl-quote {
  margin: 6px 0 0; padding: 7px 10px; border-radius: 2px var(--k-r-md) var(--k-r-md) var(--k-r-md); background: var(--k-sunken);
  font-size: .93em; line-height: 1.45; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; line-clamp: 3; overflow: hidden;
}
.fsk-tl .fsk-tl-ref {
  display: flex; align-items: center; gap: 8px; margin: 6px 0 0; padding: 6px 10px; border: 1px solid var(--k-muted-border);
  border-radius: var(--k-r-md); font-size: .86em; min-width: 0;
}
.fsk-tl .fsk-tl-ref .fsk-icon { color: var(--k-text-2); }
.fsk-tl .fsk-tl-ref span { flex: 1; min-width: 0; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; }
/* A linked email or call: the box itself opens it. */
.fsk-tl .fsk-tl-ref--open {
  width: 100%; background: none; color: inherit; font: inherit; font-size: .86em; text-align: left; text-decoration: none; cursor: pointer;
  transition: background .15s, border-color .15s;
}
.fsk-tl .fsk-tl-ref--open:hover { background: var(--k-hover); border-color: var(--k-border); }
.fsk-tl .fsk-tl-ref--open:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-tl .fsk-tl-ref--open .fsk-tl-go { flex: none; color: var(--k-text-2); transition: transform .2s var(--k-ease), color .15s; }
.fsk-tl .fsk-tl-ref--open:hover .fsk-tl-go { color: var(--k-primary); transform: translateX(2px); }
.fsk-tl .fsk-tl-note { margin: 3px 0 0; font-size: .86em; color: var(--k-text-2); display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; line-clamp: 3; overflow: hidden; }
.fsk-tl .fsk-tl-open { margin: 4px 0 -4px -4px; min-height: 28px; font-size: .86em; }
.fsk-tl .fsk-tl-open:focus-visible, .fsk-tl .fsk-tl-more:focus-visible, .fsk-tl .fsk-tl-foot .fsk-btn--link:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }

/* Collapsed: the rail fades out under the last shown event, then the button. */
.fsk-tl .fsk-tl-feed[data-collapsed] .fsk-tl-day:last-of-type .fsk-tl-ev:last-child::before {
  content: ""; position: absolute; left: 13.5px; top: 41px; bottom: -8px; width: 1px;
  background: linear-gradient(var(--k-divider), transparent);
}
.fsk-tl .fsk-tl-more {
  appearance: none; display: flex; align-items: center; justify-content: center; gap: 6px; width: 100%; min-height: 34px; margin-top: 6px;
  border: 1px dashed var(--k-border); border-radius: var(--k-r-md); background: none; color: var(--k-text-2); font: inherit; font-size: .86em; font-weight: 500;
  cursor: pointer; transition: background .15s, color .15s, border-color .15s;
}
.fsk-tl .fsk-tl-more:hover { background: var(--k-hover); color: var(--k-text); border-style: solid; }
.fsk-tl .fsk-tl-more .fsk-icon { transform: rotate(90deg); transition: transform .2s var(--k-ease); }
.fsk-tl .fsk-tl-more[aria-expanded="true"] .fsk-icon { transform: rotate(-90deg); }
.fsk-tl .fsk-tl-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--k-divider); font-size: .86em; color: var(--k-text-2); }
.fsk-tl .fsk-tl-foot .fsk-btn--link { margin-right: -4px; }
.fsk-tl .fsk-tl-empty { margin: 0; padding: 14px 0 4px; text-align: center; color: var(--k-text-2); }

/* Loading: a day label, then avatars on a rail with two lines each. */
.fsk-tl .fsk-tl-sk { display: flex; flex-direction: column; }
.fsk-tl .fsk-tl-sk-row { position: relative; display: grid; grid-template-columns: 28px minmax(0, 1fr) 40px; column-gap: 10px; padding: 8px 0 10px; }
.fsk-tl .fsk-tl-sk-row:not(:last-child)::before { content: ""; position: absolute; left: 13.5px; top: 42px; bottom: -6px; width: 1px; background: var(--k-divider); }

@container (max-width: 280px) {
  .fsk-tl .fsk-tl-line { flex-wrap: wrap; row-gap: 0; }
  .fsk-tl .fsk-tl-time { width: 100%; }
}
.fsk-tl[data-surface="mobile"] .fsk-tl-more, .fsk-tl[data-surface="mobile"] .fsk-tl-open, .fsk-tl[data-surface="mobile"] .fsk-tl-ref--open, .fsk-tl[data-surface="mobile"] .fsk-tl-foot .fsk-btn--link { min-height: 44px; }
.fsk-tl[data-surface="mobile"] .fsk-tl-open { margin-bottom: -10px; }
`;

export type TimelineKind = "created" | "updated" | "comment" | "status" | "email" | "call" | "system";

export interface TimelineChange {
  /** The field's name, e.g. "Stage". */
  field: string;
  /** The old value. Leave it out when the field was empty. */
  from?: string;
  /** The new value. */
  to: string;
}

export interface TimelineEvent {
  /** Your event's id: actions.open gets the event back. */
  id: string;
  /** Sets the icon and its tone: created, updated, comment, status, email, call or system. */
  kind: TimelineKind;
  /** Who did it, by name. Leave it out for events your system made. */
  actor?: string;
  /** A photo for the actor's avatar. Falls back to initials. */
  actorAvatarUrl?: string;
  /** What happened, after the actor's name: "moved the deal to Negotiation". Without an actor, the whole sentence. */
  action: string;
  /** When, as an ISO 8601 time. Shown relative ("2 hours ago"), the exact time on hover. */
  at: string;
  /** A comment's text, an email's subject or a call's note. Up to three lines show. */
  detail?: string;
  /** Field changes, drawn as old value, arrow, new value. */
  changes?: TimelineChange[];
  /** Shows a link on this event, e.g. "Open email". With href it goes there; without, it calls actions.open. */
  linkLabel?: string;
  /** Where the event's link goes in your app. */
  href?: string;
}

export interface TimelineData {
  title: string;
  subtitle?: string;
  /** Default: clock. */
  icon?: IconName;
  /** In any order: the card sorts them newest first and groups them by day. */
  events: TimelineEvent[];
  /** How many events show before "Show N earlier events". Default: 5. */
  visible?: number;
  /** Short note on the left of the footer, e.g. "Last 30 days". */
  footnote?: string;
  /** A footer link to the full history in your app. */
  link?: { label: string; href: string };
}

export interface TimelineActions {
  /** An event's link was clicked and the event has no href. Open it in your app. */
  open?(event: TimelineEvent): void;
}

export interface TimelineProps {
  root: HTMLElement;
  head: StyleHost;
  data: TimelineData;
  api?: CardApi;
  actions?: TimelineActions;
  /** "mobile": 44px links and button. Otherwise the same card. */
  surface?: "desktop" | "mobile";
}

const KINDS: Record<TimelineKind, { icon: IconName; tone: string; label: string }> = {
  created: { icon: "plus", tone: "success", label: "Created" },
  updated: { icon: "pencil", tone: "primary", label: "Updated" },
  comment: { icon: "message", tone: "primary", label: "Comment" },
  status: { icon: "flag", tone: "warning", label: "Status change" },
  email: { icon: "mail", tone: "primary", label: "Email" },
  call: { icon: "phone", tone: "success", label: "Call" },
  system: { icon: "zap", tone: "neutral", label: "Automatic" },
};

const dayKey = (d: Date): string => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;

/** "Today", "Yesterday", a weekday this week, then a date. */
function dayLabel(d: Date, now: Date): string {
  const start = (x: Date): number => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
  const days = Math.round((start(now) - start(d)) / 86400000);
  if (days === 0) return "Today";
  if (days === 1) return "Yesterday";
  if (days > 1 && days < 7) return new Intl.DateTimeFormat(undefined, { weekday: "long", month: "short", day: "numeric" }).format(d);
  return formatDate(d);
}

const exact = (d: Date): string => new Intl.DateTimeFormat(undefined, { dateStyle: "full", timeStyle: "short" }).format(d);
const clock = (d: Date): string => new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(d);
const sentence = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1);

/** Read-only: draws the feed and reports "displayed", so the agent doesn't wait. Event links open in your app. */
export function mount({ root, head, data, api, actions, surface = "desktop" }: TimelineProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tl", CSS);

  const now = new Date();
  const events = data.events
    .map((e) => ({ e, d: new Date(e.at) }))
    .filter((x) => !Number.isNaN(x.d.getTime()))
    .sort((a, b) => b.d.getTime() - a.d.getTime());
  const limit = Math.max(1, data.visible ?? 5);
  // Collapse only when it hides at least two: "Show 1 earlier event" isn't worth a click.
  const collapsible = events.length - limit >= 2;
  let expanded = !collapsible;

  const eventEl = (x: { e: TimelineEvent; d: Date }, fresh: boolean): HTMLElement => {
    const { e, d } = x;
    const k = KINDS[e.kind] ?? KINDS.system;
    const node = e.actor
      ? h("span", { class: "fsk-tl-node", "aria-hidden": "true" },
        avatar(e.actor, { url: e.actorAvatarUrl, size: 28 }),
        h("span", { class: "fsk-tl-badge", "data-tone": k.tone }, icon(k.icon, 10)))
      : h("span", { class: "fsk-tl-node", "aria-hidden": "true" }, h("span", { class: "fsk-tl-sys", "data-tone": k.tone }, icon(k.icon, 14)));
    const today = dayKey(d) === dayKey(now);
    const opens = !!e.linkLabel && !!(e.href || actions?.open);
    // A link: an <a> with href, else a button that calls actions.open.
    const linkTo = (cls: string, kids: (Node | string)[], label?: string): HTMLElement => e.href
      ? h("a", { class: cls, href: e.href, target: "_top", "aria-label": label, title: label ? e.linkLabel : null }, kids)
      : h("button", { class: cls, type: "button", "aria-label": label, title: label ? e.linkLabel : null, onclick: () => actions?.open?.(e) }, kids);
    // An email's subject sits in a box (the box opens the email); comments and call notes read as quotes.
    const ref = e.kind === "email";
    const refKids = (): (Node | string)[] => [icon("mail", 14), h("span", {}, e.detail ?? "")];
    const detail = !e.detail ? null
      : e.kind === "comment" || e.kind === "call" ? h("p", { class: "fsk-tl-quote" }, e.detail)
      : ref && opens ? linkTo("fsk-tl-ref fsk-tl-ref--open", [...refKids(), h("span", { class: "fsk-tl-go", "aria-hidden": "true" }, icon("chevron", 14))], `${e.linkLabel}: ${e.detail}`)
      : ref ? h("p", { class: "fsk-tl-ref" }, refKids())
      : h("p", { class: "fsk-tl-note" }, e.detail);
    const link = opens && !(ref && e.detail) ? linkTo("fsk-btn fsk-btn--link fsk-tl-open", [e.linkLabel ?? "", icon("chevron", 12)]) : null;
    return h("li", { class: `fsk-tl-ev${fresh ? " fsk-tl-ev--new" : ""}`, "data-kind": e.kind, "data-id": e.id, tabindex: "-1" },
      node,
      h("div", { class: "fsk-tl-body" },
        h("p", { class: "fsk-tl-line" },
          h("span", { class: "fsk-tl-what" },
            h("span", { class: "fsk-sr" }, `${k.label}: `),
            e.actor ? [h("span", { class: "fsk-tl-who" }, e.actor), " ", e.action] : sentence(e.action)),
          h("time", { class: "fsk-tl-time fsk-num", datetime: e.at, title: exact(d) }, today ? formatRelative(d) : clock(d))),
        (e.changes?.length ?? 0) > 0 && h("ul", { class: "fsk-tl-changes" }, (e.changes ?? []).map((c) =>
          h("li", { class: "fsk-tl-change" },
            h("span", { class: "fsk-tl-field" }, c.field),
            c.from != null && [h("span", { class: "fsk-tl-from" }, h("span", { class: "fsk-sr" }, "from "), c.from),
              h("span", { class: "fsk-tl-arrow", "aria-hidden": "true" }, icon("arrowRight", 12))],
            h("span", { class: "fsk-tl-to" }, h("span", { class: "fsk-sr" }, c.from != null ? "to " : "set to "), c.to)))),
        detail,
        link));
  };

  const feed = h("div", { class: "fsk-tl-feed" });
  const more = collapsible ? h<HTMLButtonElement>("button", { class: "fsk-tl-more", type: "button", "aria-expanded": "false", onclick: () => toggle() }) : null;

  function draw(fromIndex: number): void {
    const list = expanded ? events : events.slice(0, limit);
    const groups: { label: string; title: string; items: HTMLElement[] }[] = [];
    let key = "";
    list.forEach((x, i) => {
      const k = dayKey(x.d);
      if (k !== key) { key = k; groups.push({ label: dayLabel(x.d, now), title: formatDate(x.d, { year: true }), items: [] }); }
      groups[groups.length - 1].items.push(eventEl(x, i >= fromIndex));
    });
    feed.replaceChildren(...groups.map((g) => h("section", { class: "fsk-tl-day", "aria-label": g.label },
      h("h4", { class: "fsk-tl-dayhead", title: g.title }, g.label),
      h("ol", { class: "fsk-tl-list" }, g.items))));
    if (expanded) feed.removeAttribute("data-collapsed"); else feed.setAttribute("data-collapsed", "");
    if (more) {
      const hidden = events.length - limit;
      more.setAttribute("aria-expanded", String(expanded));
      more.replaceChildren(expanded ? "Show fewer" : `Show ${hidden} earlier event${hidden === 1 ? "" : "s"}`, icon("chevron", 14));
    }
  }

  function toggle(): void {
    expanded = !expanded;
    draw(expanded ? limit : Infinity);
    // Keyboard users land on the first event that appeared; collapsing keeps focus on the button.
    if (expanded) feed.querySelectorAll<HTMLElement>(".fsk-tl-ev")[limit]?.focus({ preventScroll: false });
  }

  draw(Infinity); // the card itself animates in; only events revealed later animate on their own

  const card = h("section", { class: "fsk fsk-card fsk-tl", "data-surface": surface, "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip", "aria-hidden": "true" }, icon(data.icon ?? "clock", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    events.length ? feed : h("p", { class: "fsk-tl-empty" }, "Nothing has happened here yet."),
    more,
    (data.footnote || data.link) && h("footer", { class: "fsk-tl-foot" },
      h("span", {}, data.footnote ?? ""),
      data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href, target: "_top" }, data.link.label, icon("chevron", 14))));

  root.replaceChildren(card);
  api?.displayed?.(); // read-only: shown, the agent doesn't wait
  return () => root.replaceChildren();
}

/** The states this card draws besides its data. */
export const states: StateKind[] = ["loading", "empty", "error"];

/** Loading (avatars on a rail), empty or error, drawn as this card. Read-only: report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop" }: StateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tl", CSS);
  const W = [72, 54, 80, 62];
  const skeleton = (): HTMLElement => h("div", { class: "fsk-tl-sk" },
    bone("22%", "9px"),
    W.map((w, i) => h("div", { class: "fsk-tl-sk-row" },
      bone("28px", "28px", { cls: "fsk-bone--round", i }),
      h("div", { class: "fsk-sk-stack", style: { paddingTop: "4px" } }, bone(`${w}%`, "10px", { i }), bone(`${w - 22}%`, "8px", { i })),
      bone("40px", "8px", { i }))));
  const card = stateCard({ state, cls: "fsk-tl", icon: "clock", title, subtitle, surface, skeleton });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

// Fixture times are relative to now, so "Today" and "Yesterday" always read right.
const minutesAgo = (m: number): string => new Date(Date.now() - m * 60000).toISOString();
const daysAgo = (days: number, hour: number, minute: number): string => {
  const d = new Date();
  d.setDate(d.getDate() - days);
  d.setHours(hour, minute, 0, 0);
  return d.toISOString();
};

export const fixtures: Record<string, TimelineData> = {
  default: {
    title: "EU rollout · Globex Retail",
    subtitle: "Deal activity · $72,000 · Negotiation",
    icon: "briefcase",
    events: [
      { id: "ev_311", kind: "comment", actor: "Dana Ortiz", action: "left a comment", at: minutesAgo(12),
        detail: "Legal signed off on the DPA. Procurement still owes us the PO number; they said Thursday." },
      { id: "ev_310", kind: "email", actor: "Sam Patel", action: "emailed Erin Walsh", at: minutesAgo(128),
        detail: "Revised order form for the EU rollout (v3)", linkLabel: "Open email" },
      { id: "ev_309", kind: "status", actor: "Dana Ortiz", action: "moved the deal to Negotiation", at: minutesAgo(190),
        changes: [{ field: "Stage", from: "Proposal", to: "Negotiation" }] },
      { id: "ev_305", kind: "updated", actor: "Dana Ortiz", action: "updated 2 fields", at: daysAgo(1, 16, 40),
        changes: [{ field: "Amount", from: "$64,000", to: "$72,000" }, { field: "Close date", from: "Dec 12", to: "Nov 30" }] },
      { id: "ev_302", kind: "call", actor: "Sam Patel", action: "logged a call with Erin Walsh", at: daysAgo(1, 11, 15),
        detail: "32 min. Walked through the Berlin and Lyon rollout. Erin wants the EU data residency terms in writing before legal review.", linkLabel: "Open call notes" },
      { id: "ev_298", kind: "system", action: "at-risk flag cleared after Globex Retail replied", at: daysAgo(2, 15, 2) },
      { id: "ev_296", kind: "email", actor: "Erin Walsh", action: "replied to Sam Patel", at: daysAgo(3, 9, 48),
        detail: "Re: EU rollout pricing" },
      { id: "ev_291", kind: "comment", actor: "Lee Kim", action: "left a comment", at: daysAgo(4, 14, 20),
        detail: "Looping in solutions engineering for the SSO question." },
      { id: "ev_288", kind: "updated", actor: "Sam Patel", action: "changed the owner", at: daysAgo(5, 10, 5),
        changes: [{ field: "Owner", from: "Lee Kim", to: "Dana Ortiz" }] },
      { id: "ev_280", kind: "created", actor: "Lee Kim", action: "created the deal", at: daysAgo(9, 13, 30),
        changes: [{ field: "Amount", to: "$64,000" }, { field: "Stage", to: "Discovery" }] },
      { id: "ev_279", kind: "system", action: "lead assigned to Lee Kim by the EMEA routing rule", at: daysAgo(9, 13, 12) },
    ],
    visible: 5,
    link: { label: "Open deal", href: "/deals/deal_801" },
  },
};
```

```js title="agent/ui/timeline.js"
// Template: timeline. A read-only chat card with what happened to one record, newest first, grouped by day.

export const meta = {
  id: "timeline",
  title: "Timeline",
  surface: "card",
  kind: "read-only",
  mobile: "same",
  whenToUse: "The user asks what happened to one record (a deal, a ticket, an order): who did what and when, in order. Comments, emails, status moves and field changes, grouped by day.",
  whenNotToUse: "The record's current state matters more than its history (entity card). Events across many records (records list or table). A trend in numbers over time (chart).",
};

const CSS = `
.fsk-tl { container-type: inline-size; }
.fsk-tl .fsk-head > div { flex: 1; min-width: 0; }
.fsk-tl .fsk-tl-day + .fsk-tl-day { margin-top: 6px; }
.fsk-tl .fsk-tl-dayhead {
  display: flex; align-items: center; gap: 10px; margin: 0 0 4px; font-size: .79em; font-weight: 600; color: var(--k-text-2);
  letter-spacing: .01em;
}
.fsk-tl .fsk-tl-dayhead::after { content: ""; flex: 1; height: 1px; background: var(--k-divider); }
.fsk-tl .fsk-tl-list { margin: 0; padding: 0; list-style: none; }
.fsk-tl .fsk-tl-ev {
  position: relative; display: grid; grid-template-columns: 28px minmax(0, 1fr); column-gap: 10px; padding: 7px 0 9px;
  border-radius: var(--k-r-md); outline: none;
}
.fsk-tl .fsk-tl-ev:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
/* The rail: from under this event's avatar down to the next one. */
.fsk-tl .fsk-tl-ev:not(:last-child)::before {
  content: ""; position: absolute; left: 13.5px; top: 41px; bottom: -5px; width: 1px; background: var(--k-divider);
}
.fsk-tl .fsk-tl-ev--new { animation: fsk-in .3s var(--k-ease) both; }
.fsk-tl .fsk-tl-node { position: relative; width: 28px; height: 28px; }
.fsk-tl .fsk-tl-node .fsk-avatar { box-shadow: 0 0 0 2px var(--k-paper); }
.fsk-tl .fsk-tl-sys {
  display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%;
  color: color-mix(in srgb, var(--tone) 80%, var(--k-text)); background: color-mix(in srgb, var(--tone) 12%, var(--k-paper));
  box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--tone) 22%, var(--k-paper)), 0 0 0 2px var(--k-paper);
}
.fsk-tl .fsk-tl-badge {
  position: absolute; right: -6px; bottom: -4px; display: grid; place-items: center; width: 15px; height: 15px; border-radius: 50%;
  color: var(--k-paper); background: var(--tone); box-shadow: 0 0 0 2px var(--k-paper);
}
.fsk-tl [data-tone="primary"] { --tone: var(--k-primary); }
.fsk-tl [data-tone="success"] { --tone: var(--k-success); }
.fsk-tl [data-tone="warning"] { --tone: var(--k-warning); }
.fsk-tl [data-tone="neutral"] { --tone: var(--k-text-2); }
.fsk-tl .fsk-tl-body { min-width: 0; }
.fsk-tl .fsk-tl-line { display: flex; align-items: baseline; gap: 8px; margin: 0; min-height: 28px; padding-top: 4px; line-height: 1.4; }
.fsk-tl .fsk-tl-what { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.fsk-tl .fsk-tl-who { font-weight: 600; }
.fsk-tl .fsk-tl-time { flex: none; font-size: .79em; color: var(--k-text-2); white-space: nowrap; cursor: default; }
.fsk-tl .fsk-tl-changes { display: grid; gap: 3px; margin: 5px 0 0; padding: 0; list-style: none; font-size: .86em; }
.fsk-tl .fsk-tl-change { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 6px; min-width: 0; }
.fsk-tl .fsk-tl-field { color: var(--k-text-2); }
.fsk-tl .fsk-tl-from { color: var(--k-text-2); text-decoration: line-through; text-decoration-color: color-mix(in srgb, var(--k-text-2) 60%, transparent); }
.fsk-tl .fsk-tl-arrow { color: var(--k-text-2); opacity: .8; }
.fsk-tl .fsk-tl-to {
  padding: 0 6px; border-radius: min(var(--k-r), 6px); font-weight: 550;
  color: color-mix(in srgb, var(--k-primary) 70%, var(--k-text)); background: var(--k-tint);
}
.fsk-tl .fsk-tl-quote {
  margin: 6px 0 0; padding: 7px 10px; border-radius: 2px var(--k-r-md) var(--k-r-md) var(--k-r-md); background: var(--k-sunken);
  font-size: .93em; line-height: 1.45; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; line-clamp: 3; overflow: hidden;
}
.fsk-tl .fsk-tl-ref {
  display: flex; align-items: center; gap: 8px; margin: 6px 0 0; padding: 6px 10px; border: 1px solid var(--k-muted-border);
  border-radius: var(--k-r-md); font-size: .86em; min-width: 0;
}
.fsk-tl .fsk-tl-ref .fsk-icon { color: var(--k-text-2); }
.fsk-tl .fsk-tl-ref span { flex: 1; min-width: 0; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden; }
/* A linked email or call: the box itself opens it. */
.fsk-tl .fsk-tl-ref--open {
  width: 100%; background: none; color: inherit; font: inherit; font-size: .86em; text-align: left; text-decoration: none; cursor: pointer;
  transition: background .15s, border-color .15s;
}
.fsk-tl .fsk-tl-ref--open:hover { background: var(--k-hover); border-color: var(--k-border); }
.fsk-tl .fsk-tl-ref--open:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-tl .fsk-tl-ref--open .fsk-tl-go { flex: none; color: var(--k-text-2); transition: transform .2s var(--k-ease), color .15s; }
.fsk-tl .fsk-tl-ref--open:hover .fsk-tl-go { color: var(--k-primary); transform: translateX(2px); }
.fsk-tl .fsk-tl-note { margin: 3px 0 0; font-size: .86em; color: var(--k-text-2); display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; line-clamp: 3; overflow: hidden; }
.fsk-tl .fsk-tl-open { margin: 4px 0 -4px -4px; min-height: 28px; font-size: .86em; }
.fsk-tl .fsk-tl-open:focus-visible, .fsk-tl .fsk-tl-more:focus-visible, .fsk-tl .fsk-tl-foot .fsk-btn--link:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }

/* Collapsed: the rail fades out under the last shown event, then the button. */
.fsk-tl .fsk-tl-feed[data-collapsed] .fsk-tl-day:last-of-type .fsk-tl-ev:last-child::before {
  content: ""; position: absolute; left: 13.5px; top: 41px; bottom: -8px; width: 1px;
  background: linear-gradient(var(--k-divider), transparent);
}
.fsk-tl .fsk-tl-more {
  appearance: none; display: flex; align-items: center; justify-content: center; gap: 6px; width: 100%; min-height: 34px; margin-top: 6px;
  border: 1px dashed var(--k-border); border-radius: var(--k-r-md); background: none; color: var(--k-text-2); font: inherit; font-size: .86em; font-weight: 500;
  cursor: pointer; transition: background .15s, color .15s, border-color .15s;
}
.fsk-tl .fsk-tl-more:hover { background: var(--k-hover); color: var(--k-text); border-style: solid; }
.fsk-tl .fsk-tl-more .fsk-icon { transform: rotate(90deg); transition: transform .2s var(--k-ease); }
.fsk-tl .fsk-tl-more[aria-expanded="true"] .fsk-icon { transform: rotate(-90deg); }
.fsk-tl .fsk-tl-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--k-divider); font-size: .86em; color: var(--k-text-2); }
.fsk-tl .fsk-tl-foot .fsk-btn--link { margin-right: -4px; }
.fsk-tl .fsk-tl-empty { margin: 0; padding: 14px 0 4px; text-align: center; color: var(--k-text-2); }

/* Loading: a day label, then avatars on a rail with two lines each. */
.fsk-tl .fsk-tl-sk { display: flex; flex-direction: column; }
.fsk-tl .fsk-tl-sk-row { position: relative; display: grid; grid-template-columns: 28px minmax(0, 1fr) 40px; column-gap: 10px; padding: 8px 0 10px; }
.fsk-tl .fsk-tl-sk-row:not(:last-child)::before { content: ""; position: absolute; left: 13.5px; top: 42px; bottom: -6px; width: 1px; background: var(--k-divider); }

@container (max-width: 280px) {
  .fsk-tl .fsk-tl-line { flex-wrap: wrap; row-gap: 0; }
  .fsk-tl .fsk-tl-time { width: 100%; }
}
.fsk-tl[data-surface="mobile"] .fsk-tl-more, .fsk-tl[data-surface="mobile"] .fsk-tl-open, .fsk-tl[data-surface="mobile"] .fsk-tl-ref--open, .fsk-tl[data-surface="mobile"] .fsk-tl-foot .fsk-btn--link { min-height: 44px; }
.fsk-tl[data-surface="mobile"] .fsk-tl-open { margin-bottom: -10px; }
`;

const KINDS = {
  created: { icon: "plus", tone: "success", label: "Created" },
  updated: { icon: "pencil", tone: "primary", label: "Updated" },
  comment: { icon: "message", tone: "primary", label: "Comment" },
  status: { icon: "flag", tone: "warning", label: "Status change" },
  email: { icon: "mail", tone: "primary", label: "Email" },
  call: { icon: "phone", tone: "success", label: "Call" },
  system: { icon: "zap", tone: "neutral", label: "Automatic" },
};

const dayKey = (d) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;

/** "Today", "Yesterday", a weekday this week, then a date. */
function dayLabel(d, now) {
  const start = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
  const days = Math.round((start(now) - start(d)) / 86400000);
  if (days === 0) return "Today";
  if (days === 1) return "Yesterday";
  if (days > 1 && days < 7) return new Intl.DateTimeFormat(undefined, { weekday: "long", month: "short", day: "numeric" }).format(d);
  return formatDate(d);
}

const exact = (d) => new Intl.DateTimeFormat(undefined, { dateStyle: "full", timeStyle: "short" }).format(d);
const clock = (d) => new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(d);
const sentence = (s) => s.charAt(0).toUpperCase() + s.slice(1);

/** Read-only: draws the feed and reports "displayed", so the agent doesn't wait. Event links open in your app. */
export function mount({ root, head, data, api, actions, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tl", CSS);

  const now = new Date();
  const events = data.events
    .map((e) => ({ e, d: new Date(e.at) }))
    .filter((x) => !Number.isNaN(x.d.getTime()))
    .sort((a, b) => b.d.getTime() - a.d.getTime());
  const limit = Math.max(1, data.visible ?? 5);
  // Collapse only when it hides at least two: "Show 1 earlier event" isn't worth a click.
  const collapsible = events.length - limit >= 2;
  let expanded = !collapsible;

  const eventEl = (x, fresh) => {
    const { e, d } = x;
    const k = KINDS[e.kind] ?? KINDS.system;
    const node = e.actor
      ? h("span", { class: "fsk-tl-node", "aria-hidden": "true" },
        avatar(e.actor, { url: e.actorAvatarUrl, size: 28 }),
        h("span", { class: "fsk-tl-badge", "data-tone": k.tone }, icon(k.icon, 10)))
      : h("span", { class: "fsk-tl-node", "aria-hidden": "true" }, h("span", { class: "fsk-tl-sys", "data-tone": k.tone }, icon(k.icon, 14)));
    const today = dayKey(d) === dayKey(now);
    const opens = !!e.linkLabel && !!(e.href || actions?.open);
    // A link: an <a> with href, else a button that calls actions.open.
    const linkTo = (cls, kids, label) => e.href
      ? h("a", { class: cls, href: e.href, target: "_top", "aria-label": label, title: label ? e.linkLabel : null }, kids)
      : h("button", { class: cls, type: "button", "aria-label": label, title: label ? e.linkLabel : null, onclick: () => actions?.open?.(e) }, kids);
    // An email's subject sits in a box (the box opens the email); comments and call notes read as quotes.
    const ref = e.kind === "email";
    const refKids = () => [icon("mail", 14), h("span", {}, e.detail ?? "")];
    const detail = !e.detail ? null
      : e.kind === "comment" || e.kind === "call" ? h("p", { class: "fsk-tl-quote" }, e.detail)
      : ref && opens ? linkTo("fsk-tl-ref fsk-tl-ref--open", [...refKids(), h("span", { class: "fsk-tl-go", "aria-hidden": "true" }, icon("chevron", 14))], `${e.linkLabel}: ${e.detail}`)
      : ref ? h("p", { class: "fsk-tl-ref" }, refKids())
      : h("p", { class: "fsk-tl-note" }, e.detail);
    const link = opens && !(ref && e.detail) ? linkTo("fsk-btn fsk-btn--link fsk-tl-open", [e.linkLabel ?? "", icon("chevron", 12)]) : null;
    return h("li", { class: `fsk-tl-ev${fresh ? " fsk-tl-ev--new" : ""}`, "data-kind": e.kind, "data-id": e.id, tabindex: "-1" },
      node,
      h("div", { class: "fsk-tl-body" },
        h("p", { class: "fsk-tl-line" },
          h("span", { class: "fsk-tl-what" },
            h("span", { class: "fsk-sr" }, `${k.label}: `),
            e.actor ? [h("span", { class: "fsk-tl-who" }, e.actor), " ", e.action] : sentence(e.action)),
          h("time", { class: "fsk-tl-time fsk-num", datetime: e.at, title: exact(d) }, today ? formatRelative(d) : clock(d))),
        (e.changes?.length ?? 0) > 0 && h("ul", { class: "fsk-tl-changes" }, (e.changes ?? []).map((c) =>
          h("li", { class: "fsk-tl-change" },
            h("span", { class: "fsk-tl-field" }, c.field),
            c.from != null && [h("span", { class: "fsk-tl-from" }, h("span", { class: "fsk-sr" }, "from "), c.from),
              h("span", { class: "fsk-tl-arrow", "aria-hidden": "true" }, icon("arrowRight", 12))],
            h("span", { class: "fsk-tl-to" }, h("span", { class: "fsk-sr" }, c.from != null ? "to " : "set to "), c.to)))),
        detail,
        link));
  };

  const feed = h("div", { class: "fsk-tl-feed" });
  const more = collapsible ? h("button", { class: "fsk-tl-more", type: "button", "aria-expanded": "false", onclick: () => toggle() }) : null;

  function draw(fromIndex) {
    const list = expanded ? events : events.slice(0, limit);
    const groups = [];
    let key = "";
    list.forEach((x, i) => {
      const k = dayKey(x.d);
      if (k !== key) { key = k; groups.push({ label: dayLabel(x.d, now), title: formatDate(x.d, { year: true }), items: [] }); }
      groups[groups.length - 1].items.push(eventEl(x, i >= fromIndex));
    });
    feed.replaceChildren(...groups.map((g) => h("section", { class: "fsk-tl-day", "aria-label": g.label },
      h("h4", { class: "fsk-tl-dayhead", title: g.title }, g.label),
      h("ol", { class: "fsk-tl-list" }, g.items))));
    if (expanded) feed.removeAttribute("data-collapsed"); else feed.setAttribute("data-collapsed", "");
    if (more) {
      const hidden = events.length - limit;
      more.setAttribute("aria-expanded", String(expanded));
      more.replaceChildren(expanded ? "Show fewer" : `Show ${hidden} earlier event${hidden === 1 ? "" : "s"}`, icon("chevron", 14));
    }
  }

  function toggle() {
    expanded = !expanded;
    draw(expanded ? limit : Infinity);
    // Keyboard users land on the first event that appeared; collapsing keeps focus on the button.
    if (expanded) feed.querySelectorAll(".fsk-tl-ev")[limit]?.focus({ preventScroll: false });
  }

  draw(Infinity); // the card itself animates in; only events revealed later animate on their own

  const card = h("section", { class: "fsk fsk-card fsk-tl", "data-surface": surface, "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip", "aria-hidden": "true" }, icon(data.icon ?? "clock", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    events.length ? feed : h("p", { class: "fsk-tl-empty" }, "Nothing has happened here yet."),
    more,
    (data.footnote || data.link) && h("footer", { class: "fsk-tl-foot" },
      h("span", {}, data.footnote ?? ""),
      data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href, target: "_top" }, data.link.label, icon("chevron", 14))));

  root.replaceChildren(card);
  api?.displayed?.(); // read-only: shown, the agent doesn't wait
  return () => root.replaceChildren();
}

/** The states this card draws besides its data. */
export const states = ["loading", "empty", "error"];

/** Loading (avatars on a rail), empty or error, drawn as this card. Read-only: report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tl", CSS);
  const W = [72, 54, 80, 62];
  const skeleton = () => h("div", { class: "fsk-tl-sk" },
    bone("22%", "9px"),
    W.map((w, i) => h("div", { class: "fsk-tl-sk-row" },
      bone("28px", "28px", { cls: "fsk-bone--round", i }),
      h("div", { class: "fsk-sk-stack", style: { paddingTop: "4px" } }, bone(`${w}%`, "10px", { i }), bone(`${w - 22}%`, "8px", { i })),
      bone("40px", "8px", { i }))));
  const card = stateCard({ state, cls: "fsk-tl", icon: "clock", title, subtitle, surface, skeleton });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

// Fixture times are relative to now, so "Today" and "Yesterday" always read right.
const minutesAgo = (m) => new Date(Date.now() - m * 60000).toISOString();
const daysAgo = (days, hour, minute) => {
  const d = new Date();
  d.setDate(d.getDate() - days);
  d.setHours(hour, minute, 0, 0);
  return d.toISOString();
};

export const fixtures = {
  default: {
    title: "EU rollout · Globex Retail",
    subtitle: "Deal activity · $72,000 · Negotiation",
    icon: "briefcase",
    events: [
      { id: "ev_311", kind: "comment", actor: "Dana Ortiz", action: "left a comment", at: minutesAgo(12),
        detail: "Legal signed off on the DPA. Procurement still owes us the PO number; they said Thursday." },
      { id: "ev_310", kind: "email", actor: "Sam Patel", action: "emailed Erin Walsh", at: minutesAgo(128),
        detail: "Revised order form for the EU rollout (v3)", linkLabel: "Open email" },
      { id: "ev_309", kind: "status", actor: "Dana Ortiz", action: "moved the deal to Negotiation", at: minutesAgo(190),
        changes: [{ field: "Stage", from: "Proposal", to: "Negotiation" }] },
      { id: "ev_305", kind: "updated", actor: "Dana Ortiz", action: "updated 2 fields", at: daysAgo(1, 16, 40),
        changes: [{ field: "Amount", from: "$64,000", to: "$72,000" }, { field: "Close date", from: "Dec 12", to: "Nov 30" }] },
      { id: "ev_302", kind: "call", actor: "Sam Patel", action: "logged a call with Erin Walsh", at: daysAgo(1, 11, 15),
        detail: "32 min. Walked through the Berlin and Lyon rollout. Erin wants the EU data residency terms in writing before legal review.", linkLabel: "Open call notes" },
      { id: "ev_298", kind: "system", action: "at-risk flag cleared after Globex Retail replied", at: daysAgo(2, 15, 2) },
      { id: "ev_296", kind: "email", actor: "Erin Walsh", action: "replied to Sam Patel", at: daysAgo(3, 9, 48),
        detail: "Re: EU rollout pricing" },
      { id: "ev_291", kind: "comment", actor: "Lee Kim", action: "left a comment", at: daysAgo(4, 14, 20),
        detail: "Looping in solutions engineering for the SSO question." },
      { id: "ev_288", kind: "updated", actor: "Sam Patel", action: "changed the owner", at: daysAgo(5, 10, 5),
        changes: [{ field: "Owner", from: "Lee Kim", to: "Dana Ortiz" }] },
      { id: "ev_280", kind: "created", actor: "Lee Kim", action: "created the deal", at: daysAgo(9, 13, 30),
        changes: [{ field: "Amount", to: "$64,000" }, { field: "Stage", to: "Discovery" }] },
      { id: "ev_279", kind: "system", action: "lead assigned to Lee Kim by the EMEA routing rule", at: daysAgo(9, 13, 12) },
    ],
    visible: 5,
    link: { label: "Open deal", href: "/deals/deal_801" },
  },
};
```

### fs-kit (shared by every template)

TypeScript: /ui-catalog/files/ts/fs-kit.ts, JavaScript: /ui-catalog/files/js/fs-kit.js
