# Commentaires

- Human documentation: [https://docs.univer.ai/fr-FR/guides/sheets/features/comments](https://docs.univer.ai/fr-FR/guides/sheets/features/comments)

- Agent Markdown: [https://docs.univer.ai/fr-FR/guides/sheets/features/comments.md](https://docs.univer.ai/fr-FR/guides/sheets/features/comments.md)

- Requested language: `fr-FR`

- Content language: `fr-FR`

- Documentation version: `1.2.0`

- Source: [sheets/features/comments.fr-FR.mdx](https://github.com/dream-num/documentation/blob/dev/content/guides/sheets/features/comments.fr-FR.mdx)

---

#### Package metadata

```json
{
  "mobile": true,
  "preset": [
    {
      "client": "@univerjs/preset-sheets-thread-comment",
      "locale": "@univerjs/preset-sheets-thread-comment/locales/en-US",
      "style": "@univerjs/preset-sheets-thread-comment/lib/index.css"
    }
  ],
  "plugins": [
    {
      "client": "@univerjs/thread-comment"
    },
    {
      "client": "@univerjs/thread-comment-ui",
      "locale": "@univerjs/thread-comment-ui/locale/en-US",
      "style": "@univerjs/thread-comment-ui/lib/index.css"
    },
    {
      "client": "@univerjs/sheets-thread-comment",
      "facade": "@univerjs/sheets-thread-comment/facade"
    },
    {
      "client": "@univerjs/sheets-thread-comment-ui",
      "locale": "@univerjs/sheets-thread-comment-ui/locale/en-US",
      "style": "@univerjs/sheets-thread-comment-ui/lib/index.css"
    }
  ],
  "server": "optional"
}
```

Les commentaires permettent d’ajouter des remarques et des réponses dans les documents, ce qui facilite la communication et la collaboration entre les membres d’une équipe.

## Mode plugin

### Installation

#### npm

```bash
npm install @univerjs/thread-comment @univerjs/thread-comment-ui @univerjs/sheets-thread-comment @univerjs/sheets-thread-comment-ui
```

#### pnpm

```bash
pnpm add @univerjs/thread-comment @univerjs/thread-comment-ui @univerjs/sheets-thread-comment @univerjs/sheets-thread-comment-ui
```

#### yarn

```bash
yarn add @univerjs/thread-comment @univerjs/thread-comment-ui @univerjs/sheets-thread-comment @univerjs/sheets-thread-comment-ui
```

#### bun

```bash
bun add @univerjs/thread-comment @univerjs/thread-comment-ui @univerjs/sheets-thread-comment @univerjs/sheets-thread-comment-ui
```

### Utilisation

```typescript
import { LocaleType, mergeLocales, Univer } from '@univerjs/core'
import { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment' // [!code ++]
import { UniverSheetsThreadCommentUIPlugin } from '@univerjs/sheets-thread-comment-ui' // [!code ++]
import SheetsThreadCommentUIEnUS from '@univerjs/sheets-thread-comment-ui/locale/en-US' // [!code ++]
import { UniverThreadCommentPlugin } from '@univerjs/thread-comment' // [!code ++]
import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui' // [!code ++]
import ThreadCommentUIEnUS from '@univerjs/thread-comment-ui/locale/en-US' // [!code ++]

import '@univerjs/sheets-thread-comment-ui/lib/index.css'
import '@univerjs/thread-comment-ui/lib/index.css' // [!code ++]

import '@univerjs/sheets-thread-comment/facade' // [!code ++]

const univer = new Univer({
  locale: LocaleType.EN_US,
  locales: {
    [LocaleType.EN_US]: mergeLocales(
      ThreadCommentUIEnUS, // [!code ++]
      SheetsThreadCommentUIEnUS, // [!code ++]
    ),
  },
})

univer.registerPlugin(UniverThreadCommentPlugin) // [!code ++]
univer.registerPlugin(UniverThreadCommentUIPlugin) // [!code ++]
univer.registerPlugin(UniverSheetsThreadCommentPlugin) // [!code ++]
univer.registerPlugin(UniverSheetsThreadCommentUIPlugin) // [!code ++]
```

#### Utilisation avec la fonctionnalité de collaboration

Si vous utilisez la fonctionnalité de [Collaboration](https://docs.univer.ai/fr-FR/guides/sheets/features/collaboration.md), configurez-la comme suit :

#### npm

```bash
npm install @univerjs-pro/thread-comment-datasource
```

#### pnpm

```bash
pnpm add @univerjs-pro/thread-comment-datasource
```

#### yarn

```bash
yarn add @univerjs-pro/thread-comment-datasource
```

#### bun

```bash
bun add @univerjs-pro/thread-comment-datasource
```

```typescript
import { UniverThreadCommentDataSourcePlugin } from '@univerjs-pro/thread-comment-datasource' // [!code ++]

univer.registerPlugin(UniverThreadCommentDataSourcePlugin) // [!code ++]
```

## Prise en charge mobile

Configurez d’abord l’[éditeur mobile](https://docs.univer.ai/fr-FR/guides/sheets/getting-started/installation.md#mobile-support). Dans l’initialisation en mode plugin de cette page, remplacez les inscriptions de bureau ci-dessous par les exports mobiles des mêmes paquets **avant d’ouvrir un document**. Conservez modèles, styles, traductions et imports Facade ; n’enregistrez pas les deux variantes.

| Paquet                               | Inscription de bureau               | Inscription mobile                        |
| ------------------------------------ | ----------------------------------- | ----------------------------------------- |
| `@univerjs/sheets-thread-comment-ui` | `UniverSheetsThreadCommentUIPlugin` | `UniverSheetsThreadCommentMobileUIPlugin` |
| `@univerjs/thread-comment-ui`        | `UniverThreadCommentUIPlugin`       | `UniverThreadCommentMobileUIPlugin`       |

## Mode preset

### Installation

#### npm

```bash
npm install @univerjs/preset-sheets-thread-comment
```

#### pnpm

```bash
pnpm add @univerjs/preset-sheets-thread-comment
```

#### yarn

```bash
yarn add @univerjs/preset-sheets-thread-comment
```

#### bun

```bash
bun add @univerjs/preset-sheets-thread-comment
```

### Utilisation

```typescript
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'
import { UniverSheetsThreadCommentPreset } from '@univerjs/preset-sheets-thread-comment' // [!code ++]
import UniverPresetSheetsThreadCommentEnUS from '@univerjs/preset-sheets-thread-comment/locales/en-US' // [!code ++]
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'

import '@univerjs/preset-sheets-core/lib/index.css'
import '@univerjs/preset-sheets-thread-comment/lib/index.css' // [!code ++]

const { univerAPI } = createUniver({
  locale: LocaleType.EN_US,
  locales: {
    [LocaleType.EN_US]: mergeLocales(
      UniverPresetSheetsCoreEnUS,
      UniverPresetSheetsThreadCommentEnUS, // [!code ++]
    ),
  },
  presets: [
    UniverSheetsCorePreset(),
    UniverSheetsThreadCommentPreset(), // [!code ++]
  ],
})
```

## API Facade

Vous trouverez les définitions de types complètes de l’API Facade dans la [FacadeAPI](https://docs.univer.ai/fr-FR/reference/facade/thread-comment.md).

### Importation

> [!INFO: Remarque sur le mode plugin]
> Seul le mode plugin nécessite d’importer manuellement le package Facade. Le mode preset inclut déjà le package Facade correspondant ; aucune importation supplémentaire n’est donc nécessaire.

```typescript
import '@univerjs/sheets-thread-comment/facade'
```

### Créer un commentaire de cellule

Vous pouvez créer un générateur de commentaire avec `univerAPI.newTheadComment()`, qui renvoie une instance de `FTheadCommentBuilder`. Vous pouvez ensuite chaîner les méthodes afin de définir les différentes propriétés du commentaire.

Voici quelques méthodes membres de [`FTheadCommentBuilder`](https://docs.univer.ai/fr-FR/reference/facade/thead-comment-builder.md) :

| Méthode     | Description                                      |
| ----------- | ------------------------------------------------ |
| setContent  | Définit le contenu du commentaire                |
| setPersonId | Définit l’identifiant de l’auteur du commentaire |
| setDateTime | Définit la date et l’heure du commentaire        |
| setId       | Définit l’identifiant du commentaire             |
| setThreadId | Définit l’identifiant du fil de discussion       |

```typescript
// Create a new comment
const richText = univerAPI.newRichText().insertText('hello univer')
const commentBuilder = univerAPI.newTheadComment()
  .setContent(richText)

console.log(commentBuilder.content.toPlainText())

// Add the comment to cell A1
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const cell = fWorksheet.getRange('A1')
const result = await cell.addCommentAsync(commentBuilder)
```

### Obtenir les commentaires des cellules

Vous pouvez récupérer les commentaires à l’aide des méthodes suivantes, qui renvoient une instance de `FThreadComment`. Vous pouvez ensuite effectuer des opérations telles que la mise à jour, la suppression ou la résolution du commentaire.

* `FWorkbook.getComments()` : obtient tous les commentaires du classeur
* `FfWorksheet.getComments()` : obtient tous les commentaires de la feuille de calcul
* `FRange.getComment()` : obtient le commentaire de la cellule située en haut à gauche de la plage
* `FRange.getComments()` : obtient tous les commentaires de la plage

Voici quelques méthodes membres de [`FThreadComment`](https://docs.univer.ai/fr-FR/reference/facade/thread-comment.md) :

| Méthode        | Description                                         |
| -------------- | --------------------------------------------------- |
| getIsRoot      | Indique si le commentaire est un commentaire racine |
| getCommentData | Obtient les données du commentaire                  |
| getReplies     | Obtient la liste des réponses au commentaire        |
| getRange       | Obtient la plage du commentaire                     |
| getRichText    | Obtient le contenu en texte enrichi du commentaire  |
| deleteAsync    | Supprime le commentaire et ses réponses             |
| updateAsync    | Met à jour le contenu du commentaire                |
| resolveAsync   | Marque le commentaire comme résolu                  |
| replyAsync     | Répond au commentaire                               |

```typescript
// Get all comments in the workbook
const fWorkbook = univerAPI.getActiveWorkbook()
fWorkbook.getComments()

// Get all comments in the active worksheet
const fWorksheet = fWorkbook.getActiveSheet()
fWorksheet.getComments()

const fRange = fWorksheet.getRange('A1:B2')
// Get the comment of cell A1
fRange.getComment()

// Get all comments in the range A1:B2
fRange.getComments()
```

### Effacer les commentaires des cellules

* `FWorkbook.clearComments()` : efface tous les commentaires du classeur
* `FWorksheet.clearComments()` : efface tous les commentaires de la feuille de calcul
* `FRange.clearCommentAsync()` : efface le commentaire de la cellule située en haut à gauche de la plage
* `FRange.clearCommentsAsync()` : efface tous les commentaires de la plage

```typescript
// Clear all comments in the workbook
const fWorkbook = univerAPI.getActiveWorkbook()
await fWorkbook.clearComments()

// Clear all comments in the active worksheet
const fWorksheet = fWorkbook.getActiveSheet()
await fWorksheet.clearComments()

const fRange = fWorksheet.getRange('A1:B2')

// Clear the comment of cell A1
await fRange.clearCommentAsync()

// Clear all comments in the range A1:B2
await fRange.clearCommentsAsync()
```

### Obtenir la liste des réponses à un commentaire

```typescript
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

// Get all comments in the worksheet
const comments = fWorksheet.getComments()
comments.forEach((comment) => {
  // If the comment is a root comment, get its replies
  if (comment.getIsRoot()) {
    const replies = comment.getReplies()
    replies.forEach((reply) => {
      console.log(reply.getCommentData())
    })
  }
})
```

### Mettre à jour, supprimer, résoudre des commentaires ou y répondre

```typescript
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

// Create a new comment and add it to cell A1
const richText = univerAPI.newRichText().insertText('hello univer')
const commentBuilder = univerAPI.newTheadComment()
  .setContent(richText)
  .setId('mock-comment-id')
const cell = fWorksheet.getRange('A1')
await cell.addCommentAsync(commentBuilder)

// Update the comment and reply after 3 seconds
setTimeout(async () => {
  // Get the comment by ID and update its content
  const comment = fWorksheet.getCommentById('mock-comment-id')
  const newRichText = univerAPI.newRichText().insertText('Hello Univer AI')
  await comment.updateAsync(newRichText)

  // Create a new reply comment and set its content
  const replyText = univerAPI.newRichText().insertText('Hello Univer AI! GO! GO! GO!')
  const reply = univerAPI.newTheadComment().setContent(replyText)
  await comment.replyAsync(reply)
}, 3000)

// Resolve the comment and delete it after 6 seconds
setTimeout(async () => {
  const comment = fWorksheet.getCommentById('mock-comment-id')
  await comment.resolveAsync()
  await comment.deleteAsync()
}, 6000)
```

### Écouteurs d’événements

Vous trouverez les définitions de types complètes des événements dans [Events](https://docs.univer.ai/fr-FR/reference/facade/events.md).

Le module de commentaires fournit une série d’événements permettant de détecter l’ajout, la mise à jour, la suppression et les changements d’état de résolution des commentaires. Tous ces événements peuvent être écoutés avec `univerAPI.addEvent()`.

#### Événements d’ajout de commentaire

`univerAPI.Event.CommentAdded` : déclenché après l’ajout d’un commentaire

```typescript
const disposable = univerAPI.addEvent(univerAPI.Event.CommentAdded, (params) => {
  const { comment, workbook, worksheet, row, col } = params
})

// Remove the event listener, use `disposable.dispose()`
```

`univerAPI.Event.BeforeCommentAdd` : déclenché avant l’ajout d’un commentaire

```typescript
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeCommentAdd, (params) => {
  const { comment, workbook, worksheet, row, col } = params

  // Cancel the comment addition operation
  params.cancel = true
})

// Remove the event listener, use `disposable.dispose()`
```

#### Événements de mise à jour de commentaire

`univerAPI.Event.CommentUpdated` : déclenché après la mise à jour d’un commentaire

```typescript
const disposable = univerAPI.addEvent(univerAPI.Event.CommentUpdated, (params) => {
  const { comment, workbook, worksheet, row, col } = params
})

// Remove the event listener, use `disposable.dispose()`
```

`univerAPI.Event.BeforeCommentUpdate` : déclenché avant la mise à jour d’un commentaire

```typescript
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeCommentUpdate, (params) => {
  const { comment, workbook, worksheet, row, col, newContent } = params

  // Cancel the comment update operation
  params.cancel = true
})

// Remove the event listener, use `disposable.dispose()`
```

#### Événements de suppression de commentaire

`univerAPI.Event.CommentDeleted` : déclenché après la suppression d’un commentaire

```typescript
const disposable = univerAPI.addEvent(univerAPI.Event.CommentDeleted, (params) => {
  const { commentId, workbook, worksheet } = params
})

// Remove the event listener, use `disposable.dispose()`
```

`univerAPI.Event.BeforeCommentDelete` : déclenché avant la suppression d’un commentaire

```typescript
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeCommentDelete, (params) => {
  const { comment, workbook, worksheet, row, col } = params

  // Cancel the comment deletion operation
  params.cancel = true
})

// Remove the event listener, use `disposable.dispose()`
```

#### Événements de changement de l’état de résolution

`univerAPI.Event.CommentResolved` : déclenché après la modification de l’état de résolution d’un commentaire

```typescript
const disposable = univerAPI.addEvent(univerAPI.Event.CommentResolved, (params) => {
  const { comment, row, col, resolved, workbook, worksheet } = params
})

// Remove the event listener, use `disposable.dispose()`
```

`univerAPI.Event.BeforeCommentResolve` : déclenché avant la modification de l’état de résolution d’un commentaire

```typescript
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeCommentResolve, (params) => {
  const { comment, row, col, resolved, workbook, worksheet } = params

  // Cancel the comment resolution operation
  params.cancel = true
})

// Remove the event listener, use `disposable.dispose()`
```

Tous les événements contiennent les paramètres communs suivants :

* `workbook` : instance actuelle du classeur
* `worksheet` : instance actuelle de la feuille de calcul
* `row` : indice de ligne du commentaire
* `col` : indice de colonne du commentaire
* `comment` : objet commentaire (seul `commentId` est inclus dans les événements de suppression)

Paramètres particuliers :

* L’événement `BeforeCommentUpdate` inclut `newContent` : nouveau contenu du commentaire (type RichTextValue)
* Les événements `CommentResolved` et `BeforeCommentResolve` incluent `resolved` : état de résolution du commentaire

Toutes les fonctions de rappel des événements préfixés par `Before` peuvent renvoyer `params.cancel = true` afin d’empêcher l’opération correspondante.

## Opérations communes

Importez la Facade commune et celle du produit. Les méthodes du produit créent les ancres stables ; l’API commune gère réponses, mises à jour, résolution et suppression. `getComments()` lit l’état local. `listCommentsAsync()` synchronise les fils déjà connus via la source configurée ; cette méthode ne découvre pas tous les fils du serveur.

```ts
import '@univerjs/thread-comment/facade'

const [thread] = univerAPI.getComments({ resolved: false })
if (thread) {
  await univerAPI.replyCommentAsync({
    unitId: thread.unitId,
    subUnitId: thread.subUnitId,
    threadId: thread.threadId,
    content: 'Reviewed.',
  })
}
```

## Discussions partagées

Intégrez Comment Service et Endpoint avec le [Server SDK](https://docs.univer.ai/fr-FR/server/collaboration/extensions.md), puis enregistrez `UniverThreadCommentDataSourcePlugin` de `@univerjs-pro/thread-comment-datasource` après la collaboration et la licence. La source fournie utilise `/universer-api/comment/unit/{unitId}/...` et `/universer-api/user/list` : exposez ces routes dans l’application. Le serveur doit autoriser la lecture et l’écriture des commentaires indépendamment de la modification du document.
