overleaf/services/web/frontend/js/features/review-panel-new/components/review-panel-add-comment.tsx
Alf Eaton e61eb1b220 Merge pull request #20008 from overleaf/ae-review-panel-empty-state
Improve calculations of empty state, mini state and sizes variables in review panel

GitOrigin-RevId: 41bcb3b67c9f0019c11b4de0e4590b0407e04e66
2024-08-22 14:01:16 +00:00

60 lines
1.9 KiB
TypeScript

import { FC, FormEventHandler, useCallback, useState } from 'react'
import {
useCodeMirrorStateContext,
useCodeMirrorViewContext,
} from '@/features/source-editor/components/codemirror-editor'
import { EditorSelection } from '@codemirror/state'
import { useTranslation } from 'react-i18next'
import { useThreadsActionsContext } from '../context/threads-context'
export const ReviewPanelAddComment: FC = () => {
const { t } = useTranslation()
const view = useCodeMirrorViewContext()
// eslint-disable-next-line no-unused-vars
const _state = useCodeMirrorStateContext()
const { addComment } = useThreadsActionsContext()
const [error, setError] = useState<Error>()
const [showForm, setShowForm] = useState(false)
const handleSubmit = useCallback<FormEventHandler>(
event => {
event.preventDefault()
const { from, to } = view.state.selection.main
const content = view.state.sliceDoc(from, to)
const formData = new FormData(event.target as HTMLFormElement)
const message = formData.get('message') as string
addComment(from, content, message).catch(setError)
view.dispatch({
selection: EditorSelection.cursor(view.state.selection.main.anchor),
})
},
[addComment, view]
)
const handleElement = useCallback((element: HTMLElement | null) => {
if (element) {
element.dispatchEvent(new Event('review-panel:position'))
}
}, [])
if (!showForm) {
return <button onClick={() => setShowForm(true)}>{t('add_comment')}</button>
}
return (
<form
onSubmit={handleSubmit}
className="review-panel-add-comment-form"
ref={handleElement}
>
{/* eslint-disable-next-line jsx-a11y/no-autofocus */}
<textarea name="message" rows={3} autoFocus />
<button type="submit">{t('comment')}</button>
{error && <div>{error.message}</div>}
</form>
)
}