/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import { Comment, Comments, CommentStore, createComment, createThread, Thread, useCommentStore, } from '../commenting'; import type { EditorState, LexicalCommand, LexicalEditor, NodeKey, } from 'lexical'; import './CommentPlugin.css'; import { $createMarkNode, $getMarkIDs, $isMarkNode, $unwrapMarkNode, $wrapSelectionInMarkNode, MarkNode, } from '@lexical/mark'; import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin'; import { ClearEditorPlugin } from '@lexical/react/LexicalClearEditorPlugin'; import { LexicalComposer } from '@lexical/react/LexicalComposer'; import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin'; import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin'; import { PlainTextPlugin } from '@lexical/react/LexicalPlainTextPlugin'; import LexicalErrorBoundary from '@lexical/react/LexicalErrorBoundary'; import { createDOMRange, createRectsFromDOMRange } from '@lexical/selection'; import { $isRootTextContentEmpty, $rootTextContent } from '@lexical/text'; import { mergeRegister, registerNestedElementResolver } from '@lexical/utils'; import { $getNodeByKey, $getSelection, $isRangeSelection, $isTextNode, CLEAR_EDITOR_COMMAND, COMMAND_PRIORITY_EDITOR, createCommand, KEY_ESCAPE_COMMAND, } from 'lexical'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import * as React from 'react'; import { createPortal } from 'react-dom'; import useLayoutEffect from '../shared/src/useLayoutEffect'; import useModal from '../hooks/useModal'; import CommentEditorTheme from '../themes/CommentEditorTheme'; import Button from '../ui/Button'; import ContentEditable from '../ui/ContentEditable'; import Placeholder from '../ui/Placeholder'; import type { Doc } from 'yjs'; import { useCollaborationContext } from '@lexical/react/LexicalCollaborationContext'; import { WebsocketProvider } from 'y-websocket'; import { useTranslation } from 'react-i18next'; import { TFunction } from 'i18next'; export const INSERT_INLINE_COMMAND: LexicalCommand = createCommand(); function AddCommentBox({ anchorKey, editor, onAddComment, }: { anchorKey: NodeKey; editor: LexicalEditor; onAddComment: () => void; }): JSX.Element { const boxRef = useRef(null); const updatePosition = useCallback(() => { const boxElem = boxRef.current; const rootElement = editor.getRootElement(); const anchorElement = editor.getElementByKey(anchorKey); if (boxElem !== null && rootElement !== null && anchorElement !== null) { const { right } = rootElement.getBoundingClientRect(); const { top } = anchorElement.getBoundingClientRect(); boxElem.style.left = `${right - 20}px`; boxElem.style.top = `${top - 30}px`; } }, [anchorKey, editor]); useEffect(() => { window.addEventListener('resize', updatePosition); return () => { window.removeEventListener('resize', updatePosition); }; }, [editor, updatePosition]); useLayoutEffect(() => { updatePosition(); }, [anchorKey, editor, updatePosition]); return (
); } function EditorRefPlugin({ editorRef, }: { editorRef: { current: null | LexicalEditor }; }): null { const [editor] = useLexicalComposerContext(); useLayoutEffect(() => { editorRef.current = editor; return () => { editorRef.current = null; }; }, [editor, editorRef]); return null; } function EscapeHandlerPlugin({ onEscape, }: { onEscape: (e: KeyboardEvent) => boolean; }): null { const [editor] = useLexicalComposerContext(); useEffect(() => { return editor.registerCommand( KEY_ESCAPE_COMMAND, (event: KeyboardEvent) => { return onEscape(event); }, 2 ); }, [editor, onEscape]); return null; } function PlainTextEditor({ className, autoFocus, onEscape, onChange, editorRef, placeholder = 'Type a comment...', }: { autoFocus?: boolean; className?: string; editorRef?: { current: null | LexicalEditor }; onChange: (editorState: EditorState, editor: LexicalEditor) => void; onEscape: (e: KeyboardEvent) => boolean; placeholder?: string; }) { const initialConfig = { namespace: 'Commenting', nodes: [], onError: (error: Error) => { throw error; }, theme: CommentEditorTheme, }; return (
} placeholder={{placeholder}} ErrorBoundary={LexicalErrorBoundary} /> {autoFocus !== false && } {editorRef !== undefined && }
); } function useOnChange( setContent: (text: string) => void, setCanSubmit: (canSubmit: boolean) => void ) { return useCallback( (editorState: EditorState, _editor: LexicalEditor) => { editorState.read(() => { setContent($rootTextContent()); setCanSubmit(!$isRootTextContentEmpty(_editor.isComposing(), true)); }); }, [setCanSubmit, setContent] ); } function CommentInputBox({ editor, cancelAddComment, submitAddComment, t, }: { cancelAddComment: () => void; editor: LexicalEditor; submitAddComment: ( commentOrThread: Comment | Thread, isInlineComment: boolean ) => void; t: TFunction; }) { const [content, setContent] = useState(''); const [canSubmit, setCanSubmit] = useState(false); const boxRef = useRef(null); const selectionState = useMemo( () => ({ container: document.createElement('div'), elements: [], }), [] ); const author = useCollabAuthorName(); const updateLocation = useCallback(() => { editor.getEditorState().read(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { const anchor = selection.anchor; const focus = selection.focus; const range = createDOMRange( editor, anchor.getNode(), anchor.offset, focus.getNode(), focus.offset ); const boxElem = boxRef.current; if (range !== null && boxElem !== null) { const { left, bottom, width } = range.getBoundingClientRect(); const selectionRects = createRectsFromDOMRange(editor, range); let correctedLeft = selectionRects.length === 1 ? left + width / 2 - 125 : left - 125; if (correctedLeft < 10) { correctedLeft = 10; } boxElem.style.left = `${correctedLeft}px`; boxElem.style.top = `${bottom + 20}px`; const selectionRectsLength = selectionRects.length; const { container } = selectionState; const elements: Array = selectionState.elements; const elementsLength = elements.length; for (let i = 0; i < selectionRectsLength; i++) { const selectionRect = selectionRects[i]; let elem: HTMLSpanElement = elements[i]; if (elem === undefined) { elem = document.createElement('span'); elements[i] = elem; container.appendChild(elem); } const color = '255, 212, 0'; const style = `position:absolute;top:${selectionRect.top}px;left:${selectionRect.left}px;height:${selectionRect.height}px;width:${selectionRect.width}px;background-color:rgba(${color}, 0.3);pointer-events:none;z-index:5;`; elem.style.cssText = style; } for (let i = elementsLength - 1; i >= selectionRectsLength; i--) { const elem = elements[i]; container.removeChild(elem); elements.pop(); } } } }); }, [editor, selectionState]); useLayoutEffect(() => { updateLocation(); const container = selectionState.container; const body = document.body; if (body !== null) { body.appendChild(container); return () => { body.removeChild(container); }; } }, [selectionState.container, updateLocation]); useEffect(() => { window.addEventListener('resize', updateLocation); return () => { window.removeEventListener('resize', updateLocation); }; }, [updateLocation]); const onEscape = (event: KeyboardEvent): boolean => { event.preventDefault(); cancelAddComment(); return true; }; const submitComment = () => { if (canSubmit) { let quote = editor.getEditorState().read(() => { const selection = $getSelection(); return selection !== null ? selection.getTextContent() : ''; }); if (quote.length > 100) { quote = quote.slice(0, 99) + '…'; } submitAddComment( createThread(quote, [createComment(content, author)]), true ); } }; const onChange = useOnChange(setContent, setCanSubmit); return (
); } function CommentsComposer({ submitAddComment, thread, placeholder, }: { placeholder?: string; submitAddComment: ( commentOrThread: Comment, isInlineComment: boolean, // eslint-disable-next-line no-shadow thread?: Thread ) => void; thread?: Thread; }) { const [content, setContent] = useState(''); const [canSubmit, setCanSubmit] = useState(false); const editorRef = useRef(null); const author = useCollabAuthorName(); const onChange = useOnChange(setContent, setCanSubmit); const submitComment = () => { if (canSubmit) { submitAddComment(createComment(content, author), false, thread); const editor = editorRef.current; if (editor !== null) { editor.dispatchCommand(CLEAR_EDITOR_COMMAND, undefined); } } }; return ( <> { return true; }} onChange={onChange} editorRef={editorRef} placeholder={placeholder} /> ); } function ShowDeleteCommentOrThreadDialog({ commentOrThread, deleteCommentOrThread, onClose, thread = undefined, t, }: { commentOrThread: Comment | Thread; deleteCommentOrThread: ( comment: Comment | Thread, // eslint-disable-next-line no-shadow thread?: Thread ) => void; onClose: () => void; thread?: Thread; t: TFunction; }): JSX.Element { return ( <> {`${t('toolbar:commentPlugin.Delete_Comment_Description')} ${ commentOrThread.type }?`}
{' '}
); } function CommentsPanelListComment({ comment, deleteComment, thread, rtf, t, }: { comment: Comment; deleteComment: ( commentOrThread: Comment | Thread, // eslint-disable-next-line no-shadow thread?: Thread ) => void; thread?: Thread; rtf: null; //FIXME: Intl.RelativeTimeFormat gives build error; t: TFunction; }): JSX.Element { const seconds = Math.round((comment.timeStamp - performance.now()) / 1000); const minutes = Math.round(seconds / 60); const [modal, showModal] = useModal(); return (
  • {comment.author} {/* · {seconds > -10 ? 'Just now' : rtf.format(minutes, 'minute')} */}

    {comment.content}

    {!comment.deleted && ( <> {modal} )}
  • ); } function CommentsPanelList({ activeIDs, comments, deleteCommentOrThread, listRef, markNodeMap, submitAddComment, t, }: { activeIDs: Array; comments: Comments; deleteCommentOrThread: ( commentOrThread: Comment | Thread, thread?: Thread ) => void; listRef: { current: null | HTMLUListElement }; markNodeMap: Map>; submitAddComment: ( commentOrThread: Comment | Thread, isInlineComment: boolean, thread?: Thread ) => void; t: TFunction; }): JSX.Element { const [editor] = useLexicalComposerContext(); const [counter, setCounter] = useState(0); const [modal, showModal] = useModal(); // const rtf = useMemo( // () => // new Intl.RelativeTimeFormat('en', { // localeMatcher: 'best fit', // numeric: 'auto', // style: 'short', // }), // [] // ); //FIXME: it is closed to fix a build error const rtf = null; useEffect(() => { // Used to keep the time stamp up to date const id = setTimeout(() => { setCounter(counter + 1); }, 10000); return () => { clearTimeout(id); }; }, [counter]); return (
      {comments.map((commentOrThread) => { const id = commentOrThread.id; if (commentOrThread.type === 'thread') { const handleClickThread = () => { const markNodeKeys = markNodeMap.get(id); if ( markNodeKeys !== undefined && (activeIDs === null || activeIDs.indexOf(id) === -1) ) { const activeElement = document.activeElement; // Move selection to the start of the mark, so that we // update the UI with the selected thread. editor.update( () => { const markNodeKey = Array.from(markNodeKeys)[0]; const markNode = $getNodeByKey(markNodeKey); if ($isMarkNode(markNode)) { markNode.selectStart(); } }, { onUpdate() { // Restore selection to the previous element if (activeElement !== null) { (activeElement as HTMLElement).focus(); } }, } ); } }; return ( // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
    • {'> '} {commentOrThread.quote}
      {/* INTRODUCE DELETE THREAD HERE*/} {modal}
        {commentOrThread.comments.map((comment) => ( ))}
    • ); } return ( ); })}
    ); } function CommentsPanel({ activeIDs, deleteCommentOrThread, comments, markNodeMap, submitAddComment, t, }: { activeIDs: Array; comments: Comments; deleteCommentOrThread: ( commentOrThread: Comment | Thread, thread?: Thread ) => void; markNodeMap: Map>; submitAddComment: ( commentOrThread: Comment | Thread, isInlineComment: boolean, thread?: Thread ) => void; t: TFunction; }): JSX.Element { const listRef = useRef(null); const isEmpty = comments.length === 0; return (

    {t('toolbar:commentPlugin.Comments')}

    {isEmpty ? (
    {t('toolbar:commentPlugin.No_Comments')}
    ) : ( )}
    ); } function useCollabAuthorName(): string { const collabContext = useCollaborationContext(); const { yjsDocMap, name } = collabContext; return yjsDocMap.has('comments') ? name : 'Playground User'; } export default function CommentPlugin({ providerFactory, }: { providerFactory?: ( id: string, yjsDocMap: Map ) => WebsocketProvider; }): JSX.Element { const collabContext = useCollaborationContext(); const [editor] = useLexicalComposerContext(); const commentStore = useMemo(() => new CommentStore(editor), [editor]); const comments = useCommentStore(commentStore); const markNodeMap = useMemo>>(() => { return new Map(); }, []); const [activeAnchorKey, setActiveAnchorKey] = useState(); const [activeIDs, setActiveIDs] = useState>([]); const [showCommentInput, setShowCommentInput] = useState(false); const [showComments, setShowComments] = useState(false); const { yjsDocMap } = collabContext; const { t } = useTranslation(['toolbar']); useEffect(() => { if (providerFactory) { const provider = providerFactory('comments', yjsDocMap); return commentStore.registerCollaboration(provider); } }, [commentStore, providerFactory, yjsDocMap]); const cancelAddComment = useCallback(() => { editor.update(() => { const selection = $getSelection(); // Restore selection if (selection !== null) { selection.dirty = true; } }); setShowCommentInput(false); }, [editor]); const deleteCommentOrThread = useCallback( (comment: Comment | Thread, thread?: Thread) => { if (comment.type === 'comment') { const deletionInfo = commentStore.deleteCommentOrThread( comment, thread ); if (!deletionInfo) return; const { markedComment, index } = deletionInfo; commentStore.addComment(markedComment, thread, index); } else { commentStore.deleteCommentOrThread(comment); // Remove ids from associated marks const id = thread !== undefined ? thread.id : comment.id; const markNodeKeys = markNodeMap.get(id); if (markNodeKeys !== undefined) { // Do async to avoid causing a React infinite loop setTimeout(() => { editor.update(() => { for (const key of markNodeKeys) { const node: null | MarkNode = $getNodeByKey(key); if ($isMarkNode(node)) { node.deleteID(id); if (node.getIDs().length === 0) { $unwrapMarkNode(node); } } } }); }); } } }, [commentStore, editor, markNodeMap] ); const submitAddComment = useCallback( ( commentOrThread: Comment | Thread, isInlineComment: boolean, thread?: Thread ) => { commentStore.addComment(commentOrThread, thread); if (isInlineComment) { editor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { const focus = selection.focus; const anchor = selection.anchor; const isBackward = selection.isBackward(); const id = commentOrThread.id; // Wrap content in a MarkNode $wrapSelectionInMarkNode(selection, isBackward, id); // Make selection collapsed at the end if (isBackward) { focus.set(anchor.key, anchor.offset, anchor.type); } else { anchor.set(focus.key, focus.offset, focus.type); } } }); setShowCommentInput(false); } }, [commentStore, editor] ); useEffect(() => { const changedElems: Array = []; for (let i = 0; i < activeIDs.length; i++) { const id = activeIDs[i]; const keys = markNodeMap.get(id); if (keys !== undefined) { for (const key of keys) { const elem = editor.getElementByKey(key); if (elem !== null) { elem.classList.add('selected'); changedElems.push(elem); setShowComments(true); } } } } return () => { for (let i = 0; i < changedElems.length; i++) { const changedElem = changedElems[i]; changedElem.classList.remove('selected'); } }; }, [activeIDs, editor, markNodeMap]); useEffect(() => { const markNodeKeysToIDs: Map> = new Map(); return mergeRegister( registerNestedElementResolver( editor, MarkNode, (from: MarkNode) => { return $createMarkNode(from.getIDs()); }, (from: MarkNode, to: MarkNode) => { // Merge the IDs const ids = from.getIDs(); ids.forEach((id) => { to.addID(id); }); } ), editor.registerMutationListener(MarkNode, (mutations) => { editor.getEditorState().read(() => { for (const [key, mutation] of mutations) { const node: null | MarkNode = $getNodeByKey(key); let ids: NodeKey[] = []; if (mutation === 'destroyed') { ids = markNodeKeysToIDs.get(key) || []; } else if ($isMarkNode(node)) { ids = node.getIDs(); } for (let i = 0; i < ids.length; i++) { const id = ids[i]; let markNodeKeys = markNodeMap.get(id); markNodeKeysToIDs.set(key, ids); if (mutation === 'destroyed') { if (markNodeKeys !== undefined) { markNodeKeys.delete(key); if (markNodeKeys.size === 0) { markNodeMap.delete(id); } } } else { if (markNodeKeys === undefined) { markNodeKeys = new Set(); markNodeMap.set(id, markNodeKeys); } if (!markNodeKeys.has(key)) { markNodeKeys.add(key); } } } } }); }), editor.registerUpdateListener(({ editorState, tags }) => { editorState.read(() => { const selection = $getSelection(); let hasActiveIds = false; let hasAnchorKey = false; if ($isRangeSelection(selection)) { const anchorNode = selection.anchor.getNode(); if ($isTextNode(anchorNode)) { const commentIDs = $getMarkIDs( anchorNode, selection.anchor.offset ); if (commentIDs !== null) { setActiveIDs(commentIDs); hasActiveIds = true; } if (!selection.isCollapsed()) { setActiveAnchorKey(anchorNode.getKey()); hasAnchorKey = true; } } } if (!hasActiveIds) { setActiveIDs((_activeIds) => _activeIds.length === 0 ? _activeIds : [] ); } if (!hasAnchorKey) { setActiveAnchorKey(null); } }); if (!tags.has('collaboration')) { setShowCommentInput(false); } }), editor.registerCommand( INSERT_INLINE_COMMAND, () => { const domSelection = window.getSelection(); if (domSelection !== null) { domSelection.removeAllRanges(); } setShowCommentInput(true); return true; }, COMMAND_PRIORITY_EDITOR ) ); }, [editor, markNodeMap]); const onAddComment = () => { editor.dispatchCommand(INSERT_INLINE_COMMAND, undefined); }; return ( <> {showCommentInput && createPortal( , document.body )} {activeAnchorKey !== null && activeAnchorKey !== undefined && !showCommentInput && createPortal( , document.body )} {createPortal( , document.body )} {showComments && createPortal( , document.body )} ); }