# Live cursors

URL: https://docs.folkways.io/docs/examples/live-cursors

Show everyone's cursor on a shared document, with a shared title everyone can edit and a list of who's viewing.

One topic per document, `docs/{doc}`:

| Event | Primitive | Why |
| --- | --- | --- |
| `cursor` | [Signal](/docs/primitives/signal) | Only the latest position per person matters, and it's stale in seconds |
| `title` | [KV](/docs/primitives/kv), one shared key | Everyone sees the current title, including people who open the document later |
| viewers | [Presence](/docs/primitives/presence) | Who has the document open |

## Define the topic and the rule [#define-the-topic-and-the-rule]

```ts title="topics.ts" check=cursors
import { defineTopic } from '@folkwaysio/realtime';

export type DocEvents = {
  cursor: { x: number; y: number; color: string };
  title: { text: string };
};

export const liveDoc = defineTopic<DocEvents>()('docs/{doc}', {
  events: {
    cursor: { delivery: 'signal', ttlMs: 3_000 },
    title: 'kv',
  },
  presence: true,
});
```

Paste `JSON.stringify([liveDoc.rule()])` on the segment's **Topic rules** tab. Give viewers a token with
`subscribe`, `set`, `signal` and `presence` on `docs/*`; see the [chat room's token endpoint](/docs/examples/chat-room#3-issue-tokens).

## The app [#the-app]

```ts title="cursors.ts" check=cursors
import { Folkways } from '@folkwaysio/realtime';
// import { liveDoc } from './topics';

declare function drawCursors(cursors: { who: string; x: number; y: number; color: string }[]): void;
declare function showTitle(text: string): void;
declare function showViewers(people: string[]): void;

const client = await Folkways.connect({ url: 'https://realtime.folkways.net', authUrl: '/api/realtime-token' });
const me = client.session?.identity;

export async function openDocument(docId: string, color: string) {
  const doc = liveDoc.open(client, { doc: docId });
  const viewersTopic = client.topic(`$presence/${doc.name}`);

  const cursors = doc.values('cursor').open();
  const title = doc.values('title').open();
  const viewers = viewersTopic.values().open();

  const stops = [
    cursors.subscribe(() => {
      drawCursors([...cursors.getSnapshot().values()]
        .filter((m) => m.publisher !== me)
        .map((m) => ({ who: m.publisher, ...(m.data as { x: number; y: number; color: string }) })));
    }),
    title.subscribe(() => {
      const current = title.getSnapshot().get('doc');
      if (current) showTitle((current.data as { text: string }).text);
    }),
    viewers.subscribe(() => {
      showViewers([...new Set([...viewers.getSnapshot().values()].map((e) => (e.data as { identity: string }).identity))]);
    }),
  ];
  const subscription = doc.subscribe();
  const viewersSub = viewersTopic.subscribe();
  await subscription.ready;

  // Send at most 10 cursor updates a second, and only when the cursor moved.
  let pending: { x: number; y: number } | undefined;
  const timer = setInterval(() => {
    if (!pending) return;
    void doc.publish('cursor', { ...pending, color });
    pending = undefined;
  }, 100);

  return {
    move(x: number, y: number) {
      pending = { x, y };
    },
    rename(text: string) {
      // One shared key, so the title is a single value everyone edits. Last write wins.
      return doc.publish('title', { text }, { key: 'doc' });
    },
    async close() {
      clearInterval(timer);
      stops.forEach((stop) => stop());
      [cursors, title, viewers].forEach((view) => view.dispose());
      await Promise.all([subscription.unsubscribe(), viewersSub.unsubscribe()]);
    },
  };
}
```

## How it behaves [#how-it-behaves]

- A cursor disappears 3 seconds after its owner stops moving it, or leaves: signals expire on their own.
- Someone who opens the document later gets the cursors still alive and the current title at once, from the
  snapshot.
- Cursor updates are best effort. A dropped one is replaced by the next a tenth of a second later.
- Throttling keeps you inside the segment's [rate limits](/docs/realtime-api/limits#rate-limits). For many active
  users in one document, pick the **Live dashboard** or **AI streaming** [rate preset](/docs/console/segments#rate-preset)
  if publishes start coming back `RateLimited`.

## Going further [#going-further]

For collaborative text, send edits as **stream** events (ordered and replayable) from a CRDT or OT library, and keep
the document itself in your own storage. The title shows the limit of KV: the last write wins, with no merging.
