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 { CaretDownIcon, CaretUpIcon, LightbulbIcon, ChatCenteredIcon, FloppyDiskIcon, TrashIcon, XIcon, } from '@phosphor-icons/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(null) const [content, setContent] = React.useState(note.content) const [isSaving, setIsSaving] = React.useState(false) const [saveError, setSaveError] = React.useState(null) const textareaRef = React.useRef(null) // Track if content has been modified const hasChanges = content !== note.content // Theme based on type const isImprovement = note.type === 'improvement' const Icon = isImprovement ? LightbulbIcon : ChatCenteredIcon 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) => { setContent(e.target.value) setSaveError(null) } return ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
e.stopPropagation()} onMouseDown={(e) => e.stopPropagation()} >
{/* Error messages */} {(deleteError || saveError) && (
{deleteError || saveError}
)} {/* Header - always visible */} {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
{isImprovement ? 'Your Improvement' : 'Your Note'} {isImprovement && note.status && ( {note.status} )}
{!note.isCollapsed && ( <> )}
{/* Preview when collapsed */} {note.isCollapsed && (
{preview}
)}
{/* Content - collapsible */} {!note.isCollapsed && (
{/* Editable textarea */}