diff --git a/worklenz-frontend/src/components/common/rich-comment-editor/RichCommentEditor.tsx b/worklenz-frontend/src/components/common/rich-comment-editor/RichCommentEditor.tsx index 54ef4d088..039c0fcac 100644 --- a/worklenz-frontend/src/components/common/rich-comment-editor/RichCommentEditor.tsx +++ b/worklenz-frontend/src/components/common/rich-comment-editor/RichCommentEditor.tsx @@ -249,16 +249,10 @@ export const RichCommentEditor = ({ HTMLAttributes: { class: 'mention' }, suggestion: { char: '@', - items: ({ query, editor }: { query: string; editor: Editor }) => { - const mentionedIds = new Set( - extractMentions(editor, optionsRef.current).map(person => person.id) - ); - + items: ({ query }: { query: string }) => { return optionsRef.current - .filter( - person => - !mentionedIds.has(person.id) && - person.name.toLowerCase().includes(query.toLowerCase()) + .filter(person => + person.name.toLowerCase().includes(query.toLowerCase()) ) .slice(0, MAX_SUGGESTIONS); }, diff --git a/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.css b/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.css index aba53b917..88d31da08 100644 --- a/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.css +++ b/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.css @@ -7,14 +7,16 @@ color: #40a9ff; } -.description-editor-shell .description-content .mentions { - font-weight: 500; +.description-editor-shell .description-content .mentions, +.description-editor-shell .ql-editor .mentions { + display: inline-block; + padding: 0 4px; border-radius: 4px; - padding: 1px 4px; - margin: 0 1px; - background-color: #f0f2f5; + font-weight: 500; + background-color: rgba(24, 144, 255, 0.12); color: #1890ff; - border: 1px solid #1890ff; + margin-inline: 1px; + border: none; } .description-editor-shell .description-editor-preview { @@ -126,10 +128,9 @@ color: #74c0fc; } -.description-editor-shell.is-dark .description-content .mentions { - background-color: #1f3344; +.description-editor-shell.is-dark .description-content .mentions, +.description-editor-shell.is-dark .ql-editor .mentions { color: #69b1ff; - border-color: #69b1ff; } .description-editor-shell.is-dark .description-editor-preview { @@ -303,22 +304,6 @@ ol.ql-nested-list { margin-bottom: 0 !important; } -.description-editor-shell .ql-editor .mentions { - font-weight: 500; - border-radius: 4px; - padding: 1px 4px; - margin: 0 1px; - background-color: #f0f2f5; - color: #1890ff; - border: 1px solid #1890ff; -} - -.description-editor-shell.is-dark .ql-editor .mentions { - background-color: #1f3344; - color: #69b1ff; - border-color: #69b1ff; -} - .description-mention-suggestions { position: fixed; z-index: 1100; diff --git a/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.test.tsx b/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.test.tsx index 1161b80e7..f80e46e1c 100644 --- a/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.test.tsx +++ b/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.test.tsx @@ -6,6 +6,7 @@ import { projectCommentsApiService } from '@/api/projects/comments/project-comme const quillMock = vi.hoisted(() => ({ formatText: vi.fn(), + format: vi.fn(), register: vi.fn(), })); @@ -50,6 +51,7 @@ vi.mock('react-quill-new', async () => { getSelection: () => { index: number; length: number }; getBounds: () => { left: number; top: number; bottom: number }; getFormat: () => Record; + format: (...args: unknown[]) => void; formatText: (...args: unknown[]) => void; deleteText: (index: number, length: number) => void; insertText: (index: number, text: string) => void; @@ -61,11 +63,12 @@ vi.mock('react-quill-new', async () => { value?: string; defaultValue?: string; onChange: (value: string) => void; + onChangeSelection?: () => void; onKeyDown?: React.KeyboardEventHandler; } const MockQuill = React.forwardRef<{ getEditor: () => MockEditor }, MockProps>( - ({ value, defaultValue, onChange, onKeyDown }, ref) => { + ({ value, defaultValue, onChange, onChangeSelection, onKeyDown }, ref) => { const initialValue = value ?? defaultValue ?? ''; const [editorValue, setEditorValue] = React.useState(initialValue); const valueRef = React.useRef(initialValue); @@ -91,6 +94,7 @@ vi.mock('react-quill-new', async () => { getSelection: () => ({ index: cursorRef.current, length: 0 }), getBounds: () => ({ left: 0, top: 0, bottom: 20 }), getFormat: () => ({}), + format: (...args) => quillMock.format(...args), formatText: (...args) => quillMock.formatText(...args), deleteText: (index, length) => commit( @@ -121,6 +125,7 @@ vi.mock('react-quill-new', async () => { const nextValue = event.target.value; commit(nextValue, nextValue.length); }} + onSelect={onChangeSelection} onKeyDown={onKeyDown} /> @@ -144,6 +149,7 @@ describe('DescriptionEditor', () => { beforeEach(() => { vi.mocked(projectCommentsApiService.getMentionMembers).mockReset(); quillMock.formatText.mockClear(); + quillMock.format.mockClear(); quillMock.register.mockClear(); }); @@ -235,6 +241,7 @@ describe('DescriptionEditor', () => { fireEvent.mouseDown(suggestion); expect(textarea).toHaveValue('@Alice Example '); + expect(quillMock.format).toHaveBeenCalledWith('mention', false, 'user'); await waitFor(() => expect(quillMock.formatText).toHaveBeenCalledWith(0, 14, 'mention', true, 'silent') ); @@ -265,6 +272,54 @@ describe('DescriptionEditor', () => { ); }); + it('preserves mention marks while members load and clears stale marks after lookup succeeds', async () => { + let resolveMembers!: ( + response: Awaited> + ) => void; + vi.mocked(projectCommentsApiService.getMentionMembers).mockReturnValue( + new Promise(resolve => { + resolveMembers = resolve; + }) + ); + + render( + + ); + + fireEvent.click(screen.getByText('@Former Member')); + const textarea = await screen.findByTestId('mock-quill-textarea'); + await waitFor(() => expect(projectCommentsApiService.getMentionMembers).toHaveBeenCalled()); + + fireEvent.select(textarea); + expect(quillMock.formatText).not.toHaveBeenCalledWith( + expect.any(Number), + expect.any(Number), + 'mention', + false, + 'silent' + ); + + resolveMembers({ + done: true, + body: [{ id: 'member-1', name: 'Alice Example', role: }], + }); + + await waitFor(() => + expect(quillMock.formatText).toHaveBeenCalledWith( + expect.any(Number), + expect.any(Number), + 'mention', + false, + 'silent' + ) + ); + }); + it('closes mention suggestions on Escape without discarding the draft', async () => { vi.mocked(projectCommentsApiService.getMentionMembers).mockResolvedValue({ done: true, diff --git a/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.tsx b/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.tsx index d2fb88d91..8cbe08705 100644 --- a/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.tsx +++ b/worklenz-frontend/src/components/task-drawer/shared/info-tab/description-editor.tsx @@ -36,6 +36,7 @@ interface QuillEditorInstance { getSelection: (focus?: boolean) => { index: number; length: number } | null; getBounds: (index: number, length?: number) => QuillBounds | null; getFormat: (index: number, length?: number) => Record; + format: (name: string, value: unknown, source?: 'api' | 'user' | 'silent') => void; formatText: ( index: number, length: number, @@ -77,6 +78,18 @@ const registerMentionFormat = (Quill: typeof import('react-quill-new').Quill) => static blotName = 'mention'; static tagName = 'span'; static className = 'mentions'; + + static create(value: boolean) { + const node = super.create(value) as HTMLElement; + if (value) { + node.classList.add('mentions'); + } + return node; + } + + static formats(node: HTMLElement) { + return node.classList.contains('mentions') ? true : undefined; + } } Quill.register(MentionBlot, true); @@ -115,7 +128,24 @@ const SANITIZE_CONFIG = { const applyMentionFormatting = (editor: QuillEditorInstance, members: MentionMember[]) => { const text = editor.getText(); - findMentionRanges(text, members).forEach(({ start, length }) => { + const ranges = findMentionRanges(text, members) + .slice() + .sort((a, b) => a.start - b.start); + + if (editor.root.querySelector('.mentions')) { + let cursor = 0; + for (const { start, length } of ranges) { + if (start > cursor) { + editor.formatText(cursor, start - cursor, 'mention', false, 'silent'); + } + cursor = Math.max(cursor, start + length); + } + if (text.length > cursor) { + editor.formatText(cursor, text.length - cursor, 'mention', false, 'silent'); + } + } + + ranges.forEach(({ start, length }) => { if (editor.getFormat(start, length).mention !== true) { editor.formatText(start, length, 'mention', true, 'silent'); } @@ -148,6 +178,9 @@ const DescriptionEditor = ({ const [mentionMembers, setMentionMembers] = useState([]); const [isLoadingMentionMembers, setIsLoadingMentionMembers] = useState(false); const [mentionMembersLoadFailed, setMentionMembersLoadFailed] = useState(false); + const [mentionMembersLoadedForProjectId, setMentionMembersLoadedForProjectId] = useState< + string | null + >(null); const [mentionQuery, setMentionQuery] = useState(null); const [selectedMentionIndex, setSelectedMentionIndex] = useState(0); const mentionMembersCacheRef = useRef<{ projectId: string; members: MentionMember[] } | null>(null); @@ -155,6 +188,7 @@ const DescriptionEditor = ({ const filteredMentionMembersRef = useRef([]); const selectedMentionIndexRef = useRef(selectedMentionIndex); const insertMentionRef = useRef<(member: MentionMember) => void>(() => undefined); + const pendingCaretRafRef = useRef(null); mentionQueryRef.current = mentionQuery; selectedMentionIndexRef.current = selectedMentionIndex; @@ -168,12 +202,15 @@ const DescriptionEditor = ({ if (cachedMembers?.projectId === projectId) { setMentionMembers(cachedMembers.members); setMentionMembersLoadFailed(false); + setMentionMembersLoadedForProjectId(projectId); + setIsLoadingMentionMembers(false); return; } let isCancelled = false; setMentionMembers([]); setMentionMembersLoadFailed(false); + setMentionMembersLoadedForProjectId(null); setIsLoadingMentionMembers(true); projectCommentsApiService @@ -194,6 +231,7 @@ const DescriptionEditor = ({ }); mentionMembersCacheRef.current = { projectId, members }; setMentionMembers(members); + setMentionMembersLoadedForProjectId(projectId); }) .catch(error => { if (isCancelled) return; @@ -209,14 +247,18 @@ const DescriptionEditor = ({ }; }, [isEditorOpen, projectId]); + const canFormatMentions = Boolean( + projectId && mentionMembersLoadedForProjectId === projectId + ); + useEffect(() => { - if (!isEditorOpen || mentionMembers.length === 0) return; + if (!isEditorOpen || !canFormatMentions) return; const frame = requestAnimationFrame(() => { const editor = quillRef.current?.getEditor(); if (editor) applyMentionFormatting(editor, mentionMembers); }); return () => cancelAnimationFrame(frame); - }, [isEditorOpen, mentionMembers]); + }, [canFormatMentions, isEditorOpen, mentionMembers]); // Mirrors of state used inside effect cleanups / callbacks that must see // the latest value without re-subscribing (avoids stale closures). @@ -587,32 +629,14 @@ const DescriptionEditor = ({ }, [isEditorOpen, handleDiscardClick]); const filteredMentionMembers = useMemo(() => { - if (!mentionQuery || !quillRef.current) return []; + if (!mentionQuery) return []; const query = normalizeMentionText(mentionQuery.query.trim()); - const editor = quillRef.current.getEditor(); - const text = editor.getText(); - - // Exclude the mention currently being typed from duplicate detection. - const textWithoutCurrentQuery = - removeActiveMentionQuery(text, mentionQuery.start, mentionQuery.end); - - const existingMentions = new Set( - findMentionRanges(textWithoutCurrentQuery, mentionMembers).map(({ start, length }) => - normalizeMentionText( - textWithoutCurrentQuery.slice(start, start + length) - ) - ) - ); return mentionMembers .filter(member => { const normalizedName = normalizeMentionText(member.name.trim()); - - return ( - normalizedName.includes(query) && - !existingMentions.has(`@${normalizedName}`) - ); + return normalizedName.includes(query); }) .slice(0, 8); }, [mentionMembers, mentionQuery]); @@ -671,13 +695,47 @@ const DescriptionEditor = ({ if (!mentionQuery || !quillRef.current) return; const editor = quillRef.current.getEditor(); const mention = `@${member.name}`; - const mentionEnd = mentionQuery.start + mention.length; + const start = mentionQuery.start; + const queryLength = mentionQuery.end - start; editor.focus(); - editor.deleteText(mentionQuery.start, mentionQuery.end - mentionQuery.start, 'user'); - editor.insertText(mentionQuery.start, mention, { mention: true }, 'user'); + + // Remove the typed @query + editor.deleteText(start, queryLength, 'user'); + + // Insert the mention + editor.insertText(start, mention, { mention: true }, 'user'); + + // Insert a normal space (without mention format) + const mentionEnd = start + mention.length; editor.insertText(mentionEnd, ' ', {}, 'user'); - editor.setSelection(mentionEnd + 1, 0, 'silent'); + + // Move caret after the space + const caretPos = mentionEnd + 1; + editor.setSelection(caretPos, 0, 'user'); + + //Force turn OFF the mention format at the caret + editor.format('mention', false, 'user'); + + if (pendingCaretRafRef.current !== null) { + cancelAnimationFrame(pendingCaretRafRef.current); + } + pendingCaretRafRef.current = requestAnimationFrame(() => { + pendingCaretRafRef.current = null; + if (typeof document !== 'undefined' && !editor.root.contains(document.activeElement)) { + return; + } + const currentSelection = editor.getSelection(); + if ( + currentSelection && + currentSelection.index === caretPos && + currentSelection.length === 0 + ) { + editor.setSelection(caretPos, 0, 'silent'); + editor.format('mention', false, 'silent'); + } + }); + setMentionQuery(null); }, [mentionQuery] @@ -702,8 +760,12 @@ const DescriptionEditor = ({ }; const handleEditorChange = (nextHtml: string) => { + if (pendingCaretRafRef.current !== null) { + cancelAnimationFrame(pendingCaretRafRef.current); + pendingCaretRafRef.current = null; + } const editor = quillRef.current?.getEditor(); - if (editor) applyMentionFormatting(editor, mentionMembers); + if (editor && canFormatMentions) applyMentionFormatting(editor, mentionMembers); // Prefer live HTML after silent mention formatting so mention spans are // included in the draft we persist. Safe because the editor is uncontrolled // while open — this string is never pushed back through Quill's `value` prop. @@ -716,7 +778,16 @@ const DescriptionEditor = ({ const handleEditorSelectionChange = () => { const editor = quillRef.current?.getEditor(); - if (editor) applyMentionFormatting(editor, mentionMembers); + if (editor) { + if (canFormatMentions) applyMentionFormatting(editor, mentionMembers); + const selection = editor.getSelection(); + if (selection && selection.length === 0 && selection.index > 0) { + const prevChar = editor.getText().slice(selection.index - 1, selection.index); + if (/\s/.test(prevChar) && editor.getFormat(selection.index).mention) { + editor.format('mention', false, 'silent'); + } + } + } updateMentionQuery(editor || null); }; @@ -754,6 +825,8 @@ const DescriptionEditor = ({ // typed spaces. defaultValue seeds the editor on mount/reopen. defaultValue={content} preserveWhitespace + spellCheck={false} + autoCorrect="off" onChange={handleEditorChange} onChangeSelection={handleEditorSelectionChange} onKeyDown={handleEditorKeyDown}