@kendew-agency/react-feedback-layer 0.3.1 → 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
  ```
@@ -267,8 +395,9 @@ Container for a single comment with positioning and active state management.
267
395
  ```tsx
268
396
  interface CommentRootProps extends HTMLProps<HTMLDivElement> {
269
397
  comment: CommentType;
270
- children?: ReactNode;
271
398
  defaultDraft?: string; // Initial draft content
399
+ withPosition?: boolean; // Apply absolute positioning from comment.position (default: true)
400
+ children?: ReactNode;
272
401
  }
273
402
  ```
274
403
 
@@ -280,6 +409,16 @@ interface CommentRootProps extends HTMLProps<HTMLDivElement> {
280
409
  </Comment.Root>
281
410
  ```
282
411
 
412
+ **Rendering without positioning (e.g. in a list):**
413
+
414
+ Set `withPosition={false}` to skip the `position`, `top` and `left` styles derived from `comment.position`. Styles passed via `style` are still applied.
415
+
416
+ ```tsx
417
+ <Comment.Root comment={comment} withPosition={false}>
418
+ {/* Sub-components */}
419
+ </Comment.Root>
420
+ ```
421
+
283
422
  ##### `Comment.Indicator`
284
423
 
285
424
  Visual indicator showing the area a comment refers to (when created via drag).
