# Notifier

A "lookless" app-wide notification system. `NotificationManager` is a singleton that owns notification state, queueing, and timing — it doesn't know how to draw anything. A `NotificationRenderer` (the built-in "pill" renderer, or your own) is responsible for showing/hiding notifications on screen.

```typescript
import { NotificationManager } from '../src/index.js';

NotificationManager.notify({ type: 'info', message: 'Saved.' });
```

No setup required — the first `notify()` call lazily creates a default pill renderer (`top-right`, list display).

---

## `NotificationManager`

### `notify(content): string`

```typescript
const id = NotificationManager.notify({
  type: 'error',              // 'info' | 'warning' | 'error'
  message: 'Upload failed',
  icon: 'error',               // optional; errors default to 'error' if omitted
  onTap: (id) => { /* per-notification tap handler */ },
});
```

Returns the notification's `id`, which can be used to `update()` or `dismiss()` it later.

### `update(id, content): void`

```typescript
NotificationManager.update(id, { message: 'Still uploading…' });
```

Merges the given fields into the existing notification and, if it's currently the front (displayed) message, resets its dismissal timer.

### `dismiss(id): void` / `dismissAll(): void`

Programmatically hide one notification, or clear everything.

### `configure(options): void`

Merges into the current configuration. Can be called any time, including after notifications are already showing.

```typescript
NotificationManager.configure({
  timeout: 4000,
  timeoutError: 8000,
  queue: true,
  queueSize: 3,
  tapBehaviour: 'dismiss',
  tapHandlerDefault: (notification) => console.log(notification.message),
  renderer: createPillRenderer({ position: 'bottom-right' }),
});
```

