# `<llumi-review>`

Review wrapper for commenting on light-DOM content. Wrap any content in
`<llumi-review>`; mark commentable elements with `data-review-id`. In default
mode, **any text and any block is commentable** — commenters click an element to
leave an element-level comment, or select text to leave a selection-level comment
anchored to the chosen words. Set the `review-only` attribute to restrict
commenting to marked elements only. React: `Review` in `review.react.tsx`.

## What it is

A `<llumi-review>` element wraps arbitrary light-DOM content and drives an
XState-driven annotation flow: a floating review bar (toggle/comment-count/
submit), floating comment dialogs anchored to the edited element or selection,
and CSS Custom Highlight API painting for commented/edited/hovered ranges.

- **Element comments** — click any `[data-review-id]` element (or, in default
  mode, any block) to comment on it.
- **Selection comments** — select text inside the host; the comment dialog
  anchors beside the selected range. In default mode any text is selectable;
  in `review-only` mode, only text inside `[data-review-id]` elements.
- **Overall comment** — a free-form note covering the whole document, opened from
  the review bar.
- **Persistence** — set the `persist` attribute to a localStorage key to keep
  the draft across reloads.

## Usage

> **Requires the base theme.** Load `@llumi/ui/base.css` (or
> `base.css`) on the page for the document-level styles the component adopts.

```html
<!-- 1. Register the element (auto side-effect) -->
<script type="module">
  import "@llumi/ui/review.mjs";
</script>

<!-- 2. Wrap content. Mark the parts you want a stable targetId for. -->
<llumi-review default-mode="annotating" bar-position="bottom-center">
  <h1 data-review-id="title">Project Proposal</h1>
  <p data-review-id="intro">
    Select a sentence in this paragraph to comment on it, or click the heading.
  </p>
  <div data-review-id="metric-1">
    <strong>42</strong> open issues
  </div>
</llumi-review>
```

Or with a named import:

```js
import { LlumiReview } from "@llumi/ui/review.mjs";
```

## Marking up commentable content

### Default mode (any text + any block is commentable)

Without `review-only`, the host is fully commentable:

- **Element comments** — clicking any block-level element opens a comment on it.
  The `targetId` is the nearest `[data-review-id]` ancestor's value, or a
  synthetic `__llumi_review_host__` id when the block is un-marked (host-rooted restore).
- **Selection comments** — selecting any text opens a selection-level comment
  anchored to the chosen range. The `targetId` resolves to the nearest
  `[data-review-id]` ancestor, or `__llumi_review_host__` for un-marked content.

Mark elements with `data-review-id` when you want a **stable, author-defined
target id** — e.g. for pre-seeded comments, cross-reload restore, or to group
selections under a known id. Un-marked content is still commentable; its comments
are rooted at the host.

### `review-only` mode (marked elements only)

Set the `review-only` attribute to restrict commenting to `[data-review-id]`
elements and `customTargets` only. Un-marked content is ignored — selections and
clicks on it do not open comments. Activating the review also flashes an outline
around every marked target.

```html
<llumi-review review-only default-mode="annotating">
  <h1 data-review-id="title">Commentable heading</h1>
  <p>This paragraph is NOT commentable in review-only mode.</p>
  <p data-review-id="marked">This one is.</p>
</llumi-review>
```

### Attribute reference

| Attribute | Applies to | Meaning |
|-----------|-----------|---------|
| `data-review-id` | any element | The element is the **path root** for comments. Element clicks resolve to it; text selections inside it are anchored to it. The value is the `targetId`. Sole marker — there is no separate `data-review-selectable` attribute. |

`targetId` values are arbitrary strings; the component does not generate them
for you.

## Attributes and properties

| Name | Attribute | Type | Default | Notes |
|------|-----------|------|---------|-------|
| `defaultMode` | `default-mode` | `"idle" \| "annotating"` | `"idle"` | Whether the component starts in annotation mode. Set `default-mode="annotating"` to enter review mode immediately on connect. |
| `reviewOnly` | `review-only` | `boolean` | `false` | When set, only `[data-review-id]` elements and `customTargets` are commentable. Un-marked content is ignored. |
| `barPosition` | `bar-position` | `ReviewBarPosition` | `"bottom-center"` | Position of the floating review bar. One of: `top-left`, `top-center`, `top-right`, `bottom-left`, `bottom-center`, `bottom-right`. |
| `shortcut` | `shortcut` | `string` | `"$mod+Shift+M"` | Keyboard shortcut (tinykeys syntax) to toggle annotation mode. `$mod` is `Cmd` on macOS, `Ctrl` elsewhere. |
| `persist` | `persist` | `string` | — (off) | When set to a non-empty value, the review draft is persisted to `localStorage` under that key and restored on load. Read once on connect. |
| `initialData` | — (property) | `ReviewResult` | `undefined` | Pre-loaded review state (existing comments). No HTML attribute. Set before connect. |
| `customTargets` | — (property) | `CustomTarget[]` | `undefined` | Additional non-DOM comment targets (e.g. BPMN elements). No HTML attribute. |

