# Комментарии

Комментарии привязаны к тексту и едут вместе с ним при правке.

`index.vue`

```vue
<template>
  <div class="flex w-full flex-col gap-3">
    <div class="flex justify-end">
      <NuiPopover placement="bottom-end" padding="sm">
        <template #trigger="{ attrs }">
          <NuiButton v-bind="attrs" variant="outline" tone="neutral" size="sm" icon="comment">
            Обсуждения
          </NuiButton>
        </template>
        <NuiEditorComments :comments="comments" />
      </NuiPopover>
    </div>
    <NuiEditor
      ref="editor"
      v-model="document"
      format="json"
      toolbar="bubble"
      aria-label="Описание товара"
      :plugins="plugins"
      :selection-actions="[comments.action.value]"
    >
      <template #overlay>
        <NuiEditorCommentPopover :comments="comments" :editor="api" />
      </template>
    </NuiEditor>
  </div>
</template>

<script setup lang="ts">
import { computed, shallowRef, useTemplateRef } from 'vue';
import {
  NuiEditorCommentPopover,
  NuiEditorComments,
  useEditorComments,
} from '@numior/kit/collaboration/vue';
import { contentSchema } from '@numior/kit/content';
import { fromHTML, toJSON, type DocJSON } from '@numior/kit/editor-core';
import { NuiEditor, type NuiEditorApi } from '@numior/kit/editor';
import { NuiButton, NuiPopover } from '@numior/kit';
import { brief } from './description';
import { team } from './team';
import { memoryComments } from './adapter';
import { threadsOf } from './threads';

const [anna] = team;

const source = fromHTML(contentSchema, brief);

const document = shallowRef<DocJSON>(toJSON(source));

const editor = useTemplateRef<{ editor: NuiEditorApi }>('editor');

const api = computed(() => editor.value?.editor);

const comments = useEditorComments({
  doc: 'oslo-chair',
  user: anna,
  adapter: memoryComments(threadsOf(source)),
  editor: () => api.value,
});

const plugins = [comments.plugin];
</script>
```

`adapter.ts`

```ts
import type { CommentThread, CommentsAdapter } from '@numior/kit/collaboration';

const newId = (): string => Math.random().toString(36).slice(2, 10);

const now = (): string => new Date().toISOString();

export const memoryComments = (initial: readonly CommentThread[]): CommentsAdapter => {
  let threads = initial;

  const changed = (
    id: string,
    change: (thread: CommentThread) => CommentThread,
  ): Promise<CommentThread> => {
    const thread = threads.find((item) => item.id === id);

    if (thread === undefined) {
      return Promise.reject(new Error('Обсуждение удалено'));
    }

    const next = change(thread);

    threads = threads.map((item) => (item.id === id ? next : item));
    return Promise.resolve(next);
  };

  return {
    list: () => Promise.resolve(threads),
    create: (_doc, comment) => {
      const thread = { ...comment, id: newId(), createdAt: now(), resolved: false, replies: [] };

      threads = [...threads, thread];
      return Promise.resolve(thread);
    },
    reply: (_doc, id, reply) =>
      changed(id, (thread) => ({
        ...thread,
        replies: [...thread.replies, { ...reply, id: newId(), createdAt: now() }],
      })),
    resolve: (_doc, id, resolved) => changed(id, (thread) => ({ ...thread, resolved })),
    remove: (_doc, id) => {
      threads = threads.filter((item) => item.id !== id);
      return Promise.resolve();
    },
    move: async (_doc, id, anchor) => {
      await changed(id, (thread) => ({ ...thread, anchor }));
    },
  };
};
```

`threads.ts`

