-
-
Notifications
You must be signed in to change notification settings - Fork 340
Expand file tree
/
Copy pathDocFeedbackNote.tsx
More file actions
510 lines (469 loc) · 16.1 KB
/
DocFeedbackNote.tsx
File metadata and controls
510 lines (469 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
import * as React from 'react'
import { twMerge } from 'tailwind-merge'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import {
deleteDocFeedback,
updateDocFeedback,
updateDocFeedbackCollapsed,
} from '~/utils/docFeedback.functions'
import type { DocFeedback } from '~/db/types'
import {
ChevronDown,
ChevronUp,
Lightbulb,
MessageSquare,
Save,
Trash,
X,
} from 'lucide-react'
interface DocFeedbackNoteProps {
note: DocFeedback
anchorName: string
inline?: boolean
}
// Types for the query cache data structures
interface DocPageCacheData {
userFeedback: DocFeedback[]
}
interface AccountPageCacheData {
feedback: DocFeedback[]
}
type DocFeedbackCacheData = DocPageCacheData | AccountPageCacheData | unknown
export function DocFeedbackNote({
note,
anchorName,
inline = false,
}: DocFeedbackNoteProps) {
const queryClient = useQueryClient()
const [isDeleting, setIsDeleting] = React.useState(false)
const [deleteError, setDeleteError] = React.useState<string | null>(null)
const [content, setContent] = React.useState(note.content)
const [isSaving, setIsSaving] = React.useState(false)
const [saveError, setSaveError] = React.useState<string | null>(null)
const textareaRef = React.useRef<HTMLTextAreaElement>(null)
// Track if content has been modified
const hasChanges = content !== note.content
// Theme based on type
const isImprovement = note.type === 'improvement'
const Icon = isImprovement ? Lightbulb : MessageSquare
const colors = isImprovement
? {
bg: 'bg-yellow-50 dark:bg-yellow-900/20',
border: 'border-yellow-400 dark:border-yellow-600',
header: 'bg-yellow-100 dark:bg-yellow-900/30',
icon: 'text-yellow-600 dark:text-yellow-500 text-[14px]',
text: 'text-yellow-800 dark:text-yellow-300',
timestamp: 'text-yellow-700 dark:text-yellow-400',
deleteHover: 'hover:text-yellow-600 dark:hover:text-yellow-400',
}
: {
bg: 'bg-blue-50 dark:bg-blue-900/20',
border: 'border-blue-400 dark:border-blue-600',
header: 'bg-blue-100 dark:bg-blue-900/30',
icon: 'text-blue-600 dark:text-blue-500 text-[14px]',
text: 'text-blue-800 dark:text-blue-300',
timestamp: 'text-blue-700 dark:text-blue-400',
deleteHover: 'hover:text-blue-600 dark:hover:text-blue-400',
}
// Auto-resize textarea to fit content
React.useEffect(() => {
if (textareaRef.current && !note.isCollapsed) {
textareaRef.current.style.height = 'auto'
textareaRef.current.style.height = textareaRef.current.scrollHeight + 'px'
}
}, [content, note.isCollapsed])
// Extract first line for preview
const firstLine = note.content.split('\n')[0]
const preview =
firstLine.length > 60 ? firstLine.substring(0, 60) + '...' : firstLine
const deleteMutation = useMutation({
mutationFn: deleteDocFeedback,
onMutate: async () => {
// Cancel any outgoing refetches
await queryClient.cancelQueries({ queryKey: ['docFeedback'] })
// Snapshot the previous value
const previousData = queryClient.getQueriesData({
queryKey: ['docFeedback'],
})
// Optimistically remove the note from all matching queries
queryClient.setQueriesData(
{ queryKey: ['docFeedback'] },
(old: DocFeedbackCacheData) => {
if (!old || typeof old !== 'object') return old
// Handle doc page structure (userFeedback)
if ('userFeedback' in old && Array.isArray(old.userFeedback)) {
return {
...old,
userFeedback: old.userFeedback.filter(
(f: DocFeedback) => f.id !== note.id,
),
}
}
// Handle account/notes page structure (feedback)
if ('feedback' in old && Array.isArray(old.feedback)) {
return {
...old,
feedback: old.feedback.filter(
(f: DocFeedback) => f.id !== note.id,
),
}
}
return old
},
)
return { previousData }
},
onError: (error: Error, variables, context) => {
// Rollback on error
if (context?.previousData) {
context.previousData.forEach(([queryKey, data]) => {
queryClient.setQueryData(queryKey, data)
})
}
setDeleteError(error.message)
setIsDeleting(false)
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['docFeedback'] })
},
})
const updateMutation = useMutation({
mutationFn: updateDocFeedback,
onMutate: async (variables) => {
// Cancel any outgoing refetches
await queryClient.cancelQueries({ queryKey: ['docFeedback'] })
// Snapshot the previous value
const previousData = queryClient.getQueriesData({
queryKey: ['docFeedback'],
})
// Optimistically update the note content
queryClient.setQueriesData(
{ queryKey: ['docFeedback'] },
(old: DocFeedbackCacheData) => {
if (!old || typeof old !== 'object') return old
// Handle doc page structure (userFeedback)
if ('userFeedback' in old && Array.isArray(old.userFeedback)) {
return {
...old,
userFeedback: old.userFeedback.map((f: DocFeedback) =>
f.id === note.id
? {
...f,
content: variables.data.content,
updatedAt: new Date(),
}
: f,
),
}
}
// Handle account/notes page structure (feedback)
if ('feedback' in old && Array.isArray(old.feedback)) {
return {
...old,
feedback: old.feedback.map((f: DocFeedback) =>
f.id === note.id
? {
...f,
content: variables.data.content,
updatedAt: new Date(),
}
: f,
),
}
}
return old
},
)
return { previousData }
},
onSuccess: () => {
setIsSaving(false)
setSaveError(null)
},
onError: (error: Error, variables, context) => {
// Rollback on error
if (context?.previousData) {
context.previousData.forEach(([queryKey, data]) => {
queryClient.setQueryData(queryKey, data)
})
}
setSaveError(error.message)
setIsSaving(false)
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['docFeedback'] })
},
})
const collapsedMutation = useMutation({
mutationFn: updateDocFeedbackCollapsed,
onMutate: async (variables) => {
// Cancel any outgoing refetches
await queryClient.cancelQueries({ queryKey: ['docFeedback'] })
// Snapshot the previous value
const previousData = queryClient.getQueriesData({
queryKey: ['docFeedback'],
})
// Optimistically toggle collapsed state
queryClient.setQueriesData(
{ queryKey: ['docFeedback'] },
(old: DocFeedbackCacheData) => {
if (!old || typeof old !== 'object') return old
// Handle doc page structure (userFeedback)
if ('userFeedback' in old && Array.isArray(old.userFeedback)) {
return {
...old,
userFeedback: old.userFeedback.map((f: DocFeedback) =>
f.id === note.id
? { ...f, isCollapsed: variables.data.isCollapsed }
: f,
),
}
}
// Handle account/notes page structure (feedback)
if ('feedback' in old && Array.isArray(old.feedback)) {
return {
...old,
feedback: old.feedback.map((f: DocFeedback) =>
f.id === note.id
? { ...f, isCollapsed: variables.data.isCollapsed }
: f,
),
}
}
return old
},
)
return { previousData }
},
onError: (error, variables, context) => {
// Rollback on error
if (context?.previousData) {
context.previousData.forEach(([queryKey, data]) => {
queryClient.setQueryData(queryKey, data)
})
}
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['docFeedback'] })
},
})
const handleToggle = () => {
collapsedMutation.mutate({
data: {
feedbackId: note.id,
isCollapsed: !note.isCollapsed,
},
})
}
const handleDelete = () => {
if (!isDeleting && confirm('Are you sure you want to delete this note?')) {
setIsDeleting(true)
setDeleteError(null)
deleteMutation.mutate({ data: { feedbackId: note.id } })
}
}
const handleSave = () => {
if (content.trim().length === 0) {
setSaveError('Note cannot be empty')
return
}
setIsSaving(true)
setSaveError(null)
updateMutation.mutate({
data: {
feedbackId: note.id,
content: content.trim(),
},
})
}
const handleCancel = () => {
setContent(note.content)
setSaveError(null)
}
const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setContent(e.target.value)
setSaveError(null)
}
return (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
<div
className={twMerge(
inline ? 'w-full' : 'fixed z-40 w-80 max-w-[calc(100vw-2rem)]',
'transition-all duration-200',
)}
style={
inline
? undefined
: {
positionAnchor: anchorName,
top: 'anchor(top)',
left: 'anchor(right)',
marginLeft: '0.5rem',
}
}
onClick={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
>
<div
className={twMerge(
colors.bg,
`border-r-4 ${colors.border}`,
'rounded-l-lg shadow-lg',
'overflow-hidden',
'transition-all duration-200',
isDeleting && 'opacity-50',
)}
>
{/* Error messages */}
{(deleteError || saveError) && (
<div className="m-2 p-2 rounded bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200 border border-red-200 dark:border-red-800 text-xs">
{deleteError || saveError}
</div>
)}
{/* Header - always visible */}
{/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
<div
className={twMerge(
`flex flex-col gap-1 p-2 ${colors.header}`,
note.isCollapsed &&
'cursor-pointer hover:opacity-80 transition-opacity',
)}
onClick={note.isCollapsed ? handleToggle : undefined}
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 flex-1 min-w-0">
<Icon className={`${colors.icon} text-xs flex-shrink-0`} />
<span className={`text-xs font-medium ${colors.text} truncate`}>
{isImprovement ? 'Your Improvement' : 'Your Note'}
</span>
{isImprovement && note.status && (
<span
className={twMerge(
'text-[10px] px-1.5 py-0.5 rounded font-medium uppercase tracking-wide flex-shrink-0',
note.status === 'approved' &&
'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400',
note.status === 'denied' &&
'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400',
note.status === 'pending' &&
'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400',
)}
>
{note.status}
</span>
)}
</div>
<div className="flex items-center gap-1 flex-shrink-0">
{!note.isCollapsed && (
<>
<button
onClick={(e) => {
e.stopPropagation()
handleDelete()
}}
className={`p-1 ${colors.icon} hover:text-red-600 dark:hover:text-red-400 transition-colors disabled:opacity-50`}
title={isImprovement ? 'Delete improvement' : 'Delete note'}
disabled={isDeleting || isSaving}
>
<Trash className="text-xs" />
</button>
</>
)}
<button
onClick={(e) => {
e.stopPropagation()
handleToggle()
}}
className={`p-1 ${colors.icon} ${colors.deleteHover} transition-colors`}
title={
note.isCollapsed
? `Expand ${isImprovement ? 'improvement' : 'note'}`
: `Collapse ${isImprovement ? 'improvement' : 'note'}`
}
>
{note.isCollapsed ? (
<ChevronDown className="text-xs" />
) : (
<ChevronUp className="text-xs" />
)}
</button>
</div>
</div>
{/* Preview when collapsed */}
{note.isCollapsed && (
<div className={`text-xs ${colors.text} opacity-70 truncate`}>
{preview}
</div>
)}
</div>
{/* Content - collapsible */}
{!note.isCollapsed && (
<div className="p-3">
{/* Editable textarea */}
<textarea
ref={textareaRef}
value={content}
onChange={handleContentChange}
className={twMerge(
'w-full px-0 py-0',
'bg-transparent',
'border-none',
'text-sm text-gray-800 dark:text-gray-200',
'focus:outline-none',
'resize-none overflow-hidden',
'whitespace-pre-wrap',
)}
disabled={isSaving || isDeleting}
/>
{/* Action buttons when content changes */}
{hasChanges && (
<div className="flex items-center gap-2 mt-2">
<button
onClick={handleSave}
className={twMerge(
'px-3 py-1 text-xs font-medium rounded',
'bg-blue-600 text-white',
'hover:bg-blue-700',
'disabled:opacity-50 disabled:cursor-not-allowed',
'transition-colors duration-150',
'flex items-center gap-1',
)}
disabled={isSaving}
>
<Save className="text-[10px]" />
{isSaving ? 'Saving...' : 'Save'}
</button>
<button
onClick={handleCancel}
className="px-3 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white disabled:opacity-50"
disabled={isSaving}
>
<X className="inline text-[10px] mr-1" />
Cancel
</button>
</div>
)}
{/* Timestamp and Points */}
<div
className={`mt-2 flex items-center justify-between text-xs ${colors.timestamp}`}
>
<div>
{new Date(note.createdAt).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
})}
</div>
{isImprovement && (
<div className="font-medium">
<span className="text-blue-600 dark:text-blue-400">
{(note.content.length * 0.1).toFixed(1)} points
</span>
</div>
)}
</div>
</div>
)}
</div>
</div>
)
}