@kendew-agency/react-feedback-layer 0.3.2 → 0.4.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,13 +1,14 @@
1
1
  # @kendew-agency/react-feedback-layer
2
2
 
3
- A drop-in React feedback layer for collecting contextual user feedback through interactive comments and annotations. Perfect for design review tools, bug reporting systems, and collaborative annotation platforms.
3
+ A drop-in React feedback layer for collecting contextual user feedback through interactive comments and annotations. Perfect for design review tools, bug reporting systems, and collaborative annotation platforms.
4
4
 
5
- Have a look at the [changelog](#changelog) when updating the package.
5
+ Have a look at the [changelog](#changelog) and the [migration guide](#migrating-from-03x) when updating the package.
6
6
 
7
7
  ## Features
8
8
 
9
9
  - 🎯 **Contextual Feedback** - Click or drag to create comments anywhere on your UI
10
- - 💬 **Comment Lifecycle** - Draft → Published → Resolving → Resolved states
10
+ - 🗂️ **Feedback Sessions** - Group comments in a session that moves from draft to confirmed, resolving and resolved
11
+ - 💬 **Comment Lifecycle** - Draft → Published → Resolved, with reopen support
11
12
  - 👥 **User Attribution** - Track who created each comment with timestamps
12
13
  - 🎨 **Fully Customizable** - Headless UI with complete styling control
13
14
  - 📦 **TypeScript First** - Full type definitions included
@@ -32,60 +33,113 @@ npm install react react-dom
32
33
 
33
34
  ## Quick Start
34
35
 
36
+ `CommentContextProvider` must be rendered inside a `FeedbackSessionProvider`. The session provider owns the session and its callbacks. The comment provider owns the individual comments and their callbacks.
37
+
35
38
  ```tsx
36
39
  import {
40
+ Comment,
37
41
  CommentContextProvider,
38
42
  CommentOverlay,
39
43
  CommentRenderer,
44
+ ConfirmSession,
45
+ CreateSession,
46
+ FeedbackSessionProvider,
47
+ ResolveSession,
48
+ StartResolving,
49
+ ToggleOverlayButton,
40
50
  } from '@kendew-agency/react-feedback-layer';
41
51
 
42
- function App() {
43
- const handleConfirm = async (comments, projectId) => {
44
- // Save comments to your database
45
- await saveToDatabase(comments, projectId);
46
- };
47
-
48
- const handleResolve = async (comments) => {
49
- // Mark comments as resolved in your database
50
- await resolveInDatabase(comments);
51
- };
52
-
53
- const handleError = (error) => {
54
- console.error('Comment error:', error.code, error.message);
55
- };
56
-
52
+ function App({ isReviewer }: { isReviewer: boolean }) {
57
53
  return (
58
- <CommentContextProvider
59
- currentUser={{ name: 'John Doe', id: 'user-123' }}
60
- onConfirm={handleConfirm}
61
- onResolve={handleResolve}
62
- onError={handleError}
63
- initialComments={[]}
54
+ <FeedbackSessionProvider
55
+ canResolveSession={isReviewer}
56
+ onCreateSession={async ({ type, user, projectId }) => {
57
+ // Persist the session and return it. The returned status is ignored,
58
+ // a new session always starts as a draft.
59
+ return api.createSession({ type, user, projectId });
60
+ }}
61
+ onConfirmSession={(sessionId, type) => api.confirmSession(sessionId)}
62
+ onStartResolving={(sessionId) => api.startResolving(sessionId)}
63
+ onResolveSession={(sessionId) => api.resolveSession(sessionId)}
64
+ onError={(error) => console.error(error.code, error.message)}
64
65
  >
65
- <CommentOverlay>
66
- <YourContent />
67
- <CommentRenderer
68
- Comment={YourCommentComponent}
69
- DraftComment={YourDraftComponent}
70
- ResolvingComment={YourResolvingComponent}
71
- ResolvedComment={YourResolvedComponent}
72
- />
73
- </CommentOverlay>
74
- </CommentContextProvider>
66
+ <CommentContextProvider
67
+ currentUser={{ name: 'John Doe', id: 'user-123' }}
68
+ onAdd={(comment) => api.addComment(comment)}
69
+ onEdit={(comment) => api.editComment(comment)}
70
+ onDelete={(commentId) => api.deleteComment(commentId)}
71
+ onResolve={(comment) => api.resolveComment(comment)}
72
+ onReopen={(comment) => api.reopenComment(comment)}
73
+ onError={(error) => console.error(error.code, error.message)}
74
+ >
75
+ <CreateSession>Start feedback session</CreateSession>
76
+ <ConfirmSession>Confirm session</ConfirmSession>
77
+ <StartResolving>Start resolving</StartResolving>
78
+ <ResolveSession>Resolve session</ResolveSession>
79
+ <ToggleOverlayButton>Toggle comments</ToggleOverlayButton>
80
+
81
+ <CommentOverlay>
82
+ <YourContent />
83
+ <CommentRenderer
84
+ Comment={YourCommentComponent}
85
+ DraftComment={YourDraftComponent}
86
+ ResolvedComment={YourResolvedComponent}
87
+ />
88
+ </CommentOverlay>
89
+ </CommentContextProvider>
90
+ </FeedbackSessionProvider>
75
91
  );
76
92
  }
77
93
  ```
78
94
 
79
95
  ## Core Concepts
80
96
 
97
+ ### Feedback Sessions
98
+
99
+ Every comment belongs to a feedback session. Only the comments of the active session (`comment.sessionId === session.id`) are visible. Without a session no comment is shown and no comment can be added.
100
+
101
+ #### Session flow
102
+
103
+ 1. **Create the session.** Call `createSession()` (or render `<CreateSession />`). The provider calls `onCreateSession`, stores the returned session as a `draft` and emits `onSessionCreated`.
104
+ 2. **Add draft comments.** While the session is a `draft`, click or drag on the overlay to register a comment, write content and confirm it with `Comment.Confirm`. Confirming a comment calls `onAdd` and turns the comment from `draft` into `published`. Published comments can be edited (`onEdit`) and deleted (`onDelete`) as long as the session is a `draft`.
105
+ 3. **Confirm the session.** Call `confirmSession()` (or render `<ConfirmSession />`). It calls `onConfirmSession(sessionId, type)`, sets `confirmedAt` and emits `onSessionConfirmed`. It is refused with a `SessionStateError` when the session is not a draft, when a local draft comment still exists, or when the session has no comments.
106
+ 4. **Start resolving.** Call `startResolving()` (or render `<StartResolving />`). It calls `onStartResolving(sessionId)` and emits `onSessionResolving`. Requires `canResolveSession` and a `confirmed` session.
107
+ 5. **Resolve comments.** While the session is `resolving`, resolve each published comment with `resolveComment(id)` or `<Comment.Resolve />`, and reopen resolved comments with `reopenComment(id)` or `<Comment.Reopen />`. Requires `canResolveSession`.
108
+ 6. **Resolve the session.** Call `resolveSession()` (or render `<ResolveSession />`). It calls `onResolveSession(sessionId)`, sets `resolvedAt` and emits `onSessionResolved`. Requires `canResolveSession`, a `resolving` session and no comment that is still `published`.
109
+
110
+ #### Session status
111
+
112
+ `Session_Status` is `"draft" | "confirmed" | "resolving" | "resolved"`.
113
+
114
+ | From | To | Triggered by | Requires |
115
+ |------|----|--------------|----------|
116
+ | (none) | `draft` | `createSession()` | No other draft session, `onCreateSession` provided |
117
+ | `draft` | `confirmed` | `confirmSession()` | No local draft comments, at least one comment |
118
+ | `confirmed` | `resolving` | `startResolving()` | `canResolveSession` |
119
+ | `resolving` | `resolved` | `resolveSession()` | `canResolveSession`, no `published` comment left |
120
+
121
+ No other transitions exist. A transition is committed only after its callback resolves. When the callback throws or rejects, the status stays as it was and `onError` receives the error.
122
+
123
+ What each status allows:
124
+
125
+ | Status | Add, edit, delete comments | Resolve, reopen comments |
126
+ |--------|----------------------------|--------------------------|
127
+ | `draft` | Yes | No |
128
+ | `confirmed` | No | No |
129
+ | `resolving` | No | Yes, with `canResolveSession` |
130
+ | `resolved` | No | No |
131
+
132
+ Calls that are not allowed return `{ error }` with a `SessionStateError` and call `onError`. Calls without permission return a `PermissionError`.
133
+
81
134
  ### Comment Lifecycle
82
135
 
83
- Comments flow through four distinct states:
136
+ Comments have three statuses:
137
+
138
+ 1. **Draft** - Newly created and only held locally. It is not persisted yet.
139
+ 2. **Published** - Persisted through `onAdd` (or `onEdit` for later edits).
140
+ 3. **Resolved** - Resolved through `onResolve`. A resolved comment can be reopened through `onReopen`, which turns it back into `published` and removes `resolvedAt`.
84
141
 
85
- 1. **Draft** - Newly created, not yet saved
86
- 2. **Published** - Confirmed and saved to your database
87
- 3. **Resolving** - Marked for resolution (in progress)
88
- 4. **Resolved** - Completed and archived
142
+ Draft comments exist only in a `draft` session. Resolving and reopening only work in a `resolving` session.
89
143
 
90
144
  ### Headless UI Architecture
91
145
 
@@ -103,6 +157,7 @@ The `Comment` component uses a compound pattern for maximum flexibility:
103
157
  <Comment.Confirm />
104
158
  <Comment.Delete />
105
159
  <Comment.Resolve />
160
+ <Comment.Reopen />
106
161
  </Comment.Root>
107
162
  ```
108
163
 
@@ -110,59 +165,143 @@ The `Comment` component uses a compound pattern for maximum flexibility:
110
165
 
111
166
  ### Components
112
167
 
168
+ #### `FeedbackSessionProvider`
169
+
170
+ Owns the active session and the session transitions. It must wrap `CommentContextProvider`.
171
+
172
+ **Props:**
173
+
174
+ ```tsx
175
+ type FeedbackSessionProviderProps = {
176
+ children: ReactNode;
177
+
178
+ // Resume a session, for example after a reload
179
+ initialSession?: InitialFeedbackSession;
180
+
181
+ // Default project id passed to onCreateSession (1 to 128 characters)
182
+ projectId?: string;
183
+
184
+ // Whether the current user may start resolving, resolve the session,
185
+ // and resolve and reopen comments. Default: false
186
+ canResolveSession?: boolean;
187
+
188
+ // Persist a new session. The returned status is ignored, it starts as a draft.
189
+ onCreateSession?: (input: CreateSessionInput) => Promise<FeedbackSession>;
190
+
191
+ // Persist the confirmation of the session
192
+ onConfirmSession?: (sessionId: string, type: SessionType) => Promise<void>;
193
+
194
+ // Persist the start of the resolution
195
+ onStartResolving?: (sessionId: string) => Promise<void>;
196
+
197
+ // Persist the resolution of the session
198
+ onResolveSession?: (sessionId: string) => Promise<void>;
199
+
200
+ // Receives every error that the provider produces
201
+ onError?: (error: KnownError) => void;
202
+ };
203
+
204
+ type CreateSessionInput = {
205
+ type: SessionType; // "feedback"
206
+ user: User | null;
207
+ projectId?: string | undefined;
208
+ };
209
+ ```
210
+
211
+ `createSession` is refused when `onCreateSession` is not provided, when a draft session already exists, when a creation is in progress, or when `projectId` is not 1 to 128 characters long.
212
+
213
+ `initialSession` must have a valid `status`. Otherwise the provider starts without a session and reports a `SessionStateError` once on mount. Its `comments` are optional and default to an empty array.
214
+
215
+ **Example:**
216
+
217
+ ```tsx
218
+ <FeedbackSessionProvider
219
+ initialSession={savedSession}
220
+ canResolveSession={user.role === 'reviewer'}
221
+ onCreateSession={api.createSession}
222
+ onConfirmSession={(id) => api.confirmSession(id)}
223
+ onStartResolving={(id) => api.startResolving(id)}
224
+ onResolveSession={(id) => api.resolveSession(id)}
225
+ onError={handleError}
226
+ >
227
+ {children}
228
+ </FeedbackSessionProvider>
229
+ ```
230
+
231
+ #### `UserProvider`
232
+
233
+ Optional. Shares the current user with the session provider and the comment provider. When a `UserProvider` is present, its `user` takes precedence over the `currentUser` prop of `CommentContextProvider`.
234
+
235
+ ```tsx
236
+ <UserProvider user={{ id: 'user-123', name: 'John Doe' }}>
237
+ <FeedbackSessionProvider>{/* ... */}</FeedbackSessionProvider>
238
+ </UserProvider>
239
+ ```
240
+
241
+ Use `useCurrentUser()` to read the user (`User | null`). It throws outside a `UserProvider`.
242
+
113
243
  #### `CommentContextProvider`
114
244
 
115
- The root provider that manages all comment state and actions.
245
+ The provider that manages comment state and comment actions. It throws when it is not rendered inside a `FeedbackSessionProvider`. Standalone use is no longer possible.
116
246
 
117
247
  **Props:**
118
248
 
119
249
  ```tsx
120
- interface CommentOverlayProps {
121
- // Initial comments from your database
250
+ type CommentOverlayProps = {
251
+ // Comments to start with. Defaults to the comments of the session.
252
+ // Each comment needs a sessionId equal to the initialSession id.
122
253
  initialComments?: ConfirmedComment[];
123
-
124
- // Current logged-in user
125
- currentUser: User | null;
126
-
127
- // Your app content
254
+
255
+ // Current logged-in user (default: null). Ignored when a UserProvider exists.
256
+ currentUser?: User | null;
257
+
128
258
  children: ReactNode;
129
-
259
+
130
260
  // Initial overlay state (default: "inactive")
131
- initialOverlayState?: "idle" | "editing" | "saving" | "error" | "resolving" | "inactive";
132
-
133
- // Optional real-time subscription
261
+ initialOverlayState?: "idle" | "editing" | "saving" | "resolving" | "inactive";
262
+
263
+ // Optional real-time subscription (beta)
134
264
  subscription?: {
135
- subscribe: (update: unknown) => void;
265
+ subscribe: (onUpdate: (comment: CommentType) => void) => void;
136
266
  unsubscribe: () => void;
137
267
  };
138
-
139
- // Callback when user confirms draft comments
140
- onConfirm: (comments: ConfirmedComment[], projectId?: string) => Promise<void>;
141
-
142
- // Callback when user resolves comments
143
- onResolve: (comments: ConfirmedComment[]) => Promise<void>;
144
-
145
- // Callback to handle errors
146
- onError: (error: KnownError) => void;
147
-
268
+
269
+ // Persist a newly added comment
270
+ onAdd?: (comment: ConfirmedComment) => Promise<void>;
271
+
272
+ // Persist an edited comment
273
+ onEdit?: (comment: ConfirmedComment) => Promise<void>;
274
+
275
+ // Persist a resolved comment
276
+ onResolve?: (comment: ConfirmedComment) => Promise<void>;
277
+
278
+ // Persist a reopened comment
279
+ onReopen?: (comment: ConfirmedComment) => Promise<void>;
280
+
281
+ // Delete a persisted comment
282
+ onDelete?: (commentId: string) => Promise<void>;
283
+
284
+ // Receives every error that the provider produces
285
+ onError?: (error: KnownError) => void;
286
+
148
287
  // Optional configuration for the comment layer
149
- config?: {
150
- // Custom prefix for comment IDs
151
- idPrefix?: string;
152
- // Visibility of comment indicators: "always" | "active"
153
- indicatorVisibility?: "always" | "active";
154
- // Comment visibility settings
155
- commentVisibility?: {
156
- hideResolved?: boolean;
157
- hideResolving?: boolean;
158
- };
159
- };
160
-
161
- // Optional project ID to attach to all comments in this overlay
288
+ config?: Config;
289
+
290
+ // Optional project ID attached to every new comment
162
291
  projectId?: string;
163
- }
292
+ };
164
293
  ```
165
294
 
295
+ | Callback | Called when | Receives |
296
+ |----------|-------------|----------|
297
+ | `onAdd` | A draft comment is confirmed | The comment with status `published` |
298
+ | `onEdit` | A published comment gets new content | The updated comment with status `published` |
299
+ | `onDelete` | A published comment is deleted | The comment id |
300
+ | `onResolve` | A published comment is resolved | The comment with status `resolved` and `resolvedAt` |
301
+ | `onReopen` | A resolved comment is reopened | The comment with status `published` and no `resolvedAt` |
302
+
303
+ Every callback is optional. When a callback throws or rejects, the change is not applied and `onError` receives an `AddError`, `EditError`, `DeleteError`, `ResolveError` or `ReopenError`. Deleting a local draft does not call `onDelete`.
304
+
166
305
  **Example:**
167
306
 
168
307
  ```tsx
@@ -170,24 +309,16 @@ interface CommentOverlayProps {
170
309
  currentUser={{ name: 'Jane Smith', id: '456', avatar: '/avatar.jpg' }}
171
310
  initialComments={existingComments}
172
311
  projectId="proj_123456789"
173
- onConfirm={async (comments, projectId) => {
174
- await api.createComments(comments, projectId);
175
- }}
176
- onResolve={async (comments) => {
177
- await api.resolveComments(comments);
178
- }}
179
- onError={(error) => {
180
- console.error('Comment operation failed:', error);
181
- toast.error('Failed to save comments');
182
- }}
312
+ onAdd={(comment) => api.addComment(comment)}
313
+ onResolve={(comment) => api.resolveComment(comment)}
314
+ onReopen={(comment) => api.reopenComment(comment)}
315
+ onError={(error) => toast.error(error.message)}
183
316
  initialOverlayState="idle"
184
317
  config={{
185
318
  idPrefix: 'proj_',
186
319
  indicatorVisibility: 'active',
187
- commentVisibility: {
188
- hideResolved: false,
189
- hideResolving: false,
190
- },
320
+ draftVisibility: 'visible',
321
+ commentVisibility: { hideResolved: false },
191
322
  }}
192
323
  >
193
324
  {children}
@@ -201,7 +332,7 @@ Creates an interactive overlay for adding comments via click or drag selection.
201
332
  **Props:**
202
333
 
203
334
  ```tsx
204
- interface CommentOverlayProps {
335
+ interface CommentOverlayProps extends HTMLProps<HTMLDivElement> {
205
336
  children: ReactNode;
206
337
  }
207
338
  ```
@@ -211,6 +342,7 @@ interface CommentOverlayProps {
211
342
  - **Click** - Creates a comment at the clicked position
212
343
  - **Drag** - Creates a comment with a visual indicator box
213
344
  - **Inactive State** - Renders children without overlay when `overlayState === "inactive"`
345
+ - **Session state** - Comments can only be created while the session is a `draft`. Otherwise `onError` receives a `SessionStateError`.
214
346
 
215
347
  **Example:**
216
348
 
@@ -223,7 +355,7 @@ interface CommentOverlayProps {
223
355
 
224
356
  #### `CommentRenderer`
225
357
 
226
- Renders all comments based on their current state.
358
+ Renders all visible comments based on their status. Resolved comments are skipped when `config.commentVisibility.hideResolved` is `true`.
227
359
 
228
360
  **Props:**
229
361
 
@@ -231,13 +363,10 @@ Renders all comments based on their current state.
231
363
  interface CommentRendererProps {
232
364
  // Component for published comments
233
365
  Comment: ElementType<{ comment: CommentType }>;
234
-
366
+
235
367
  // Component for draft comments
236
368
  DraftComment: ElementType<{ comment: CommentType }>;
237
-
238
- // Component for resolving comments
239
- ResolvingComment: ElementType<{ comment: CommentType }>;
240
-
369
+
241
370
  // Component for resolved comments
242
371
  ResolvedComment: ElementType<{ comment: CommentType }>;
243
372
  }
@@ -249,7 +378,6 @@ interface CommentRendererProps {
249
378
  <CommentRenderer
250
379
  Comment={PublishedComment}
251
380
  DraftComment={DraftComment}
252
- ResolvingComment={ResolvingComment}
253
381
  ResolvedComment={ResolvedComment}
254
382
  />
255
383
  ```
@@ -388,7 +516,7 @@ interface CommentDeleteProps extends ButtonHTMLAttributes<HTMLButtonElement> {
388
516
 
389
517
  ##### `Comment.Resolve`
390
518
 
391
- Button to toggle resolving state (only for published/resolving comments).
519
+ Button that resolves the comment. It calls `resolveComment(comment.id)`, which needs a `resolving` session and `canResolveSession`. It renders nothing (and logs an error) for draft and resolved comments.
392
520
 
393
521
  **Props:**
394
522
 
@@ -406,91 +534,182 @@ interface CommentResolveProps extends ButtonHTMLAttributes<HTMLButtonElement> {
406
534
  </Comment.Resolve>
407
535
  ```
408
536
 
409
- #### Action Components
537
+ ##### `Comment.Reopen`
410
538
 
411
- ##### `ToggleOverlayButton`
539
+ Button that reopens a resolved comment. It calls `reopenComment(comment.id)`, with the same requirements as `Comment.Resolve`. It renders nothing (and logs an error) for draft and published comments.
412
540
 
413
- Toggles the comment overlay on/off.
541
+ ```tsx
542
+ <Comment.Reopen className="btn-reopen">Reopen</Comment.Reopen>
543
+ ```
414
544
 
415
- **Props:**
545
+ Hide both buttons for users that may not resolve by reading `canResolve` from `useComments()`:
416
546
 
417
547
  ```tsx
418
- interface CommentButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
419
- asChild?: boolean;
548
+ function PublishedComment({ comment }) {
549
+ const { canResolve } = useComments();
550
+ return (
551
+ <Comment.Root comment={comment}>
552
+ <Comment.Content />
553
+ {canResolve && <Comment.Resolve>Resolve</Comment.Resolve>}
554
+ </Comment.Root>
555
+ );
420
556
  }
421
557
  ```
422
558
 
423
- **Example:**
559
+ #### Action Components
424
560
 
425
- ```tsx
426
- import { ToggleOverlayButton } from '@kendew-agency/react-feedback-layer';
561
+ All action components accept button props and `asChild`. They call the matching action and then your own `onClick`. The result of the action is not exposed, so use the hooks when you need it.
427
562
 
563
+ ##### `ToggleOverlayButton`
564
+
565
+ Toggles the comment overlay on/off. Sets `data-active` when the overlay is not inactive.
566
+
567
+ ```tsx
428
568
  <ToggleOverlayButton className="toggle-btn">
429
569
  Toggle Comments
430
570
  </ToggleOverlayButton>
431
571
  ```
432
572
 
433
- ##### `ConfirmComments`
573
+ ##### `CreateSession`, `ConfirmSession`, `StartResolving`, `ResolveSession`
434
574
 
435
- Confirms all draft comments and triggers the `onConfirm` callback.
575
+ Call `createSession()`, `confirmSession()`, `startResolving()` and `resolveSession()` of `useFeedbackSession()`. They must be rendered inside a `FeedbackSessionProvider`.
436
576
 
437
- **Example:**
577
+ ```tsx
578
+ <CreateSession>New session</CreateSession>
579
+ <ConfirmSession>Confirm</ConfirmSession>
580
+ <StartResolving>Start resolving</StartResolving>
581
+ <ResolveSession>Finish</ResolveSession>
582
+ ```
583
+
584
+ ### Hooks
585
+
586
+ #### `useFeedbackSession()`
587
+
588
+ Access the session and its actions. Throws outside a `FeedbackSessionProvider`.
589
+
590
+ **Returns:**
438
591
 
439
592
  ```tsx
440
- import { ConfirmComments } from '@kendew-agency/react-feedback-layer';
593
+ type FeedbackSessionContextType = {
594
+ // The active session with its persisted comments, or null
595
+ session: ActiveFeedbackSession | null;
596
+
597
+ // The pending operation
598
+ sessionState:
599
+ | "idle"
600
+ | "creating"
601
+ | "confirming"
602
+ | "startingResolution"
603
+ | "completingResolution";
604
+
605
+ // Mirrors the canResolveSession prop
606
+ canResolve: boolean;
607
+
608
+ createSession: (options?: {
609
+ type?: SessionType;
610
+ user?: User | null;
611
+ projectId?: string;
612
+ }) => Promise<{ error: KnownError | null }>;
613
+ confirmSession: () => Promise<{ error: KnownError | null }>;
614
+ startResolving: () => Promise<{ error: KnownError | null }>;
615
+ resolveSession: () => Promise<{ error: KnownError | null }>;
616
+
617
+ // Subscribe to session transitions
618
+ events: SessionEvents;
619
+ };
620
+ ```
621
+
622
+ `createSession` defaults `type` to `"feedback"`, `user` to the `UserProvider` user, and `projectId` to the provider `projectId`. A failed or refused action returns `{ error }` and also calls `onError`. A second call of the same transition while it is pending resolves with `{ error: null }` and does nothing.
441
623
 
442
- <ConfirmComments className="btn-save">
443
- Save All Comments
444
- </ConfirmComments>
624
+ ```tsx
625
+ function SessionToolbar() {
626
+ const { session, sessionState, canResolve, confirmSession, startResolving } =
627
+ useFeedbackSession();
628
+
629
+ if (!session) return null;
630
+
631
+ return (
632
+ <div>
633
+ <span>Status: {session.status}</span>
634
+ {session.status === 'draft' && (
635
+ <button disabled={sessionState !== 'idle'} onClick={confirmSession}>
636
+ Confirm
637
+ </button>
638
+ )}
639
+ {session.status === 'confirmed' && canResolve && (
640
+ <button disabled={sessionState !== 'idle'} onClick={startResolving}>
641
+ Start resolving
642
+ </button>
643
+ )}
644
+ </div>
645
+ );
646
+ }
445
647
  ```
446
648
 
447
- ##### `ResolveComments`
649
+ #### Session events
448
650
 
449
- Resolves all resolving comments and triggers the `onResolve` callback.
651
+ `useFeedbackSession().events` mirrors the comment events. Each method accepts a callback and returns an `unsubscribe` function. Every event receives the `ActiveFeedbackSession` after the transition.
450
652
 
451
- **Example:**
653
+ | Event | Trigger | Callback Signature |
654
+ |-------|---------|-------------------|
655
+ | `onSessionCreated` | A draft session was created | `(session: ActiveFeedbackSession) => void` |
656
+ | `onSessionConfirmed` | The session moved to `confirmed` | `(session: ActiveFeedbackSession) => void` |
657
+ | `onSessionResolving` | The session moved to `resolving` | `(session: ActiveFeedbackSession) => void` |
658
+ | `onSessionResolved` | The session moved to `resolved` | `(session: ActiveFeedbackSession) => void` |
452
659
 
453
660
  ```tsx
454
- import { ResolveComments } from '@kendew-agency/react-feedback-layer';
661
+ function SessionTracker() {
662
+ const { events } = useFeedbackSession();
663
+
664
+ useEffect(
665
+ () =>
666
+ events.onSessionConfirmed((session) => {
667
+ analytics.track('session_confirmed', {
668
+ id: session.id,
669
+ comments: session.comments.length,
670
+ });
671
+ }),
672
+ [events],
673
+ );
455
674
 
456
- <ResolveComments className="btn-resolve-all">
457
- Resolve All
458
- </ResolveComments>
675
+ return null;
676
+ }
459
677
  ```
460
678
 
461
- ### Hooks
462
-
463
679
  #### `useComments()`
464
680
 
465
- Access the global comment context and actions.
681
+ Access the comment context and actions. Throws outside a `CommentContextProvider` (and outside a `FeedbackSessionProvider`).
466
682
 
467
683
  **Returns:**
468
684
 
469
685
  ```tsx
470
686
  interface CommentContext {
471
- // Filtered comment arrays
687
+ // Comments of the active session, after the draftVisibility filter
472
688
  draftComments: CommentType[];
473
689
  comments: CommentType[]; // Published comments
474
- resolvingComments: CommentType[];
475
690
  resolvedComments: CommentType[];
476
691
  allComments: CommentType[];
477
-
692
+
478
693
  // State
479
694
  overlayState: CommentOverlayState;
480
695
  currentUser: User | null;
481
696
  config: Config | undefined;
482
-
697
+ // Mirrors the canResolveSession prop of the session provider
698
+ canResolve: boolean;
699
+
483
700
  // Actions
484
701
  registerComment: (position: Position, indicatorPosition?: Indicator) => void;
485
- updateComment: (id: string, newComment: Pick<CommentType, "content">) => void;
486
- deleteComment: (id: string) => void;
702
+ updateComment: (
703
+ id: string,
704
+ newComment: Pick<CommentType, "content">,
705
+ ) => Promise<{ error: KnownError | null }>;
706
+ deleteComment: (id: string) => Promise<{ error: KnownError | null }>;
707
+ resolveComment: (id: string) => Promise<{ error: KnownError | null }>;
708
+ reopenComment: (id: string) => Promise<{ error: KnownError | null }>;
487
709
  focusOnComment: (id: string | null) => void;
488
710
  getActiveComment: () => CommentType | undefined;
489
711
  toggleOverlay: () => void;
490
- toggleResolvingComment: (id: string) => void;
491
712
  changeOverlayState: (state: CommentOverlayState) => void;
492
- confirmComments: () => Promise<{ error: Error | DOMException | null }>;
493
- resolveComments: () => Promise<{ error: Error | DOMException | null }>;
494
713
  updateCommentVisibility: (visibility: Partial<CommentVisibility>) => void;
495
714
  triggerError: (error: KnownError) => void;
496
715
 
@@ -499,31 +718,22 @@ interface CommentContext {
499
718
  }
500
719
  ```
501
720
 
721
+ `updateComment` adds a draft comment (`onAdd`) or edits a published one (`onEdit`). It needs a `draft` session and rejects empty content for new comments. `resolveComment` and `reopenComment` need a `resolving` session and `canResolveSession`, and they do nothing (`{ error: null }`) when the comment is already in the target status.
722
+
502
723
  **Example:**
503
724
 
504
725
  ```tsx
505
726
  import { useComments } from '@kendew-agency/react-feedback-layer';
506
727
 
507
728
  function CommentToolbar() {
508
- const {
509
- draftComments,
510
- confirmComments,
511
- overlayState,
512
- toggleOverlay,
513
- config
514
- } = useComments();
515
-
729
+ const { allComments, overlayState, toggleOverlay, config } = useComments();
730
+
516
731
  return (
517
732
  <div>
518
733
  <button onClick={toggleOverlay}>
519
734
  {overlayState === 'inactive' ? 'Enable' : 'Disable'} Comments
520
735
  </button>
521
- <button
522
- onClick={confirmComments}
523
- disabled={draftComments.length === 0}
524
- >
525
- Save {draftComments.length} Comments
526
- </button>
736
+ <span>{allComments.length} comments</span>
527
737
  {config?.commentVisibility && (
528
738
  <span>Resolved hidden: {config.commentVisibility.hideResolved ? 'Yes' : 'No'}</span>
529
739
  )}
@@ -547,14 +757,10 @@ interface CommentScope {
547
757
  }
548
758
  ```
549
759
 
550
- **Example:**
551
-
552
760
  ```tsx
553
- import { useCommentScope } from '@kendew-agency/react-feedback-layer';
554
-
555
761
  function CustomCommentContent() {
556
762
  const { comment, isActive, draft } = useCommentScope();
557
-
763
+
558
764
  return (
559
765
  <div className={isActive ? 'active' : ''}>
560
766
  <p>{draft}</p>
@@ -564,72 +770,34 @@ function CustomCommentContent() {
564
770
  }
565
771
  ```
566
772
 
567
- #### `events` (via `useComments()`)
568
-
569
- The `events` object provides a subscription-based system for reacting to comment lifecycle changes. Each event method accepts a callback and returns an `unsubscribe` function.
773
+ #### Comment events
570
774
 
571
- **Available Events:**
775
+ `useComments().events` provides a subscription-based system for reacting to comment changes. Each method accepts a callback and returns an `unsubscribe` function.
572
776
 
573
777
  | Event | Trigger | Callback Signature |
574
778
  |-------|---------|-------------------|
575
779
  | `onFocusChange` | Focus moves to a different comment | `(commentId: string \| null, comment: CommentType \| undefined) => void` |
576
- | `onCommentsConfirmed` | Draft comments are successfully saved | `(comments: CommentType[]) => void` |
577
- | `onCommentsResolved` | Comments are successfully resolved | `(comments: CommentType[]) => void` |
578
- | `onCommentDeleted` | A comment is deleted | `(commentId: string) => void` |
579
780
  | `onCommentRegistered` | A new draft comment is created | `(comment: CommentType) => void` |
580
-
581
- **Basic Usage:**
781
+ | `onCommentAdded` | A comment was persisted through `onAdd` | `(comment: CommentType) => void` |
782
+ | `onCommentEdited` | A comment was persisted through `onEdit` | `(comment: CommentType) => void` |
783
+ | `onCommentResolved` | A comment was resolved | `(comment: CommentType) => void` |
784
+ | `onCommentReopened` | A resolved comment was reopened | `(comment: CommentType) => void` |
785
+ | `onCommentDeleted` | A comment is deleted | `(commentId: string) => void` |
582
786
 
583
787
  ```tsx
584
- import { useComments } from '@kendew-agency/react-feedback-layer';
585
- import { useEffect } from 'react';
586
-
587
788
  function CommentTracker() {
588
789
  const { events } = useComments();
589
790
 
590
- useEffect(() => {
591
- const unsubscribe = events.onFocusChange((commentId, comment) => {
592
- console.log('Focus changed to:', commentId);
593
- if (comment) {
594
- highlightElement(comment.position);
595
- }
596
- });
597
-
598
- return unsubscribe;
599
- }, [events]);
600
-
601
- useEffect(() => {
602
- const unsubscribe = events.onCommentsConfirmed((comments) => {
603
- console.log(`${comments.length} comments saved`);
604
- toast.success('Comments saved successfully!');
605
- });
606
-
607
- return unsubscribe;
608
- }, [events]);
609
-
610
- return null;
611
- }
612
- ```
613
-
614
- **Multiple Subscriptions:**
615
-
616
- ```tsx
617
- function AnalyticsTracker() {
618
- const { events } = useComments();
619
-
620
791
  useEffect(() => {
621
792
  const unsubs = [
622
- events.onCommentRegistered((comment) => {
623
- analytics.track('comment_created', {
624
- position: comment.position,
625
- user: comment.user?.name,
626
- });
793
+ events.onCommentAdded((comment) => {
794
+ analytics.track('comment_added', { id: comment.id });
627
795
  }),
628
- events.onCommentsConfirmed((comments) => {
629
- analytics.track('comments_confirmed', { count: comments.length });
796
+ events.onCommentResolved((comment) => {
797
+ toast.success(`Resolved: ${comment.content}`);
630
798
  }),
631
- events.onCommentsResolved((comments) => {
632
- analytics.track('comments_resolved', { count: comments.length });
799
+ events.onCommentReopened((comment) => {
800
+ toast(`Reopened: ${comment.content}`);
633
801
  }),
634
802
  events.onCommentDeleted((id) => {
635
803
  analytics.track('comment_deleted', { commentId: id });
@@ -643,58 +811,42 @@ function AnalyticsTracker() {
643
811
  }
644
812
  ```
645
813
 
646
- **Syncing with External State:**
647
-
648
- ```tsx
649
- function CommentSidebar() {
650
- const { events, allComments } = useComments();
651
- const [activeId, setActiveId] = useState<string | null>(null);
652
-
653
- useEffect(() => {
654
- return events.onFocusChange((commentId) => {
655
- setActiveId(commentId);
656
- // Scroll sidebar to the active comment
657
- if (commentId) {
658
- document.getElementById(`sidebar-${commentId}`)?.scrollIntoView({
659
- behavior: 'smooth',
660
- });
661
- }
662
- });
663
- }, [events]);
664
-
665
- return (
666
- <aside className="comment-sidebar">
667
- {allComments.map((comment) => (
668
- <div
669
- key={comment.id}
670
- id={`sidebar-${comment.id}`}
671
- className={comment.id === activeId ? 'active' : ''}
672
- >
673
- <p>{comment.content}</p>
674
- <small>{comment.user?.name}</small>
675
- </div>
676
- ))}
677
- </aside>
678
- );
679
- }
680
- ```
681
-
682
- **Type Definitions:**
814
+ Type definitions:
683
815
 
684
816
  ```tsx
685
817
  import type {
686
818
  CommentEvents,
687
819
  CommentEventMap,
820
+ SessionEvents,
821
+ SessionEventMap,
688
822
  Unsubscribe,
689
823
  } from '@kendew-agency/react-feedback-layer/types';
690
824
  ```
691
825
 
826
+ ### Draft visibility
827
+
828
+ `config.draftVisibility` controls whether comments that other users already persisted are shown while the session is a draft.
829
+
830
+ | Value | Effect while the session is a `draft` |
831
+ |-------|----------------------------------------|
832
+ | `"visible"` (default) | All comments of the session are shown |
833
+ | `"hidden"` | Only your own comments are shown. Comments of other users are hidden. |
834
+
835
+ - The default is `"visible"`. Any other value falls back to `"visible"`.
836
+ - It only applies while the session status is `draft`. Once the session is `confirmed`, `resolving` or `resolved`, all comments of the session are shown.
837
+ - Your own local drafts are always shown. Comments without a `user.id` are also shown.
838
+ - Hidden comments are removed from `draftComments`, `comments`, `resolvedComments` and `allComments`.
839
+
840
+ ```tsx
841
+ <CommentContextProvider config={{ draftVisibility: 'hidden' }} /* ... */>
842
+ ```
843
+
692
844
  ### Types
693
845
 
694
846
  Import types from the `/types` subpath:
695
847
 
696
848
  ```tsx
697
- import type {
849
+ import type {
698
850
  CommentType,
699
851
  ConfirmedComment,
700
852
  User,
@@ -702,8 +854,16 @@ import type {
702
854
  Indicator,
703
855
  CommentOverlayState,
704
856
  CommentVisibility,
705
- CommentAction,
706
- Config
857
+ DraftVisibility,
858
+ Config,
859
+ FeedbackSession,
860
+ ActiveFeedbackSession,
861
+ InitialFeedbackSession,
862
+ SessionStatus,
863
+ SessionType,
864
+ SessionOperationState,
865
+ CreateSessionInput,
866
+ KnownError,
707
867
  } from '@kendew-agency/react-feedback-layer/types';
708
868
  ```
709
869
 
@@ -717,12 +877,50 @@ type CommentType = {
717
877
  user: User | null;
718
878
  createdAt: Date;
719
879
  resolvedAt?: Date;
720
- status: "draft" | "published" | "resolving" | "resolved";
880
+ status: "draft" | "published" | "resolved";
721
881
  indicator?: Indicator | null;
882
+ sessionId: string;
722
883
  projectId?: string;
723
884
  };
885
+
886
+ // A persisted comment, as passed to onAdd, onEdit, onResolve and onReopen
887
+ type ConfirmedComment = Omit<CommentType, "status"> & {
888
+ status: "published" | "resolved";
889
+ };
724
890
  ```
725
891
 
892
+ #### `FeedbackSession`
893
+
894
+ ```tsx
895
+ type SessionType = "feedback";
896
+ type SessionStatus = "draft" | "confirmed" | "resolving" | "resolved";
897
+
898
+ type FeedbackSession = {
899
+ id: string;
900
+ type: SessionType;
901
+ status: SessionStatus;
902
+ createdAt: Date;
903
+ createdBy: string; // user id
904
+ participantIds: string[];
905
+ confirmedAt?: Date;
906
+ resolvedAt?: Date;
907
+ projectId?: string;
908
+ sourceSessionId?: string; // reserved, no behavior depends on it
909
+ };
910
+
911
+ // The session held by the provider
912
+ type ActiveFeedbackSession = FeedbackSession & {
913
+ comments: ConfirmedComment[];
914
+ };
915
+
916
+ // Accepted by initialSession. comments is optional.
917
+ type InitialFeedbackSession = FeedbackSession & {
918
+ comments?: ConfirmedComment[];
919
+ };
920
+ ```
921
+
922
+ `participantIds` gets the `user.id` of every user that added a comment while the session is a draft.
923
+
726
924
  #### `User`
727
925
 
728
926
  ```tsx
@@ -756,7 +954,6 @@ type Indicator = {
756
954
  ```tsx
757
955
  type CommentVisibility = {
758
956
  hideResolved?: boolean;
759
- hideResolving?: boolean;
760
957
  };
761
958
  ```
762
959
 
@@ -766,10 +963,12 @@ type CommentVisibility = {
766
963
  type Config = {
767
964
  // Custom prefix for comment IDs
768
965
  idPrefix?: string;
769
- // Visibility of comment indicators
966
+ // Visibility of comment indicators (default: "always")
770
967
  indicatorVisibility?: "always" | "active";
771
968
  // Comment visibility settings
772
969
  commentVisibility?: CommentVisibility;
970
+ // Visibility of other users' comments in a draft session (default: "visible")
971
+ draftVisibility?: "hidden" | "visible";
773
972
  };
774
973
  ```
775
974
 
@@ -779,12 +978,15 @@ type Config = {
779
978
 
780
979
  ```tsx
781
980
  import {
981
+ Comment,
782
982
  CommentContextProvider,
783
983
  CommentOverlay,
784
984
  CommentRenderer,
785
- Comment,
985
+ ConfirmSession,
986
+ CreateSession,
987
+ FeedbackSessionProvider,
786
988
  ToggleOverlayButton,
787
- ConfirmComments,
989
+ useComments,
788
990
  } from '@kendew-agency/react-feedback-layer';
789
991
 
790
992
  function DraftComment({ comment }) {
@@ -803,6 +1005,8 @@ function DraftComment({ comment }) {
803
1005
  }
804
1006
 
805
1007
  function PublishedComment({ comment }) {
1008
+ const { canResolve } = useComments();
1009
+
806
1010
  return (
807
1011
  <Comment.Root comment={comment} className="published-comment">
808
1012
  <Comment.Indicator className="indicator" />
@@ -813,7 +1017,7 @@ function PublishedComment({ comment }) {
813
1017
  <span>{comment.createdAt.toLocaleDateString()}</span>
814
1018
  </div>
815
1019
  <div className="actions">
816
- <Comment.Resolve>Resolve</Comment.Resolve>
1020
+ {canResolve && <Comment.Resolve>Resolve</Comment.Resolve>}
817
1021
  <Comment.Delete>Delete</Comment.Delete>
818
1022
  </div>
819
1023
  </div>
@@ -821,88 +1025,103 @@ function PublishedComment({ comment }) {
821
1025
  );
822
1026
  }
823
1027
 
1028
+ function ResolvedComment({ comment }) {
1029
+ return (
1030
+ <Comment.Root comment={comment} className="resolved-comment">
1031
+ <Comment.Content />
1032
+ <Comment.Reopen>Reopen</Comment.Reopen>
1033
+ </Comment.Root>
1034
+ );
1035
+ }
1036
+
824
1037
  function App() {
825
1038
  return (
826
- <CommentContextProvider
827
- currentUser={{ name: 'John Doe', id: '123' }}
828
- onConfirm={async (comments, projectId) => {
829
- const response = await fetch('/api/comments', {
1039
+ <FeedbackSessionProvider
1040
+ onCreateSession={async ({ type, user, projectId }) => {
1041
+ const response = await fetch('/api/sessions', {
830
1042
  method: 'POST',
831
- body: JSON.stringify({ comments, projectId }),
1043
+ body: JSON.stringify({ type, user, projectId }),
832
1044
  });
833
- if (!response.ok) {
834
- throw new Error('Failed to save comments');
835
- }
1045
+ if (!response.ok) throw new Error('Failed to create session');
1046
+ return response.json();
836
1047
  }}
837
- onResolve={async (comments) => {
838
- const response = await fetch('/api/comments/resolve', {
839
- method: 'POST',
840
- body: JSON.stringify(comments),
841
- });
842
- if (!response.ok) {
843
- throw new Error('Failed to resolve comments');
844
- }
845
- }}
846
- onError={(error) => {
847
- console.error('Comment operation failed:', error);
848
- // Show user-friendly error message
849
- }}
850
- config={{
851
- commentVisibility: {
852
- hideResolved: false,
853
- hideResolving: false,
854
- },
1048
+ onConfirmSession={async (sessionId) => {
1049
+ await fetch(`/api/sessions/${sessionId}/confirm`, { method: 'POST' });
855
1050
  }}
1051
+ onError={(error) => console.error(error.code, error.message)}
856
1052
  >
857
- <ToggleOverlayButton>Toggle Feedback Mode</ToggleOverlayButton>
858
- <ConfirmComments>Save All Comments</ConfirmComments>
859
-
860
- <CommentOverlay>
861
- <YourContent />
862
- <CommentRenderer
863
- Comment={PublishedComment}
864
- DraftComment={DraftComment}
865
- ResolvingComment={PublishedComment}
866
- ResolvedComment={PublishedComment}
867
- />
868
- </CommentOverlay>
869
- </CommentContextProvider>
1053
+ <CommentContextProvider
1054
+ currentUser={{ name: 'John Doe', id: '123' }}
1055
+ onAdd={async (comment) => {
1056
+ const response = await fetch('/api/comments', {
1057
+ method: 'POST',
1058
+ body: JSON.stringify(comment),
1059
+ });
1060
+ if (!response.ok) throw new Error('Failed to save comment');
1061
+ }}
1062
+ onError={(error) => console.error(error.code, error.message)}
1063
+ >
1064
+ <ToggleOverlayButton>Toggle Feedback Mode</ToggleOverlayButton>
1065
+ <CreateSession>Start session</CreateSession>
1066
+ <ConfirmSession>Send feedback</ConfirmSession>
1067
+
1068
+ <CommentOverlay>
1069
+ <YourContent />
1070
+ <CommentRenderer
1071
+ Comment={PublishedComment}
1072
+ DraftComment={DraftComment}
1073
+ ResolvedComment={ResolvedComment}
1074
+ />
1075
+ </CommentOverlay>
1076
+ </CommentContextProvider>
1077
+ </FeedbackSessionProvider>
870
1078
  );
871
1079
  }
872
1080
  ```
873
1081
 
874
- ### With Real-time Subscription
1082
+ ### Resuming a session
1083
+
1084
+ Pass the saved session as `initialSession`. Each of its comments, and each entry of `initialComments`, needs a `sessionId` equal to the `initialSession` id. Comments with another `sessionId` are not shown.
875
1085
 
876
1086
  ```tsx
877
- import { useEffect, useState } from 'react';
1087
+ <FeedbackSessionProvider initialSession={savedSession} canResolveSession>
1088
+ <CommentContextProvider
1089
+ initialComments={savedSession.comments}
1090
+ initialOverlayState="idle"
1091
+ onError={handleError}
1092
+ >
1093
+ {/* ... */}
1094
+ </CommentContextProvider>
1095
+ </FeedbackSessionProvider>
1096
+ ```
1097
+
1098
+ `initialComments` is optional. Without it, the provider starts with `initialSession.comments`.
878
1099
 
1100
+ ### With Real-time Subscription
1101
+
1102
+ ```tsx
879
1103
  function App() {
880
1104
  const [subscription, setSubscription] = useState(null);
881
-
1105
+
882
1106
  useEffect(() => {
883
1107
  // Example with a WebSocket or real-time database
884
- const sub = {
885
- subscribe: (callback) => {
886
- socket.on('comments:update', callback);
887
- },
888
- unsubscribe: () => {
889
- socket.off('comments:update');
890
- },
891
- };
892
-
893
- setSubscription(sub);
1108
+ setSubscription({
1109
+ subscribe: (callback) => socket.on('comments:update', callback),
1110
+ unsubscribe: () => socket.off('comments:update'),
1111
+ });
894
1112
  }, []);
895
-
1113
+
896
1114
  return (
897
- <CommentContextProvider
898
- currentUser={currentUser}
899
- subscription={subscription}
900
- onConfirm={saveComments}
901
- onResolve={resolveComments}
902
- onError={(error) => console.error(error)}
903
- >
904
- {/* ... */}
905
- </CommentContextProvider>
1115
+ <FeedbackSessionProvider onCreateSession={createSession}>
1116
+ <CommentContextProvider
1117
+ currentUser={currentUser}
1118
+ subscription={subscription}
1119
+ onAdd={saveComment}
1120
+ onError={(error) => console.error(error)}
1121
+ >
1122
+ {/* ... */}
1123
+ </CommentContextProvider>
1124
+ </FeedbackSessionProvider>
906
1125
  );
907
1126
  }
908
1127
  ```
@@ -910,61 +1129,45 @@ function App() {
910
1129
  ### Custom Toolbar with Visibility Controls
911
1130
 
912
1131
  ```tsx
913
- import { useComments } from '@kendew-agency/react-feedback-layer';
1132
+ import { useComments, useFeedbackSession } from '@kendew-agency/react-feedback-layer';
914
1133
 
915
1134
  function CommentToolbar() {
916
- const {
917
- draftComments,
918
- resolvingComments,
919
- config,
920
- updateCommentVisibility,
921
- confirmComments,
922
- resolveComments,
923
- overlayState,
924
- } = useComments();
925
-
1135
+ const { draftComments, resolvedComments, config, updateCommentVisibility } =
1136
+ useComments();
1137
+ const { session, sessionState, confirmSession, startResolving, resolveSession } =
1138
+ useFeedbackSession();
1139
+
926
1140
  return (
927
1141
  <div className="toolbar">
928
1142
  <div className="stats">
1143
+ <span>Session: {session?.status ?? 'none'}</span>
929
1144
  <span>{draftComments.length} drafts</span>
930
- <span>{resolvingComments.length} resolving</span>
1145
+ <span>{resolvedComments.length} resolved</span>
931
1146
  </div>
932
-
933
- <div className="visibility">
934
- <label>
935
- <input
936
- type="checkbox"
937
- checked={!config?.commentVisibility?.hideResolved}
938
- onChange={(e) =>
939
- updateCommentVisibility({ hideResolved: !e.target.checked })
940
- }
941
- />
942
- Show Resolved
943
- </label>
944
- <label>
945
- <input
946
- type="checkbox"
947
- checked={!config?.commentVisibility?.hideResolving}
948
- onChange={(e) =>
949
- updateCommentVisibility({ hideResolving: !e.target.checked })
950
- }
951
- />
952
- Show Resolving
953
- </label>
954
- </div>
955
-
1147
+
1148
+ <label>
1149
+ <input
1150
+ type="checkbox"
1151
+ checked={!config?.commentVisibility?.hideResolved}
1152
+ onChange={(e) =>
1153
+ updateCommentVisibility({ hideResolved: !e.target.checked })
1154
+ }
1155
+ />
1156
+ Show Resolved
1157
+ </label>
1158
+
956
1159
  <div className="actions">
957
- <button
958
- onClick={confirmComments}
959
- disabled={draftComments.length === 0 || overlayState === 'saving'}
1160
+ <button
1161
+ onClick={confirmSession}
1162
+ disabled={session?.status !== 'draft' || sessionState !== 'idle'}
960
1163
  >
961
- {overlayState === 'saving' ? 'Saving...' : 'Save Comments'}
1164
+ {sessionState === 'confirming' ? 'Confirming...' : 'Confirm session'}
962
1165
  </button>
963
- <button
964
- onClick={resolveComments}
965
- disabled={resolvingComments.length === 0}
966
- >
967
- Resolve All
1166
+ <button onClick={startResolving} disabled={session?.status !== 'confirmed'}>
1167
+ Start resolving
1168
+ </button>
1169
+ <button onClick={resolveSession} disabled={session?.status !== 'resolving'}>
1170
+ Resolve session
968
1171
  </button>
969
1172
  </div>
970
1173
  </div>
@@ -988,7 +1191,7 @@ function CustomComment({ comment }) {
988
1191
  Save Comment
989
1192
  </MyCustomButton>
990
1193
  </Comment.Confirm>
991
-
1194
+
992
1195
  {/* Render content as a div */}
993
1196
  <Comment.Content asChild>
994
1197
  <div className="rich-text-content" />
@@ -1000,97 +1203,83 @@ function CustomComment({ comment }) {
1000
1203
 
1001
1204
  ## Configuration Options
1002
1205
 
1003
- The `config` prop allows you to customize various aspects of the comment system:
1206
+ The `config` prop of `CommentContextProvider` customizes the comment layer.
1004
1207
 
1005
1208
  ### ID Prefix
1006
1209
 
1007
- Add a custom prefix to all comment IDs:
1008
-
1009
1210
  ```tsx
1010
- <CommentContextProvider
1011
- config={{
1012
- idPrefix: 'proj_a_', // Results in IDs like "proj_a_uuid"
1013
- }}
1014
- // ... other props
1015
- >
1211
+ <CommentContextProvider config={{ idPrefix: 'proj_a_' }} /* "proj_a_uuid" */>
1016
1212
  ```
1017
1213
 
1018
1214
  ### Indicator Visibility
1019
1215
 
1020
- Control when comment indicators (selection boxes) are shown:
1021
-
1022
1216
  ```tsx
1023
1217
  <CommentContextProvider
1024
1218
  config={{
1025
1219
  indicatorVisibility: 'active', // Only show when comment is active
1026
- // or 'always' to always show indicators
1220
+ // or 'always' (default)
1027
1221
  }}
1028
- // ... other props
1029
1222
  >
1030
1223
  ```
1031
1224
 
1032
1225
  ### Comment Visibility
1033
1226
 
1034
- Hide specific types of comments from the UI:
1227
+ Hide resolved comments from the UI:
1035
1228
 
1036
1229
  ```tsx
1037
1230
  <CommentContextProvider
1038
- config={{
1039
- commentVisibility: {
1040
- hideResolved: true, // Hide resolved comments
1041
- hideResolving: false, // Show resolving comments
1042
- },
1043
- }}
1044
- // ... other props
1231
+ config={{ commentVisibility: { hideResolved: true } }}
1045
1232
  >
1046
1233
  ```
1047
1234
 
1048
- You can also update visibility dynamically:
1235
+ Update it dynamically:
1049
1236
 
1050
1237
  ```tsx
1051
1238
  function VisibilityControls() {
1052
1239
  const { config, updateCommentVisibility } = useComments();
1053
-
1240
+
1054
1241
  return (
1055
- <div>
1056
- <label>
1057
- <input
1058
- type="checkbox"
1059
- checked={!config?.commentVisibility?.hideResolved}
1060
- onChange={(e) =>
1061
- updateCommentVisibility({ hideResolved: !e.target.checked })
1062
- }
1063
- />
1064
- Show Resolved Comments
1065
- </label>
1066
- </div>
1242
+ <label>
1243
+ <input
1244
+ type="checkbox"
1245
+ checked={!config?.commentVisibility?.hideResolved}
1246
+ onChange={(e) =>
1247
+ updateCommentVisibility({ hideResolved: !e.target.checked })
1248
+ }
1249
+ />
1250
+ Show Resolved Comments
1251
+ </label>
1067
1252
  );
1068
1253
  }
1069
1254
  ```
1070
1255
 
1256
+ ### Draft Visibility
1257
+
1258
+ See [Draft visibility](#draft-visibility). Default `"visible"`, applies only while the session is a draft.
1259
+
1071
1260
  ## Advanced Patterns
1072
1261
 
1073
1262
  ### Project ID
1074
1263
 
1075
- Attach a project ID to all comments created within an overlay. This is useful for multi-project setups where you need to associate comments with a specific project in your database.
1264
+ Set `projectId` on `FeedbackSessionProvider` to send it to `onCreateSession`, and on `CommentContextProvider` to attach it to every new comment.
1076
1265
 
1077
1266
  ```tsx
1078
- <CommentContextProvider
1079
- currentUser={currentUser}
1267
+ <FeedbackSessionProvider
1080
1268
  projectId="proj_123456789"
1081
- onConfirm={async (comments, projectId) => {
1082
- // projectId is passed through to your callback
1083
- await api.createComments(comments, projectId);
1084
- }}
1085
- onResolve={resolveComments}
1086
- onError={handleError}
1269
+ onCreateSession={({ projectId, user, type }) =>
1270
+ api.createSession({ projectId, user, type })
1271
+ }
1087
1272
  >
1088
- {children}
1089
- </CommentContextProvider>
1273
+ <CommentContextProvider
1274
+ projectId="proj_123456789"
1275
+ onAdd={(comment) => api.addComment(comment)} // comment.projectId is set
1276
+ onError={handleError}
1277
+ >
1278
+ {children}
1279
+ </CommentContextProvider>
1280
+ </FeedbackSessionProvider>
1090
1281
  ```
1091
1282
 
1092
- Each comment created within this provider will have the `projectId` field set, which you can use for filtering and organizing comments per project.
1093
-
1094
1283
  ### Programmatic Comment Creation
1095
1284
 
1096
1285
  ```tsx
@@ -1098,18 +1287,18 @@ import { useComments } from '@kendew-agency/react-feedback-layer';
1098
1287
 
1099
1288
  function CustomTool() {
1100
1289
  const { registerComment } = useComments();
1101
-
1290
+
1102
1291
  const addCommentAtElement = (elementId: string) => {
1103
1292
  const element = document.getElementById(elementId);
1104
1293
  if (!element) return;
1105
-
1294
+
1106
1295
  const rect = element.getBoundingClientRect();
1107
1296
  registerComment(
1108
1297
  { x: rect.right, y: rect.bottom },
1109
1298
  { width: rect.width, height: rect.height }
1110
1299
  );
1111
1300
  };
1112
-
1301
+
1113
1302
  return (
1114
1303
  <button onClick={() => addCommentAtElement('target-element')}>
1115
1304
  Comment on Element
@@ -1118,68 +1307,59 @@ function CustomTool() {
1118
1307
  }
1119
1308
  ```
1120
1309
 
1121
- ### Error Handling
1122
-
1123
- The `onError` callback is required and handles all error types, including overlay interaction errors like attempting to add a comment while editing or dismissing an empty comment.
1310
+ `registerComment` needs a `draft` session. Otherwise `onError` receives a `SessionStateError`.
1124
1311
 
1125
- **1. Using the `onError` callback:**
1126
-
1127
- ```tsx
1128
- <CommentContextProvider
1129
- currentUser={currentUser}
1130
- onConfirm={saveComments}
1131
- onResolve={resolveComments}
1132
- onError={(error) => {
1133
- console.error('Comment operation failed:', error.code, error.message);
1134
- toast.error(error.message);
1135
- }}
1136
- >
1137
- {children}
1138
- </CommentContextProvider>
1139
- ```
1312
+ ### Error Handling
1140
1313
 
1141
- **2. Handling errors from action results:**
1314
+ Both providers accept an optional `onError`. Every failure is reported there, including overlay interaction errors such as adding a comment while editing. Every action also returns `{ error }`.
1142
1315
 
1143
1316
  ```tsx
1144
- import { useComments } from '@kendew-agency/react-feedback-layer';
1317
+ function ConfirmButton() {
1318
+ const { confirmSession, sessionState } = useFeedbackSession();
1145
1319
 
1146
- function SaveButton() {
1147
- const { confirmComments, overlayState } = useComments();
1148
-
1149
- const handleSave = async () => {
1150
- const { error } = await confirmComments();
1151
-
1320
+ const handleConfirm = async () => {
1321
+ const { error } = await confirmSession();
1152
1322
  if (error) {
1153
- console.error('Failed to save comments:', error);
1154
- alert('Failed to save comments. Please try again.');
1155
- } else {
1156
- alert('Comments saved successfully!');
1323
+ alert(`Failed to confirm: ${error.message}`);
1157
1324
  }
1158
1325
  };
1159
-
1326
+
1160
1327
  return (
1161
- <button
1162
- onClick={handleSave}
1163
- disabled={overlayState === 'saving'}
1164
- >
1165
- {overlayState === 'saving' ? 'Saving...' : 'Save Comments'}
1328
+ <button onClick={handleConfirm} disabled={sessionState === 'confirming'}>
1329
+ {sessionState === 'confirming' ? 'Confirming...' : 'Confirm session'}
1166
1330
  </button>
1167
1331
  );
1168
1332
  }
1169
1333
  ```
1170
1334
 
1171
1335
  #### Error codes
1172
- To keep track of the origin of a comment an error code is provided. You can use this code to display a more accurate error message. For example:
1336
+
1337
+ | Code | Error class | Origin |
1338
+ |------|-------------|--------|
1339
+ | `SESSION_CREATE_ERROR` | `SessionCreateError` | `createSession` or `onCreateSession` failed |
1340
+ | `CONFIRM_ERROR` | `ConfirmError` | `onConfirmSession` failed |
1341
+ | `START_RESOLVING_ERROR` | `StartResolvingError` | `onStartResolving` failed |
1342
+ | `SESSION_RESOLVE_ERROR` | `SessionResolveError` | `onResolveSession` failed |
1343
+ | `SESSION_STATE_ERROR` | `SessionStateError` | The action is not allowed in the current session state |
1344
+ | `PERMISSION_ERROR` | `PermissionError` | `canResolveSession` is `false` |
1345
+ | `ADD_ERROR` | `AddError` | `onAdd` failed or the content is empty |
1346
+ | `EDIT_ERROR` | `EditError` | `onEdit` failed |
1347
+ | `DELETE_ERROR` | `DeleteError` | `onDelete` failed |
1348
+ | `RESOLVE_ERROR` | `ResolveError` | `onResolve` failed |
1349
+ | `REOPEN_ERROR` | `ReopenError` | `onReopen` failed |
1350
+ | `INSERT_ERROR` | `InsertError` | The overlay refused to add a comment |
1351
+ | `UNKNOWN_ERROR` | `UnknownError` | Anything else |
1352
+
1173
1353
  ```ts
1174
- switch(e.code){
1175
- case "RESOLVE_ERROR":
1176
- alert('Failed to resolve your comments')
1354
+ switch (error.code) {
1355
+ case "PERMISSION_ERROR":
1356
+ alert('You are not allowed to do this')
1177
1357
  break
1178
- case "CONFIRM_ERROR":
1179
- alert('Failed to submit your comments')
1358
+ case "SESSION_STATE_ERROR":
1359
+ alert('This is not possible in the current session state')
1180
1360
  break
1181
- case "INSERT_ERROR":
1182
- alert('Failed to insert your comment')
1361
+ case "CONFIRM_ERROR":
1362
+ alert('Failed to confirm your session')
1183
1363
  break
1184
1364
  default:
1185
1365
  alert('An unknown error occured')
@@ -1221,6 +1401,62 @@ function CommentList() {
1221
1401
  }
1222
1402
  ```
1223
1403
 
1404
+ ## Migrating from 0.3.x
1405
+
1406
+ Comments now live in feedback sessions, so the batch confirm and resolve flow is gone. Each removed API maps to a replacement:
1407
+
1408
+ | Removed | Replacement |
1409
+ |---------|-------------|
1410
+ | `confirmComments()` from `useComments()` | `confirmSession()` from `useFeedbackSession()` |
1411
+ | `resolveComments()` from `useComments()` | `resolveComment(id)` per comment, then `resolveSession()` from `useFeedbackSession()` |
1412
+ | `onConfirm(comments, projectId)` on `CommentContextProvider` | `onAdd(comment)` per comment on `CommentContextProvider`, and `onConfirmSession(sessionId, type)` on `FeedbackSessionProvider` |
1413
+ | `onResolve(comments[])` on `CommentContextProvider` | `onResolve(comment)` for a single comment on `CommentContextProvider`, and `onResolveSession(sessionId)` on `FeedbackSessionProvider` |
1414
+ | `<ConfirmComments />` | `<ConfirmSession />` |
1415
+ | `<ResolveComments />` | `<ResolveSession />`, and `<Comment.Resolve />` per comment |
1416
+ | `events.onCommentsConfirmed` | `events.onCommentAdded` (per comment) and `useFeedbackSession().events.onSessionConfirmed` |
1417
+ | `events.onCommentsResolved` | `events.onCommentResolved` (per comment) and `useFeedbackSession().events.onSessionResolved` |
1418
+ | `toggleResolvingComment(id)` | `startResolving()` for the session, then `resolveComment(id)` and `reopenComment(id)` |
1419
+
1420
+ Other breaking changes:
1421
+
1422
+ - **A session provider is required.** `CommentContextProvider` and `useComments()` throw without a `FeedbackSessionProvider`. Using the comment layer standalone, without a session provider, is no longer possible.
1423
+ - **The `resolving` comment status is removed.** `CommentType["status"]` is now `"draft" | "published" | "resolved"`. The resolving phase belongs to the session (`SessionStatus` `"resolving"`).
1424
+ - **`resolvingComments` is removed** from `useComments()`.
1425
+ - **The `hideResolving` filter is removed** from `CommentVisibility` and `config.commentVisibility`. Only `hideResolved` remains.
1426
+ - **The `ResolvingComment` prop is removed** from `CommentRenderer`. Pass `Comment`, `DraftComment` and `ResolvedComment`.
1427
+ - **`initialComments` need a `sessionId`** equal to the `initialSession` id. Comments of another session are not shown, and without an active session no comments are shown.
1428
+ - **`CommentType` has a required `sessionId`** field.
1429
+ - **`onError` is optional** on both providers.
1430
+
1431
+ Before:
1432
+
1433
+ ```tsx
1434
+ <CommentContextProvider
1435
+ currentUser={user}
1436
+ onConfirm={(comments, projectId) => api.createComments(comments, projectId)}
1437
+ onResolve={(comments) => api.resolveComments(comments)}
1438
+ onError={handleError}
1439
+ >
1440
+ ```
1441
+
1442
+ After:
1443
+
1444
+ ```tsx
1445
+ <FeedbackSessionProvider
1446
+ canResolveSession={isReviewer}
1447
+ onCreateSession={api.createSession}
1448
+ onConfirmSession={(sessionId) => api.confirmSession(sessionId)}
1449
+ onResolveSession={(sessionId) => api.resolveSession(sessionId)}
1450
+ onError={handleError}
1451
+ >
1452
+ <CommentContextProvider
1453
+ currentUser={user}
1454
+ onAdd={(comment) => api.addComment(comment)}
1455
+ onResolve={(comment) => api.resolveComment(comment)}
1456
+ onError={handleError}
1457
+ >
1458
+ ```
1459
+
1224
1460
  ## Styling
1225
1461
 
1226
1462
  This library is completely unstyled (headless). Here's a basic CSS example to get started:
@@ -1301,6 +1537,7 @@ const comment: CommentType = {
1301
1537
  user,
1302
1538
  createdAt: new Date(),
1303
1539
  status: 'published',
1540
+ sessionId: 'session-1',
1304
1541
  };
1305
1542
  ```
1306
1543
 
@@ -1350,6 +1587,14 @@ MIT © [Kendew Agency](https://github.com/Kendew-Agency)
1350
1587
 
1351
1588
  A list if breaking changes that could impact the way you configured the package
1352
1589
 
1590
+ ### Unreleased
1591
+
1592
+ - Added feedback sessions. See [Feedback Sessions](#feedback-sessions) and the [migration guide](#migrating-from-03x). `FeedbackSessionProvider` is now required around `CommentContextProvider`.
1593
+ - Added `FeedbackSessionProvider`, `UserProvider`, `useFeedbackSession()`, `useCurrentUser()`, `CreateSession`, `ConfirmSession`, `StartResolving`, `ResolveSession` and `Comment.Reopen`.
1594
+ - Added the `onAdd`, `onEdit`, `onDelete` and `onReopen` callbacks, a single-comment `onResolve`, `resolveComment`, `reopenComment`, `canResolve` and the `config.draftVisibility` option.
1595
+ - Added the session events `onSessionCreated`, `onSessionConfirmed`, `onSessionResolving` and `onSessionResolved`, and the comment events `onCommentAdded`, `onCommentEdited`, `onCommentResolved` and `onCommentReopened`.
1596
+ - Breaking: removed `confirmComments`, `resolveComments`, `onConfirm`, array `onResolve`, `ConfirmComments`, `ResolveComments`, `onCommentsConfirmed` and `onCommentsResolved`. Removed the `resolving` comment status, `resolvingComments`, the `hideResolving` filter and the `ResolvingComment` renderer prop. Standalone use without a session provider is no longer possible. `initialComments` need a `sessionId` equal to the `initialSession` id.
1597
+
1353
1598
  ### 0.3.2
1354
1599
  - Added `withPosition` prop to `Comment.Root`. It defaults to `true`, so existing behavior is unchanged. Set it to `false` to skip the absolute positioning styles (`position`, `top`, `left`), for example when rendering comments in a list.
1355
1600