## Events

All events bubble and are composed (they cross shadow boundaries).

### `llumi-review-change`

Fires on every edit — a comment added, edited, or deleted, or the overall
comment changed. `detail` is a `ReviewResult`:

```ts
element.addEventListener("llumi-review-change", (e: CustomEvent<ReviewResult>) => {
  console.log("current review:", e.detail);
});
```

### `llumi-review-submit`

Fires when the user clicks Submit / Approve on the review bar. `detail` is
`{ result, clearPersisted }`:

```ts
element.addEventListener(
  "llumi-review-submit",
  (e: CustomEvent<ReviewSubmitDetail>) => {
    const { result, clearPersisted } = e.detail;
    // Persist `result` to your server, then:
    clearPersisted(); // discard the localStorage draft for this element
  },
);
```

Call `clearPersisted()` only after a confirmed server save; it is a no-op when
persistence is off. You can also call `element.clearPersisted()` directly.

### `llumi-review-persist-error`

Fires when persisting the draft to `localStorage` fails (e.g. quota exceeded,
serialization error, or storage disabled). `detail` is
`{ message: string; cause: Error }`:

```ts
element.addEventListener(
  "llumi-review-persist-error",
  (e: CustomEvent<{ message: string; cause: Error }>) => {
    console.warn("review draft not saved:", e.detail.message);
    // Optionally surface to the user, fall back to in-memory only, etc.
  },
);
```

The review continues to work in-memory after a persist error; only the
localStorage write failed.

## Data shapes

```ts
interface PathStep {
  tag: string;   // tagName of the element (e.g. "P", "LI")
  index: number; // nth child of this tag among its parent's element children
}

interface DomPosition {
  rootId?: string;     // data-review-id of the root ancestor; absent → host-rooted
  rootIndex?: number;  // disambiguator for duplicate data-review-id values
  path: PathStep[];    // path from root to the text-bearing element ([] for element-comments)
  textOffset: number;  // char offset within the resolved element's text
}

interface SelectionRange {
  /** Schema version. Absent = v1 (legacy, auto-migrated on load). */
  version: 2;
  /** Primary restore path — DOM-position-independent anchor. */
  domAnchor: { start: DomPosition; end: DomPosition };
  /** Text fallback layer — the original selected text. */
  selectedText: string;
  /** Fallback disambiguator — which occurrence (0-indexed) in the target's text. */
  matchIndex: number;
  /** Locality context for the text fallback (~100 chars each side, capped to 200 total). */
  context: { before: string; after: string };
}

interface ReviewComment {
  commentId: string;
  targetId: string;          // matches a data-review-id value, or "__llumi_review_host__" for un-marked content
  content: string;
  createdAt: string;         // ISO timestamp
  selection?: SelectionRange; // present for selection-level comments
}

type ReviewResult =
  | { status: "approved" }
  | { status: "commented"; comments: ReviewComment[]; overallComment?: string };

interface ReviewSubmitDetail {
  result: ReviewResult;
  clearPersisted: () => void;
}
```

### Re-anchoring

On load, a selection comment is re-anchored from its `domAnchor`, or, if the
DOM changed, by searching `selectedText` near its `context`. A comment that can
no longer be found stays in the data but is not painted.

### Legacy v1 ranges

Comments persisted with the v1 schema (`startOffset`/`endOffset` instead of
`domAnchor`) are automatically migrated to v2 on load by the migration engine.
No action is required from the host application.

## Dependencies

`lit`, `xstate`, `@floating-ui/dom`, `tinykeys`.

```js
import "@llumi/ui/review.mjs"; // npm / esm.sh
```

## React

```tsx
import { Review } from "./review.react";

<Review
  initialData={saved}
  persist="review-draft"
  reviewOnly
  onChange={(result) => setDraft(result)}
  onSubmit={async ({ result, clearPersisted }) => {
    await save(result);
    clearPersisted();
  }}
>
  <article data-review-id="intro">…</article>
</Review>
```

Children are the reviewed content. Props: `initialData`, `customTargets`,
`defaultMode`, `reviewOnly`, `barPosition`, `shortcut`, `persist` (as above;
`initialData` and `persist` are read once, on mount), `onChange(result)`,
`onSubmit({ result, clearPersisted })`, `onPersistError({ message, cause })`,
`ref` (the `LlumiReview` element), `className` and `style`.