```ts
import type { CommentThread } from '@numior/kit/collaboration';
import {
  AnchorRangeKind,
  ContentNodeKind,
  type AnchorJSON,
  type ContentNode,
  type Doc,
  type ElementNode,
} from '@numior/kit/editor-core';
import { team } from './team';

const [anna, , maria] = team;

const textOf = (node: ContentNode): string =>
  node.kind === ContentNodeKind.Text ? node.text : node.content.map(textOf).join('');

const isText = (node: ContentNode): boolean => node.kind === ContentNodeKind.Text;

const textBlocksOf = (node: ElementNode): readonly ElementNode[] =>
  node.content.flatMap((child) => {
    if (child.kind === ContentNodeKind.Text) {
      return [];
    }
    return child.content.some(isText) ? [child] : textBlocksOf(child);
  });

const anchorOf = (doc: Doc, phrase: string): AnchorJSON => {
  const block = textBlocksOf(doc.root).find((node) => textOf(node).includes(phrase));

  if (block === undefined) {
    throw new Error(`В описании нет текста «${phrase}»`);
  }

  const from = textOf(block).indexOf(phrase);

  return {
    kind: AnchorRangeKind.Text,
    fromId: block.id,
    fromOffset: from,
    toId: block.id,
    toOffset: from + phrase.length,
  };
};

export const threadsOf = (doc: Doc): readonly CommentThread[] => [
  {
    id: 'oak',
    anchor: anchorOf(doc, 'массива дуба'),
    author: maria,
    body: 'Покупатели спрашивают, не шпон ли это. Добавим фото среза?',
    createdAt: '2026-11-10T07:40:00.000Z',
    resolved: false,
    replies: [
      {
        id: 'oak-photo',
        author: anna,
        body: 'Попрошу фото у склада и добавлю к карточке.',
        createdAt: '2026-11-10T08:15:00.000Z',
      },
    ],
  },
  {
    id: 'load',
    anchor: anchorOf(doc, 'до 120 кг'),
    author: anna,
    body: 'В паспорте поставщика 110 кг, сверьте с образцом.',
    createdAt: '2026-11-11T11:05:00.000Z',
    resolved: false,
    replies: [],
  },
];
```

`description.ts`

```ts
export const brief = `
<h2>Кресло «Осло»</h2>
<p>Мягкое кресло на каркасе из <strong>массива дуба</strong>. Чехол снимается и стирается при 30&nbsp;°C.</p>
<ul>
  <li>Ширина 78 см, глубина 84 см, высота 92 см</li>
  <li>Высота сиденья 42 см</li>
  <li>Выдерживает до 120 кг</li>
</ul>
`;

export const description = `${brief}<div class="nui-content__callout nui-content__callout--tone-warning">
  <p>Не ставьте кресло вплотную к батарее: дуб рассыхается.</p>
</div>
<h3>Обивка</h3>
<table>
  <thead>
    <tr><th>Ткань</th><th>Цена</th><th>В наличии</th></tr>
  </thead>
  <tbody>
    <tr><td>Серый лён</td><td>18900</td><td>да</td></tr>
    <tr><td>Тёмный лён</td><td>19400</td><td>да</td></tr>
    <tr><td>Синий велюр</td><td>21500</td><td>нет</td></tr>
  </tbody>
</table>
<details>
  <summary>Уход за чехлом</summary>
  <p>Стирайте чехол отдельно от цветных вещей и сушите расправленным.</p>
</details>
`;
```

`team.ts`

```ts
export interface Employee {
  readonly id: string;
  readonly name: string;
  readonly role: string;
  readonly email: string;
}

export const team: readonly [Employee, Employee, Employee, Employee, Employee] = [
  { id: 'anna', name: 'Анна Титова', role: 'Менеджер заказов', email: 'anna@example.com' },
  { id: 'igor', name: 'Игорь Белов', role: 'Кладовщик', email: 'igor@example.com' },
  { id: 'maria', name: 'Мария Ким', role: 'Поддержка', email: 'maria@example.com' },
  { id: 'oleg', name: 'Олег Смирнов', role: 'Закупки', email: 'oleg@example.com' },
  { id: 'dina', name: 'Дина Ахметова', role: 'Маркетинг', email: 'dina@example.com' },
];
```