@@ -377,7 +516,7 @@ interface CommentDeleteProps extends ButtonHTMLAttributes<HTMLButtonElement> {
377
516
 
378
517
  ##### `Comment.Resolve`
379
518
 
380
- 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.
381
520
 
382
521
  **Props:**
383
522
 
@@ -395,91 +534,182 @@ interface CommentResolveProps extends ButtonHTMLAttributes<HTMLButtonElement> {
395
534
  </Comment.Resolve>
396
535
  ```
397
536
 
398
- #### Action Components
537
+ ##### `Comment.Reopen`
399
538
 
400
- ##### `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.
401
540
 
402
- Toggles the comment overlay on/off.
541
+ ```tsx
542
+ <Comment.Reopen className="btn-reopen">Reopen</Comment.Reopen>
543
+ ```
403
544
 
404
- **Props:**
545
+ Hide both buttons for users that may not resolve by reading `canResolve` from `useComments()`:
405
546
 
406
547
  ```tsx
407
- interface CommentButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
408
- 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
+ );
409
556
  }
410
557
  ```
411
558
 
412
- **Example:**
559
+ #### Action Components
413
560
 
414
- ```tsx
415
- 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.
416
562
 
563
+ ##### `ToggleOverlayButton`
564
+
565
+ Toggles the comment overlay on/off. Sets `data-active` when the overlay is not inactive.
566
+
567
+ ```tsx
417
568
  <ToggleOverlayButton className="toggle-btn">
418
569
  Toggle Comments
419
570
  </ToggleOverlayButton>
420
571
  ```
421
572
 
422
- ##### `ConfirmComments`
573
+ ##### `CreateSession`, `ConfirmSession`, `StartResolving`, `ResolveSession`
423
574
 
424
- 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`.
425
576
 
426
- **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:**
427
591
 
428
592
  ```tsx
429
- 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
+ ```
430
621
 
431
- <ConfirmComments className="btn-save">
432
- Save All Comments
433
- </ConfirmComments>
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.
623
+
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
+ }
434
647
  ```
435
648
 
436
- ##### `ResolveComments`
649
+ #### Session events
437
650
 
438
- 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.
439
652
 
440
- **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` |
441
659
 
442
660
  ```tsx
443
- 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
+ );
444
674
 
445
- <ResolveComments className="btn-resolve-all">
446
- Resolve All
447
- </ResolveComments>
675
+ return null;
676
+ }
448
677
  ```
449
678
 
450
- ### Hooks
451
-
452
679
  #### `useComments()`
453
680
 
454
- Access the global comment context and actions.
681
+ Access the comment context and actions. Throws outside a `CommentContextProvider` (and outside a `FeedbackSessionProvider`).
455
682
 
456
683
  **Returns:**
457
684
 
458
685
  ```tsx
459
686
  interface CommentContext {
460
- // Filtered comment arrays
687
+ // Comments of the active session, after the draftVisibility filter
461
688
  draftComments: CommentType[];
462
689
  comments: CommentType[]; // Published comments
463
- resolvingComments: CommentType[];
464
690
  resolvedComments: CommentType[];
465
691
  allComments: CommentType[];
466
-
692
+
467
693
  // State
468
694
  overlayState: CommentOverlayState;
469
695
  currentUser: User | null;
470
696
  config: Config | undefined;
471
-
697
+ // Mirrors the canResolveSession prop of the session provider
698
+ canResolve: boolean;
699
+
472
700
  // Actions
473
701
  registerComment: (position: Position, indicatorPosition?: Indicator) => void;
474
- updateComment: (id: string, newComment: Pick<CommentType, "content">) => void;
475
- 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 }>;
476
709
  focusOnComment: (id: string | null) => void;
477
710
  getActiveComment: () => CommentType | undefined;
478
711
  toggleOverlay: () => void;
479
- toggleResolvingComment: (id: string) => void;
480
712
  changeOverlayState: (state: CommentOverlayState) => void;
481
- confirmComments: () => Promise<{ error: Error | DOMException | null }>;
482
- resolveComments: () => Promise<{ error: Error | DOMException | null }>;
483
713
  updateCommentVisibility: (visibility: Partial<CommentVisibility>) => void;
484
714
  triggerError: (error: KnownError) => void;
485
715
 
@@ -488,31 +718,22 @@ interface CommentContext {
488
718
  }
489
719
  ```
490
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
+
491
723
  **Example:**
492
724
 
493
725
  ```tsx
494
726
  import { useComments } from '@kendew-agency/react-feedback-layer';
495
727
 
496
728
  function CommentToolbar() {
497
- const {
498
- draftComments,
499
- confirmComments,
500
- overlayState,
501
- toggleOverlay,
502
- config
503
- } = useComments();
504
-
729
+ const { allComments, overlayState, toggleOverlay, config } = useComments();
730
+
505
731
  return (
506
732
  <div>
507
733
  <button onClick={toggleOverlay}>
508
734
  {overlayState === 'inactive' ? 'Enable' : 'Disable'} Comments
509
735
  </button>
510
- <button
511
- onClick={confirmComments}
512
- disabled={draftComments.length === 0}
513
- >
514
- Save {draftComments.length} Comments
515
- </button>
736
+ <span>{allComments.length} comments</span>
516
737
  {config?.commentVisibility && (
517
738
  <span>Resolved hidden: {config.commentVisibility.hideResolved ? 'Yes' : 'No'}</span>
518
739
  )}
@@ -536,14 +757,10 @@ interface CommentScope {
536
757
  }
537
758
  ```
538
759
 
539
- **Example:**
540
-
541
760
  ```tsx
542
- import { useCommentScope } from '@kendew-agency/react-feedback-layer';
543
-
544
761
  function CustomCommentContent() {
545
762
  const { comment, isActive, draft } = useCommentScope();
546
-
763
+
547
764
  return (
548
765
  <div className={isActive ? 'active' : ''}>
549
766
  <p>{draft}</p>
@@ -553,72 +770,34 @@ function CustomCommentContent() {
553
770
  }
554
771
  ```
555
772
 
556
- #### `events` (via `useComments()`)
557
-
558
- 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
559
774
 
560
- **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.
561
776
 
562
777
  | Event | Trigger | Callback Signature |
563
778
  |-------|---------|-------------------|
564
779
  | `onFocusChange` | Focus moves to a different comment | `(commentId: string \| null, comment: CommentType \| undefined) => void` |
565
- | `onCommentsConfirmed` | Draft comments are successfully saved | `(comments: CommentType[]) => void` |
566
- | `onCommentsResolved` | Comments are successfully resolved | `(comments: CommentType[]) => void` |
567
- | `onCommentDeleted` | A comment is deleted | `(commentId: string) => void` |
568
780
  | `onCommentRegistered` | A new draft comment is created | `(comment: CommentType) => void` |
569
-
570
- **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` |
571
786
 
572
787
  ```tsx
573
- import { useComments } from '@kendew-agency/react-feedback-layer';
574
- import { useEffect } from 'react';
575
-
576
788
  function CommentTracker() {
577
789
  const { events } = useComments();
578
790
 
579
- useEffect(() => {
580
- const unsubscribe = events.onFocusChange((commentId, comment) => {
581
- console.log('Focus changed to:', commentId);
582
- if (comment) {
583
- highlightElement(comment.position);
584
- }
585
- });
586
-
587
- return unsubscribe;
588
- }, [events]);
589
-
590
- useEffect(() => {
591
- const unsubscribe = events.onCommentsConfirmed((comments) => {
592
- console.log(`${comments.length} comments saved`);
593
- toast.success('Comments saved successfully!');
594
- });
595
-
596
- return unsubscribe;
597
- }, [events]);
598
-
599
- return null;
600
- }
601
- ```
602
-
603
- **Multiple Subscriptions:**
604
-
605
- ```tsx
606
- function AnalyticsTracker() {
607
- const { events } = useComments();
608
-
609
791
  useEffect(() => {
610
792
  const unsubs = [
611
- events.onCommentRegistered((comment) => {
612
- analytics.track('comment_created', {
613
- position: comment.position,
614
- user: comment.user?.name,
615
- });
793
+ events.onCommentAdded((comment) => {
794
+ analytics.track('comment_added', { id: comment.id });
616
795
  }),
617
- events.onCommentsConfirmed((comments) => {
618
- analytics.track('comments_confirmed', { count: comments.length });
796
+ events.onCommentResolved((comment) => {
797
+ toast.success(`Resolved: ${comment.content}`);
619
798
  }),
620
- events.onCommentsResolved((comments) => {
621
- analytics.track('comments_resolved', { count: comments.length });
799
+ events.onCommentReopened((comment) => {
800
+ toast(`Reopened: ${comment.content}`);
622
801
  }),
623
802
  events.onCommentDeleted((id) => {
624
803
  analytics.track('comment_deleted', { commentId: id });
@@ -632,58 +811,42 @@ function AnalyticsTracker() {
632
811
  }
633
812
  ```
634
813
 
635
- **Syncing with External State:**
636
-
637
- ```tsx
638
- function CommentSidebar() {
639
- const { events, allComments } = useComments();
640
- const [activeId, setActiveId] = useState<string | null>(null);
641
-
642
- useEffect(() => {
643
- return events.onFocusChange((commentId) => {
644
- setActiveId(commentId);
645
- // Scroll sidebar to the active comment
646
- if (commentId) {
647
- document.getElementById(`sidebar-${commentId}`)?.scrollIntoView({
648
- behavior: 'smooth',
649
- });
650
- }
651
- });
652
- }, [events]);
653
-
654
- return (
655
- <aside className="comment-sidebar">
656
- {allComments.map((comment) => (
657
- <div
658
- key={comment.id}
659
- id={`sidebar-${comment.id}`}
660
- className={comment.id === activeId ? 'active' : ''}
661
- >
662
- <p>{comment.content}</p>
663
- <small>{comment.user?.name}</small>
664
- </div>
665
- ))}
666
- </aside>
667
- );
668
- }
669
- ```
670
-
671
- **Type Definitions:**
814
+ Type definitions:
672
815
 
673
816
  ```tsx
674
817
  import type {
675
818
  CommentEvents,
676
819
  CommentEventMap,
820
+ SessionEvents,
821
+ SessionEventMap,
677
822
  Unsubscribe,
678
823
  } from '@kendew-agency/react-feedback-layer/types';
679
824
  ```
680
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
+
681
844
  ### Types
682
845
 
683
846
  Import types from the `/types` subpath:
684
847
 
685
848
  ```tsx
686
- import type {
849
+ import type {
687
850
  CommentType,
688
851
  ConfirmedComment,
689
852
  User,
@@ -691,8 +854,16 @@ import type {
691
854
  Indicator,
692
855
  CommentOverlayState,
693
856
  CommentVisibility,
694
- CommentAction,
695
- Config
857
+ DraftVisibility,
858
+ Config,
859
+ FeedbackSession,
860
+ ActiveFeedbackSession,
861
+ InitialFeedbackSession,
862
+ SessionStatus,
863
+ SessionType,
864
+ SessionOperationState,
865
+ CreateSessionInput,
866
+ KnownError,
696
867
  } from '@kendew-agency/react-feedback-layer/types';
697
868
  ```
698
869
 
@@ -706,12 +877,50 @@ type CommentType = {
706
877
  user: User | null;
707
878
  createdAt: Date;
708
879
  resolvedAt?: Date;
709
- status: "draft" | "published" | "resolving" | "resolved";
880
+ status: "draft" | "published" | "resolved";
710
881
  indicator?: Indicator | null;
882
+ sessionId: string;
711
883
  projectId?: string;
712
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
+ };
713
890
  ```
714
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
+
715
924
  #### `User`
716
925
 
717
926
  ```tsx
@@ -745,7 +954,6 @@ type Indicator = {
745
954
  ```tsx
746
955
  type CommentVisibility = {
747
956
  hideResolved?: boolean;
748
- hideResolving?: boolean;
749
957
  };
750
958
  ```
751
959
 
@@ -755,10 +963,12 @@ type CommentVisibility = {
755
963
  type Config = {
756
964
  // Custom prefix for comment IDs
757
965
  idPrefix?: string;
758
- // Visibility of comment indicators
966
+ // Visibility of comment indicators (default: "always")
759
967
  indicatorVisibility?: "always" | "active";
760
968
  // Comment visibility settings
761
969
  commentVisibility?: CommentVisibility;
970
+ // Visibility of other users' comments in a draft session (default: "visible")
971
+ draftVisibility?: "hidden" | "visible";
762
972
  };
763
973
  ```
764
974
 
@@ -768,12 +978,15 @@ type Config = {
768
978
 
769
979
  ```tsx
770
980
  import {
981
+ Comment,
771
982
  CommentContextProvider,
772
983
  CommentOverlay,
773
984
  CommentRenderer,
774
- Comment,
985
+ ConfirmSession,
986
+ CreateSession,
987
+ FeedbackSessionProvider,
775
988
  ToggleOverlayButton,
776
- ConfirmComments,
989
+ useComments,
777
990
  } from '@kendew-agency/react-feedback-layer';
778
991
 
779
992
  function DraftComment({ comment }) {
@@ -792,6 +1005,8 @@ function DraftComment({ comment }) {
792
1005
  }
793
1006
 
794
1007
  function PublishedComment({ comment }) {
1008
+ const { canResolve } = useComments();
1009
+
795
1010
  return (
796
1011
  <Comment.Root comment={comment} className="published-comment">
797
1012
  <Comment.Indicator className="indicator" />
@@ -802,7 +1017,7 @@ function PublishedComment({ comment }) {
802
1017
  <span>{comment.createdAt.toLocaleDateString()}</span>
803
1018
  </div>
804
1019
  <div className="actions">
805
- <Comment.Resolve>Resolve</Comment.Resolve>
1020
+ {canResolve && <Comment.Resolve>Resolve</Comment.Resolve>}
806
1021
  <Comment.Delete>Delete</Comment.Delete>
807
1022
  </div>
808
1023
  </div>
@@ -810,88 +1025,103 @@ function PublishedComment({ comment }) {
810
1025
  );
811
1026
  }
812
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
+
813
1037
  function App() {
814
1038
  return (
815
- <CommentContextProvider
816
- currentUser={{ name: 'John Doe', id: '123' }}
817
- onConfirm={async (comments, projectId) => {
818
- const response = await fetch('/api/comments', {
1039
+ <FeedbackSessionProvider
1040
+ onCreateSession={async ({ type, user, projectId }) => {
1041
+ const response = await fetch('/api/sessions', {
819
1042
  method: 'POST',
820
- body: JSON.stringify({ comments, projectId }),
1043
+ body: JSON.stringify({ type, user, projectId }),
821
1044
  });
822
- if (!response.ok) {
823
- throw new Error('Failed to save comments');
824
- }
825
- }}
826
- onResolve={async (comments) => {
827
- const response = await fetch('/api/comments/resolve', {
828
- method: 'POST',
829
- body: JSON.stringify(comments),
830
- });
831
- if (!response.ok) {
832
- throw new Error('Failed to resolve comments');
833
- }
834
- }}
835
- onError={(error) => {
836
- console.error('Comment operation failed:', error);
837
- // Show user-friendly error message
1045
+ if (!response.ok) throw new Error('Failed to create session');
1046
+ return response.json();
838
1047
  }}
839
- config={{
840
- commentVisibility: {
841
- hideResolved: false,
842
- hideResolving: false,
843
- },
1048
+ onConfirmSession={async (sessionId) => {
1049
+ await fetch(`/api/sessions/${sessionId}/confirm`, { method: 'POST' });
844
1050
  }}
1051
+ onError={(error) => console.error(error.code, error.message)}
845
1052
  >
846
- <ToggleOverlayButton>Toggle Feedback Mode</ToggleOverlayButton>
847
- <ConfirmComments>Save All Comments</ConfirmComments>
848
-
849
- <CommentOverlay>
850
- <YourContent />
851
- <CommentRenderer
852
- Comment={PublishedComment}
853
- DraftComment={DraftComment}
854
- ResolvingComment={PublishedComment}
855
- ResolvedComment={PublishedComment}
856
- />
857
- </CommentOverlay>
858
- </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>
859
1078
  );
860
1079
  }
861
1080
  ```
862
1081
 
863
- ### 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.
864
1085
 
865
1086
  ```tsx
866
- 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
+ ```
867
1097
 
1098
+ `initialComments` is optional. Without it, the provider starts with `initialSession.comments`.
1099
+
1100
+ ### With Real-time Subscription
1101
+
1102
+ ```tsx
868
1103
  function App() {
869
1104
  const [subscription, setSubscription] = useState(null);
870
-
1105
+
871
1106
  useEffect(() => {
872
1107
  // Example with a WebSocket or real-time database
873
- const sub = {
874
- subscribe: (callback) => {
875
- socket.on('comments:update', callback);
876
- },
877
- unsubscribe: () => {
878
- socket.off('comments:update');
879
- },
880
- };
881
-
882
- setSubscription(sub);
1108
+ setSubscription({
1109
+ subscribe: (callback) => socket.on('comments:update', callback),
1110
+ unsubscribe: () => socket.off('comments:update'),
1111
+ });
883
1112
  }, []);
884
-
1113
+
885
1114
  return (
886
- <CommentContextProvider
887
- currentUser={currentUser}
888
- subscription={subscription}
889
- onConfirm={saveComments}
890
- onResolve={resolveComments}
891
- onError={(error) => console.error(error)}
892
- >
893
- {/* ... */}
894
- </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>
895
1125
  );
896
1126
  }
897
1127
  ```
@@ -899,61 +1129,45 @@ function App() {
899
1129
  ### Custom Toolbar with Visibility Controls
900
1130
 
901
1131
  ```tsx
902
- import { useComments } from '@kendew-agency/react-feedback-layer';
1132
+ import { useComments, useFeedbackSession } from '@kendew-agency/react-feedback-layer';
903
1133
 
904
1134
  function CommentToolbar() {
905
- const {
906
- draftComments,
907
- resolvingComments,
908
- config,
909
- updateCommentVisibility,
910
- confirmComments,
911
- resolveComments,
912
- overlayState,
913
- } = useComments();
914
-
1135
+ const { draftComments, resolvedComments, config, updateCommentVisibility } =
1136
+ useComments();
1137
+ const { session, sessionState, confirmSession, startResolving, resolveSession } =
1138
+ useFeedbackSession();
1139
+
915
1140
  return (
916
1141
  <div className="toolbar">
917
1142
  <div className="stats">
1143
+ <span>Session: {session?.status ?? 'none'}</span>
918
1144
  <span>{draftComments.length} drafts</span>
919
- <span>{resolvingComments.length} resolving</span>
920
- </div>
921
-
922
- <div className="visibility">
923
- <label>
924
- <input
925
- type="checkbox"
926
- checked={!config?.commentVisibility?.hideResolved}
927
- onChange={(e) =>
928
- updateCommentVisibility({ hideResolved: !e.target.checked })
929
- }
930
- />
931
- Show Resolved
932
- </label>
933
- <label>
934
- <input
935
- type="checkbox"
936
- checked={!config?.commentVisibility?.hideResolving}
937
- onChange={(e) =>
938
- updateCommentVisibility({ hideResolving: !e.target.checked })
939
- }
940
- />
941
- Show Resolving
942
- </label>
1145
+ <span>{resolvedComments.length} resolved</span>
943
1146
  </div>
944
-
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
+
945
1159
  <div className="actions">
946
- <button
947
- onClick={confirmComments}
948
- disabled={draftComments.length === 0 || overlayState === 'saving'}
1160
+ <button
1161
+ onClick={confirmSession}
1162
+ disabled={session?.status !== 'draft' || sessionState !== 'idle'}
949
1163
  >
950
- {overlayState === 'saving' ? 'Saving...' : 'Save Comments'}
1164
+ {sessionState === 'confirming' ? 'Confirming...' : 'Confirm session'}
951
1165
  </button>
952
- <button
953
- onClick={resolveComments}
954
- disabled={resolvingComments.length === 0}
955
- >
956
- 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
957
1171
  </button>
958
1172
  </div>
959
1173
  </div>
@@ -977,7 +1191,7 @@ function CustomComment({ comment }) {
977
1191
  Save Comment
978
1192
  </MyCustomButton>
979
1193
  </Comment.Confirm>
980
-
1194
+
981
1195
  {/* Render content as a div */}
982
1196
  <Comment.Content asChild>
983
1197
  <div className="rich-text-content" />
@@ -989,97 +1203,83 @@ function CustomComment({ comment }) {
989
1203
 
990
1204
  ## Configuration Options
991
1205
 
992
- The `config` prop allows you to customize various aspects of the comment system:
1206
+ The `config` prop of `CommentContextProvider` customizes the comment layer.
993
1207
 
994
1208
  ### ID Prefix
995
1209
 
996
- Add a custom prefix to all comment IDs:
997
-
998
1210
  ```tsx
999
- <CommentContextProvider
1000
- config={{
1001
- idPrefix: 'proj_a_', // Results in IDs like "proj_a_uuid"
1002
- }}
1003
- // ... other props
1004
- >
1211
+ <CommentContextProvider config={{ idPrefix: 'proj_a_' }} /* "proj_a_uuid" */>
1005
1212
  ```
1006
1213
 
1007
1214
  ### Indicator Visibility
1008
1215
 
1009
- Control when comment indicators (selection boxes) are shown:
1010
-
1011
1216
  ```tsx
1012
1217
  <CommentContextProvider
1013
1218
  config={{
1014
1219
  indicatorVisibility: 'active', // Only show when comment is active
1015
- // or 'always' to always show indicators
1220
+ // or 'always' (default)
1016
1221
  }}
1017
- // ... other props
1018
1222
  >
1019
1223
  ```
1020
1224
 
1021
1225
  ### Comment Visibility
1022
1226
 
1023
- Hide specific types of comments from the UI:
1227
+ Hide resolved comments from the UI:
1024
1228
 
1025
1229
  ```tsx
1026
1230
  <CommentContextProvider
1027
- config={{
1028
- commentVisibility: {
1029
- hideResolved: true, // Hide resolved comments
1030
- hideResolving: false, // Show resolving comments
1031
- },
1032
- }}
1033
- // ... other props
1231
+ config={{ commentVisibility: { hideResolved: true } }}
1034
1232
  >
1035
1233
  ```
1036
1234
 
1037
- You can also update visibility dynamically:
1235
+ Update it dynamically:
1038
1236
 
1039
1237
  ```tsx
1040
1238
  function VisibilityControls() {
1041
1239
  const { config, updateCommentVisibility } = useComments();
1042
-
1240
+
1043
1241
  return (
1044
- <div>
1045
- <label>
1046
- <input
1047
- type="checkbox"
1048
- checked={!config?.commentVisibility?.hideResolved}
1049
- onChange={(e) =>
1050
- updateCommentVisibility({ hideResolved: !e.target.checked })
1051
- }
1052
- />
1053
- Show Resolved Comments
1054
- </label>
1055
- </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>
1056
1252
  );
1057
1253
  }
1058
1254
  ```
1059
1255
 
1256
+ ### Draft Visibility
1257
+
1258
+ See [Draft visibility](#draft-visibility). Default `"visible"`, applies only while the session is a draft.
1259
+
1060
1260
  ## Advanced Patterns
1061
1261
 
1062
1262
  ### Project ID
1063
1263
 
1064
- 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.
1065
1265
 
1066
1266
  ```tsx
1067
- <CommentContextProvider
1068
- currentUser={currentUser}
1267
+ <FeedbackSessionProvider
1069
1268
  projectId="proj_123456789"
1070
- onConfirm={async (comments, projectId) => {
1071
- // projectId is passed through to your callback
1072
- await api.createComments(comments, projectId);
1073
- }}
1074
- onResolve={resolveComments}
1075
- onError={handleError}
1269
+ onCreateSession={({ projectId, user, type }) =>
1270
+ api.createSession({ projectId, user, type })
1271
+ }
1076
1272
  >
1077
- {children}
1078
- </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>
1079
1281
  ```
1080
1282
 
1081
- Each comment created within this provider will have the `projectId` field set, which you can use for filtering and organizing comments per project.
1082
-
1083
1283
  ### Programmatic Comment Creation
1084
1284
 
1085
1285
  ```tsx
@@ -1087,18 +1287,18 @@ import { useComments } from '@kendew-agency/react-feedback-layer';
1087
1287
 
1088
1288
  function CustomTool() {
1089
1289
  const { registerComment } = useComments();
1090
-
1290
+
1091
1291
  const addCommentAtElement = (elementId: string) => {
1092
1292
  const element = document.getElementById(elementId);
1093
1293
  if (!element) return;
1094
-
1294
+
1095
1295
  const rect = element.getBoundingClientRect();
1096
1296
  registerComment(
1097
1297
  { x: rect.right, y: rect.bottom },
1098
1298
  { width: rect.width, height: rect.height }
1099
1299
  );
1100
1300
  };
1101
-
1301
+
1102
1302
  return (
1103
1303
  <button onClick={() => addCommentAtElement('target-element')}>
1104
1304
  Comment on Element
@@ -1107,68 +1307,59 @@ function CustomTool() {
1107
1307
  }
1108
1308
  ```
1109
1309
 
1110
- ### Error Handling
1111
-
1112
- 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`.
1113
1311
 
1114
- **1. Using the `onError` callback:**
1115
-
1116
- ```tsx
1117
- <CommentContextProvider
1118
- currentUser={currentUser}
1119
- onConfirm={saveComments}
1120
- onResolve={resolveComments}
1121
- onError={(error) => {
1122
- console.error('Comment operation failed:', error.code, error.message);
1123
- toast.error(error.message);
1124
- }}
1125
- >
1126
- {children}
1127
- </CommentContextProvider>
1128
- ```
1312
+ ### Error Handling
1129
1313
 
1130
- **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 }`.
1131
1315
 
1132
1316
  ```tsx
1133
- import { useComments } from '@kendew-agency/react-feedback-layer';
1317
+ function ConfirmButton() {
1318
+ const { confirmSession, sessionState } = useFeedbackSession();
1134
1319
 
1135
- function SaveButton() {
1136
- const { confirmComments, overlayState } = useComments();
1137
-
1138
- const handleSave = async () => {
1139
- const { error } = await confirmComments();
1140
-
1320
+ const handleConfirm = async () => {
1321
+ const { error } = await confirmSession();
1141
1322
  if (error) {
1142
- console.error('Failed to save comments:', error);
1143
- alert('Failed to save comments. Please try again.');
1144
- } else {
1145
- alert('Comments saved successfully!');
1323
+ alert(`Failed to confirm: ${error.message}`);
1146
1324
  }
1147
1325
  };
1148
-
1326
+
1149
1327
  return (
1150
- <button
1151
- onClick={handleSave}
1152
- disabled={overlayState === 'saving'}
1153
- >
1154
- {overlayState === 'saving' ? 'Saving...' : 'Save Comments'}
1328
+ <button onClick={handleConfirm} disabled={sessionState === 'confirming'}>
1329
+ {sessionState === 'confirming' ? 'Confirming...' : 'Confirm session'}
1155
1330
  </button>
1156
1331
  );
1157
1332
  }
1158
1333
  ```
1159
1334
 
1160
1335
  #### Error codes
1161
- 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
+
1162
1353
  ```ts
1163
- switch(e.code){
1164
- case "RESOLVE_ERROR":
1165
- alert('Failed to resolve your comments')
1354
+ switch (error.code) {
1355
+ case "PERMISSION_ERROR":
1356
+ alert('You are not allowed to do this')
1166
1357
  break
1167
- case "CONFIRM_ERROR":
1168
- alert('Failed to submit your comments')
1358
+ case "SESSION_STATE_ERROR":
1359
+ alert('This is not possible in the current session state')
1169
1360
  break
1170
- case "INSERT_ERROR":
1171
- alert('Failed to insert your comment')
1361
+ case "CONFIRM_ERROR":
1362
+ alert('Failed to confirm your session')
1172
1363
  break
1173
1364
  default:
1174
1365
  alert('An unknown error occured')
@@ -1210,6 +1401,62 @@ function CommentList() {
1210
1401
  }
1211
1402
  ```
1212
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
+
1213
1460
  ## Styling
1214
1461
 
1215
1462
  This library is completely unstyled (headless). Here's a basic CSS example to get started:
@@ -1290,6 +1537,7 @@ const comment: CommentType = {
1290
1537
  user,
1291
1538
  createdAt: new Date(),
1292
1539
  status: 'published',
1540
+ sessionId: 'session-1',
1293
1541
  };
1294
1542
  ```
1295
1543
 
@@ -1339,6 +1587,17 @@ MIT © [Kendew Agency](https://github.com/Kendew-Agency)
1339
1587
 
1340
1588
  A list if breaking changes that could impact the way you configured the package
1341
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
+
1598
+ ### 0.3.2
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.
1600
+
1342
1601
  ### 0.3.1
1343
1602
  - Added `events` to the `useComments()` hook. You can now subscribe to comment lifecycle events such as `onFocusChange`, `onCommentsConfirmed`, `onCommentsResolved`, `onCommentDeleted`, and `onCommentRegistered`. Each event method returns an unsubscribe function for easy cleanup.
1344
1603
  - New types exported: `CommentEvents`, `CommentEventMap`, `Unsubscribe`.