| Option | Type | Default | Description |
|---|---|---|---|
| `renderer` | `NotificationRenderer` | built-in pill renderer | Swap the display implementation. See [Custom renderers](#custom-renderers). |
| `timeout` | `number` (ms) | `4000` | Default display time for `info`/`warning` messages. |
| `timeoutError` | `number` (ms) | `8000` | Display time for `error` messages. |
| `queue` | `boolean` | `true` | `true`: up to `queueSize` messages can be waiting at once (see below). `false`: each new message immediately replaces whatever is showing. |
| `queueSize` | `number` | `3` | Max number of messages held at once when `queue` is `true`. Shrinking it evicts overflow immediately. |
| `tapBehaviour` | `'none' \| 'dismiss'` | `'dismiss'` | Whether tapping a notification also dismisses it (after any tap handler runs). |
| `tapHandlerDefault` | `(notification) => void` | — | Called on tap when the notification has no `onTap` of its own. |

---

## Scoped managers, history and unread

`NotificationManager` is the default, app-wide instance. Every instance has its own queue, timers, renderer and options, so toasts can sit beside the component they concern:

```typescript
import { createNotificationManager, NotificationManager } from '../src/index.js';

const lister = NotificationManager.scope('lister-1', { renderer: myAnchoredRenderer }); // get-or-create by name
// or, unregistered: const lister = createNotificationManager({ renderer: myAnchoredRenderer });
lister.notify({ type: 'info', message: 'Moved 3 items' });
NotificationManager.releaseScope('lister-1'); // on unmount: dismiss, detach, forget
```

Each instance also keeps a bounded history (`historyLimit`, default 100; `0` disables):

| API | Description |
|---|---|
| `getHistory()` | Snapshot of `{ ...Notification, read, dismissedAt? }`, oldest first; includes toasts no longer visible |
| `unreadCount` | Entries not yet read — drive a bell indicator |
| `markRead(id)` / `markAllRead()` | Mark read. Tapping a toast also marks it read |
| `clearHistory()` | Drop history |
| `subscribe(listener)` | Called with the history on every change; returns an unsubscribe function |
| `destroy()` | Dismiss all, drop history/listeners, detach renderer |

Scoped instances with no `renderer` fall back to the default top-right pill renderer, which is viewport-anchored — give anchored scopes a custom renderer.

---

## Queueing model

- **`queue: false`** — a message is always shown alone, for the full `timeout`/`timeoutError`. A new `notify()` call immediately replaces whatever is showing.
- **`queue: true`** — up to `queueSize` messages are visible at once. When a new message arrives and the queue is already full, **the oldest message is evicted immediately** to make room — nothing waits in an unbounded backlog.
- Only the **front** message (the oldest, next to be dismissed) has a running timer. A message that arrived while others were already queued gets `1/queueSize` of the normal timeout once it becomes front; a message that was alone in the queue when it arrived gets the full timeout. This means a burst of messages cycles through quickly, while a single message gets the full, unhurried display time.
- `update()` only resets the timer if the updated notification is currently front (i.e. actually has a timer running).

---

## Pill renderer

The built-in renderer, `createPillRenderer(options)`, renders notifications as rounded pills fixed to a corner or edge of the viewport, using theme CSS variables for styling.

```typescript
import { createPillRenderer, NotificationManager } from '../src/index.js';

NotificationManager.configure({
  renderer: createPillRenderer({
    position: 'top-right',
    queueDisplay: 'list',
    safeArea: { top: 60 }, // e.g. clear a fixed header
  }),
});
```

| Option | Type | Default | Description |
|---|---|---|---|
| `position` | `'top-left' \| 'top-middle' \| 'top-right' \| 'bottom-left' \| 'bottom-middle' \| 'bottom-right'` | `'top-right'` | Which corner/edge pills anchor to, and the direction they slide in/out from. |
| `queueDisplay` | `'list' \| 'stack'` | `'list'` | How queued (non-front) messages are shown — see below. |
| `safeArea` | `{ top?, right?, bottom?, left? }` (px) | `{}` | Extra margin added on top of the default spacing, e.g. to avoid a fixed header/footer/notch. |
| `topLayer` | `boolean` | `true` | Show toasts in the browser's top layer so they sit above modal dialogs and popovers. See [Stacking with dialogs](#stacking-with-dialogs-and-popovers). |
| `zIndex` | `number` | — | Only used when `topLayer` is `false`: the `z-index` of the toast layer, for apps that manage stacking themselves. |

### Stacking with dialogs and popovers

A modal `<dialog>` (opened with `showModal()`) and its backdrop live in the browser's *top layer*, which no `z-index` can beat. So by default the pill renderer puts its container in the top layer too, using the [Popover API](https://developer.mozilla.org/docs/Web/API/Popover_API) (`popover="manual"`), and toasts appear above the backdrop.

- **Order follows time.** Top-layer elements stack in the order they were shown. Each time a *new* toast arrives the container is re-shown, so it ends up above a dialog opened after earlier toasts. An already-visible toast is not re-promoted if a dialog opens later; the next toast will be.
- **Modal dialogs make the page inert.** While a modal dialog is open, everything outside it, including toasts in the top layer, cannot be clicked or focused. Toasts are visible and still time out, but tap-to-dismiss only works once the dialog closes. If toasts must be clickable over a modal, open that dialog non-modally (`show()`), or render toasts inside the dialog.
- **Manual control.** Pass `topLayer: false` to opt out. Toasts then stack normally; give them a `zIndex` above your own layers if needed:

```typescript
createPillRenderer({ topLayer: false, zIndex: 1000 });
```

- **Older browsers** without the Popover API fall back to normal stacking automatically.

### `queueDisplay: 'list'`

Each message gets its own row. The oldest message sits nearest the anchor edge; newer messages extend away from it (for `top-*` positions, newest is lowest on screen; for `bottom-*`, newest is highest). When the front message is dismissed, the rest animate into the vacated slot.

### `queueDisplay: 'stack'`

Only the front message is fully shown. Queued messages peek out from behind it, offset by a few pixels and increasingly faded/desaturated, giving a visual hint that more are waiting. They aren't interactive (no tap, no pointer events) until promoted to front.

The offset direction follows the anchor position: corner positions (e.g. `top-left`) offset diagonally, away from both edges (`top-left` → down-right); `-middle` positions offset only vertically, away from the anchor edge (`bottom-middle` → straight up).

When the front message is dismissed, the next one animates into the front slot at full opacity.

---

## Custom renderers

Anything implementing `NotificationRenderer` can be passed to `configure({ renderer })`:

```typescript
export interface NotificationRenderer {
  attach: (hooks: NotificationRendererHooks) => void;
  detach?: () => void;
  setNotifications: (notifications: Notification[], queueSize: number) => void;
}
```

- `attach(hooks)` is called once when the renderer becomes active. Call `hooks.onTap(id)` whenever the user interacts with a shown notification — the manager decides what tapping means (per-notification `onTap`, `tapHandlerDefault`, `tapBehaviour`).
- `detach?()` is called if the renderer is swapped out at runtime, so it can tear down its DOM.
- `setNotifications(notifications, queueSize)` is called any time the visible set changes (new message, dismissal, eviction, reorder, content update). `notifications` is the manager's full, rank-ordered view — index `0` is the front/oldest message — and is never longer than `queueSize`, since the manager itself evicts overflow. A renderer just needs to reconcile this list against whatever it's currently showing (create new, update existing, remove missing) — see `pill-renderer.ts` for a full example.

`NotificationContent.onTap` is per-notification and takes the notification's `id`; `tapHandlerDefault` (manager-wide) takes the full `Notification`.