Выделите текст и нажмите кнопку комментария в панели у выделения.

## Храните комментарии

Сохраняйте обсуждения у себя и передайте редактору адаптер с методами `list`, `create`, `reply`,
`resolve` и `remove`:

```ts
import type { CommentsAdapter } from '@numior/kit/collaboration';

interface CommentsAdapter {
  list(doc: string, signal: AbortSignal): Promise<readonly CommentThread[]>;
  create(doc: string, comment: NewComment): Promise<CommentThread>;
  reply(doc: string, threadId: string, reply: NewReply): Promise<CommentThread>;
  resolve(doc: string, threadId: string, resolved: boolean): Promise<CommentThread>;
  remove(doc: string, threadId: string): Promise<void>;
  move?(doc: string, threadId: string, anchor: CommentAnchor): Promise<void>;
  subscribe?(doc: string, listener: (event: CommentEvent) => void): () => void;
}
```

```ts
import type { CommentThread } from '@numior/kit/collaboration';

interface CommentThread {
  readonly id: string;
  readonly anchor: CommentAnchor;
  readonly author: PresenceUser;
  readonly body: string;
  readonly createdAt: string;
  readonly resolved: boolean;
  readonly replies: readonly CommentReply[];
}
```

`create`, `reply` и `resolve` возвращают обсуждение целиком, каким его сохранил сервер. Привязку
`anchor` адаптер хранит как есть: в ней id блоков и смещения в тексте.

Добавьте `move`, и новое место отметки после правки переживёт перезагрузку страницы. Через
`subscribe` редактор узнаёт о новых и изменённых обсуждениях соавторов без перезагрузки.

## Подключите к редактору

Передайте адаптер в `useEditorComments`, плагин — в `plugins`, а кнопку комментария — в
`selectionActions`:

```vue
<template>
  <NuiEditor
    ref="editor"
    v-model="document"
    format="json"
    label="Описание товара"
    :plugins="[comments.plugin]"
    :selection-actions="[comments.action.value]"
  >
    <template #overlay>
      <NuiEditorCommentPopover :comments="comments" :editor="api" />
    </template>
  </NuiEditor>
  <NuiEditorComments :comments="comments" />
</template>

<script setup lang="ts">
import { computed, shallowRef, useTemplateRef } from 'vue';
import {
  NuiEditorCommentPopover,
  NuiEditorComments,
  useEditorComments,
} from '@numior/kit/collaboration/vue';
import type { DocJSON } from '@numior/kit/editor-core';
import { NuiEditor, type NuiEditorApi } from '@numior/kit/editor';

const document = shallowRef<DocJSON>();
const editor = useTemplateRef<{ editor: NuiEditorApi }>('editor');
const api = computed(() => editor.value?.editor);

const comments = useEditorComments({
  doc: 'oslo-chair',
  user: { id: 'anna', name: 'Анна Титова' },
  adapter: shopComments,
  editor: () => api.value,
});
</script>
```

Поповер в слоте `overlay` открывает форму нового комментария у выделения и обсуждение по клику на
отмеченный текст. `NuiEditorComments` выводит все обсуждения списком, например в боковой панели.

При совместной работе добавьте плагин к плагинам из `useCollabEditor`:
`[...plugins.value, comments.plugin]`.

```ts
import { useEditorComments } from '@numior/kit/collaboration/vue';

useEditorComments: (options: UseEditorCommentsOptions) => CollabComments
```

```ts
import type { UseEditorCommentsOptions } from '@numior/kit/collaboration/vue';

interface UseEditorCommentsOptions {
  readonly doc: string;
  readonly user: PresenceUser;
  readonly adapter: CommentsAdapter;
  readonly editor: () => NuiEditorApi | undefined;
}
```

```ts
import type { CollabComments } from '@numior/kit/collaboration/vue';

interface CollabComments {
  readonly plugin: Plugin;
  readonly user: PresenceUser;
  readonly threads: ComputedRef<readonly CommentThreadView[]>;
  readonly active: Readonly<ShallowRef<string | undefined>>;
  readonly opened: Readonly<ShallowRef<string | undefined>>;
  readonly drafting: Readonly<Ref<boolean>>;
  readonly failed: Readonly<Ref<boolean>>;
  readonly revision: Readonly<Ref<number>>;
  readonly action: ComputedRef<NuiEditorSelectionAction>;
  readonly spot: () => CommentSpot | undefined;
  readonly openAt: (pos: number) => void;
  readonly close: () => void;
  readonly cancel: () => void;
  readonly submit: (body: string) => Promise<boolean>;
  readonly reply: (id: string, body: string) => Promise<boolean>;
  readonly resolve: (id: string, resolved: boolean) => Promise<void>;
  readonly remove: (id: string) => Promise<void>;
  readonly activate: (id: string) => void;
}
```

## Поведение

- Отметка едет вместе с текстом при своих правках и правках соавторов.
- Если отмеченный текст удалили, обсуждение остаётся в списке с пометкой «Текст удалён».
- Решённое обсуждение снимает отметку и уходит в конец списка. «Открыть снова» возвращает отметку на
  сохранённое место.
- Удалить обсуждение может только его автор.
- Документ только для чтения тоже можно комментировать: в панели у выделения останется одна кнопка
  комментария.

## API

### NuiEditorComments

```ts
import { NuiEditorComments } from '@numior/kit/collaboration/vue';
```

#### Свойства

| Имя | Тип | По умолчанию | Описание |
| --- | --- | --- | --- |
| `comments` (обязательно) | `CollabComments` |  | Комментарии документа из `useEditorComments`. |
| `labels` | `Partial<Omit<NuiCollabMessages, "present">>` |  | Свои тексты вместо встроенных из `collabMessages`, по одному ключу. |

#### Тексты

| Ключ | Текст |
| --- | --- |
| `add` | Добавить комментарий |
| `alternativeEmpty` | Пусто |
| `alternativeFalse` | Нет |
| `alternativeHide` | Скрыть |
| `alternativeRestore` | Вернуть |
| `alternativeShow` | Показать в документе |
| `alternativeTrue` | Да |
| `alternativeUnknown` | Другой участник |
| `alternatives` | Перезаписанные значения |
| `cancel` | Отмена |
| `closeVersion` | Закрыть |
| `comments` | Комментарии |
| `empty` | Пока нет комментариев |
| `failed` | Не удалось сохранить комментарий |
| `failureDiverged` | Ваша копия новее документа на сервере. |
| `failureDocument` | Правка другого участника не подошла к вашей копии. |
| `failureInvalid` | Сервер не принял одну из ваших правок. |
| `failureProtocol` | Сервер прислал ответ, который страница не смогла прочитать. |
| `failureReadOnly` | Документ открыт только для чтения, пока вы не откроете его заново. |
| `failureRejoin` | Открыть заново |
| `failureSchema` | Страница работает на версии приложения старее той, что нужна документу. Обновите страницу. |
| `failureTitle` | Правки больше не отправляются |
| `failureUnsent` | ({ count }) => `Не отправлено правок: ${count}. Скопируйте нужное, прежде чем открыть документ заново.` |
| `history` | История версий |
| `historyFailed` | История версий недоступна |
| `lost` | Текст удалён |
| `noChanges` | В этой версии нет изменений |
| `noVersions` | Сохранённых версий пока нет |
| `placeholder` | Напишите комментарий |
| `present` | Сейчас в документе |
| `remove` | Удалить |
| `reopen` | Открыть снова |
| `reply` | Ответить |
| `replyPlaceholder` | Напишите ответ |
| `reportDamaged` | Копию на этом устройстве не удалось прочитать |
| `reportStep` | ({ subject }) => `${subject}: сохранённые правки нельзя перевести на новую версию` |
| `reportTitle` | Документ открыт только для чтения |
| `reportUnsent` | ({ count }) => `Неотправленные правки сохранены на этом устройстве: ${count}` |
| `reportVersion` | ({ subject, stored, current }) => `${subject}: у сохранённой копии версия ${stored}, приложение ждёт ${current}` |
| `resolve` | Решить |
| `resolved` | Решён |
| `restore` | Восстановить эту версию |
| `saveVersion` | Сохранить версию |
| `send` | Отправить |
| `show` | Показать в тексте |
| `showChanges` | Показать изменения |

### NuiEditorCommentPopover

```ts
import { NuiEditorCommentPopover } from '@numior/kit/collaboration/vue';
```

#### Свойства

| Имя | Тип | По умолчанию | Описание |
| --- | --- | --- | --- |
| `comments` (обязательно) | `CollabComments` |  | Комментарии документа из `useEditorComments`. |
| `editor` (обязательно) | `NuiEditorApi` |  | API редактора: поповер встаёт у выделения или у отмеченного текста. |
| `labels` | `Partial<Omit<NuiCollabMessages, "present">>` |  | Свои тексты вместо встроенных из `collabMessages`, по одному ключу. |

#### Тексты

| Ключ | Текст |
| --- | --- |
| `add` | Добавить комментарий |
| `alternativeEmpty` | Пусто |
| `alternativeFalse` | Нет |
| `alternativeHide` | Скрыть |
| `alternativeRestore` | Вернуть |
| `alternativeShow` | Показать в документе |
| `alternativeTrue` | Да |
| `alternativeUnknown` | Другой участник |
| `alternatives` | Перезаписанные значения |
| `cancel` | Отмена |
| `closeVersion` | Закрыть |
| `comments` | Комментарии |
| `empty` | Пока нет комментариев |
| `failed` | Не удалось сохранить комментарий |
| `failureDiverged` | Ваша копия новее документа на сервере. |
| `failureDocument` | Правка другого участника не подошла к вашей копии. |
| `failureInvalid` | Сервер не принял одну из ваших правок. |
| `failureProtocol` | Сервер прислал ответ, который страница не смогла прочитать. |
| `failureReadOnly` | Документ открыт только для чтения, пока вы не откроете его заново. |
| `failureRejoin` | Открыть заново |
| `failureSchema` | Страница работает на версии приложения старее той, что нужна документу. Обновите страницу. |
| `failureTitle` | Правки больше не отправляются |
| `failureUnsent` | ({ count }) => `Не отправлено правок: ${count}. Скопируйте нужное, прежде чем открыть документ заново.` |
| `history` | История версий |
| `historyFailed` | История версий недоступна |
| `lost` | Текст удалён |
| `noChanges` | В этой версии нет изменений |
| `noVersions` | Сохранённых версий пока нет |
| `placeholder` | Напишите комментарий |
| `present` | Сейчас в документе |
| `remove` | Удалить |
| `reopen` | Открыть снова |
| `reply` | Ответить |
| `replyPlaceholder` | Напишите ответ |
| `reportDamaged` | Копию на этом устройстве не удалось прочитать |
| `reportStep` | ({ subject }) => `${subject}: сохранённые правки нельзя перевести на новую версию` |
| `reportTitle` | Документ открыт только для чтения |
| `reportUnsent` | ({ count }) => `Неотправленные правки сохранены на этом устройстве: ${count}` |
| `reportVersion` | ({ subject, stored, current }) => `${subject}: у сохранённой копии версия ${stored}, приложение ждёт ${current}` |
| `resolve` | Решить |
| `resolved` | Решён |
| `restore` | Восстановить эту версию |
| `saveVersion` | Сохранить версию |
| `send` | Отправить |
| `show` | Показать в тексте |
| `showChanges` | Показать изменения |
