import { css, cx } from '@emotion/css'; import Avatar from 'antd/lib/avatar/avatar'; import React, { useEffect, useMemo, useRef, useState } from 'react'; import ReactDOM from 'react-dom'; import { Editor, Node, Path, Range, Text } from '@src/components/slate-packages/slate'; import { v4 as anchorId } from 'uuid'; import { TripdocsSdkContext } from '../../../../Docs'; import { hashCode, intToRGB } from '../../../../utils/hexColorUtils'; import { createRandomId } from '../../../../utils/randomId'; import { bodySelectAll } from '../../../../utils/selectionUtils'; import { Editable, ReactEditor, Slate, withReact } from '../../../slate-packages/slate-react'; import { IconBtn } from '../Components'; import { getNodesByRangeId } from './commentOps'; import { deleteCommentByCommentId, deleteCommentByRangeId } from './deleteSideComment'; import { CommentContentProps, insertSideComment } from './insertSideComment'; import { updateSideComment } from './updateSideComment'; import { message, Tooltip, Image } from 'antd'; import { createEditor, Transforms } from '../../../slate-packages/slate'; import { CommentCallbackActionType, ELTYPE } from '../config'; import { withHistory } from '../../../slate-packages/slate-history'; import { deserialize, InlineSlateEditor } from './inlineSlateEditor'; import { rangesMap, timeFormat } from './utils'; import { ArrowDownOutlined, CaretDownOutlined, CaretLeftOutlined } from '@ant-design/icons'; import { getCache } from '@src/utils/cacheUtils'; import { f } from '@src/resource/string'; import { EditorContainerInnerPortal } from '@src/utils/createPortal'; import { SlateInlineImage } from '../InlineImage/inlineImagePlugins'; const PortalByRow = ({ children, sideCommentRowNum, editor }: any) => { const container = ReactEditor.toDOMNode(editor, Node.get(editor, [sideCommentRowNum])); return ReactDOM.createPortal(children, container); }; export const getInlineElList = (string: any) => { if (!string) { return []; } const mentionArr: any = [...string.matchAll(/\@\[\[(.*?)\]\]/g)].map((item: any) => item[1]); console.log('getMentionedMemberList string', string, mentionArr); return mentionArr; }; export const replaceInlineElements = (string: string = '') => { const inlineElArr = []; const textArr = string?.split(/[\!\@]\[\[.*?\]\]/); string?.replace(/([\!\@])\[\[(.*?)\]\]/g, (_, $1, $2) => { console.log('match', _, $1, $2); if ($2.startsWith('{')) { if ($1 === '!') { const element = JSON.parse($2); inlineElArr.push({ type: ELTYPE.INLINEIMAGE, source: element?.source, linkSource: element?.linkSource, width: element?.width, height: element?.height, }); } else if ($1 === '@') { inlineElArr.push({ type: ELTYPE.MENTION, data: JSON.parse($2) }); } } return ''; }); console.log('[inlineElArr[', textArr, inlineElArr); const leaves = []; if (textArr.length - 1 === inlineElArr.length) { for (let i = 0; i < inlineElArr.length; i++) { leaves.push(<>{textArr[i]}); const inline = inlineElArr[i]; if (inline.type === ELTYPE.INLINEIMAGE) { console.log('inlineElArr[i].data', inline, inlineElArr[i].data); leaves.push( } element={{ source: inline.source, linkSource: inline.linkSource, width: inline.width, height: inline.height }} editor={null} /> ); } else if (inline.type === ELTYPE.MENTION) { leaves.push( @{inline.data?.sn} ); } } leaves.push(<>{textArr[textArr.length - 1]}); } return leaves; }; const SideCommentCreator = (props: any) => { const { editor, docId, sideCommentRowNum, setSideCommentRowNum, rangeId, curUserName, WIPCommentRangeId, setWIPCommentRangeId, identicalSelectionRangeId, setIdenticalSelectionRangeId, editorClientRect, containerClientRect, } = props; const sideCommentWidth = 280; const sideCommentRightThreshold = sideCommentWidth + 10; const [value, setValue] = useState([ { type: ELTYPE.PARAGRAPH, children: [ { text: '', }, ], }, ]); const [sideCommentRight, setSideCommentRight] = useState(-sideCommentWidth); const [commentValue, setCommentValue] = useState(''); const creatorRef = useRef(); useEffect(() => { const editorRight = editorClientRect.right; const containerRight = containerClientRect.right - 20; console.log('[con]', containerRight - editorRight < sideCommentRightThreshold, containerRight, editorRight, sideCommentRightThreshold); if (containerRight - editorRight < sideCommentRightThreshold) { setSideCommentRight(editorRight - containerRight); } else { setSideCommentRight(-sideCommentWidth); } }, [sideCommentRowNum]); useEffect(() => { let count = 0; const creatorMouseUpHandler = e => { if (!creatorRef || !creatorRef.current) { return; } let _con: any = creatorRef.current; if (!_con.contains(e.target) && sideCommentRowNum > 0) { if (count >= 1) { setSideCommentRowNum(-1); setWIPCommentRangeId(null); const nodesEntryArr = getNodesByRangeId(editor, rangeId); if (identicalSelectionRangeId) { setIdenticalSelectionRangeId(null); } else { deleteCommentByRangeId(editor, rangeId, nodesEntryArr, docId); } count = 0; } else { ++count; } } }; document.addEventListener('mouseup', creatorMouseUpHandler); return () => { document.removeEventListener('mouseup', creatorMouseUpHandler); }; }, []); const editorDom = document.getElementById(`editorarea-${docId}`); let curRowTop = 0; const curRow = editor?.children[sideCommentRowNum]; if (curRow && curRow.type === ELTYPE.CARD) { console.log('curRow', curRow, curRow.children[1]); curRowTop = ReactEditor.toDOMNode(editor, curRow.children[1])?.getBoundingClientRect().top; } else { curRowTop = ReactEditor.toDOMNode(editor, curRow)?.getBoundingClientRect().top; } const top = curRowTop + 10 - editorDom.getBoundingClientRect().top; const commentValueLength = commentValue?.replace(/[\!\@]\[\[(.*?)\]\]/g, '').length; return (
500 ? '#f04f4f' : null }}>{commentValueLength} /500
); }; const InlineSideCommentButton = (props: any) => { const { comments, editor, position, isShowHoveringCommentButton } = props; const { docId, focusedRangeId, resetFocusedRangeId, setFocusedRangeId, WIPCommentRangeId } = React.useContext(TripdocsSdkContext); const [showInlineSideComment, setShowInlineSideComment] = useState(false); const [editingCommentId, setEditingCommentId] = useState(null); const [isReplyingComment, setIsReplyingComment] = useState(false); const sideCommentWidth = 280; const [sideCommentRight, setSideCommentRight] = useState(-sideCommentWidth); const commentWrapperRef = useRef(); useEffect(() => { if (showInlineSideComment) { const editorRight = document.getElementById(`editorarea-${docId}`).getBoundingClientRect().right + 20; const containerRight = document.getElementById(`editorContainer-${docId}`).getBoundingClientRect().right; if (containerRight - editorRight < sideCommentWidth) { setSideCommentRight(editorRight - containerRight); } else { setSideCommentRight(-sideCommentWidth); } if (!!WIPCommentRangeId) return; const editorContent = document.getElementById(`editor-content-${docId}`); const commentItem: HTMLElement = focusedRangeId && editorContent?.querySelector(`[data-commentitem-rangeid='${focusedRangeId.replace(/['"\\]/g, '\\$&')}']`); const containerWrapDom = document.getElementById(`editor-content-wrap-${docId}`); if (commentItem && commentItem.offsetParent) { const offsetTop = (commentItem.offsetParent as HTMLElement).offsetTop + commentItem.offsetTop; const height = commentItem?.getBoundingClientRect().height; console.log('[] 自动滚动到 focused 评论', height, containerWrapDom, offsetTop - height, commentItem, commentItem.offsetParent); if (typeof offsetTop === 'number' && typeof height === 'number' && containerWrapDom) { containerWrapDom.scroll({ behavior: 'smooth', top: offsetTop - height }); } } } }, [showInlineSideComment, WIPCommentRangeId]); useEffect(() => { console.log('1---InlineSideCommentButton---', focusedRangeId); if (focusedRangeId) { const isCommentIncluded = comments.some(item => item.rangeIdList && item.rangeIdList.includes(focusedRangeId)); console.log('2---InlineSideCommentButton---', focusedRangeId, isCommentIncluded); if (isCommentIncluded) { setShowInlineSideComment(true); } } }, [focusedRangeId]); useEffect(() => { const sideCommentMouseUpHandler = e => { if (!commentWrapperRef || !commentWrapperRef.current) { return; } let _con: any = commentWrapperRef.current; if (!_con.contains(e.target) && showInlineSideComment) { setEditingCommentId(prevEditingCommentId => { setIsReplyingComment(prevIsReplyingComment => { if (prevIsReplyingComment) { deleteCommentByCommentId(editor, prevEditingCommentId, docId, true); } return false; }); return null; }); setShowInlineSideComment(false); resetFocusedRangeId(); } }; document.addEventListener('mouseup', sideCommentMouseUpHandler); return () => { document.removeEventListener('mouseup', sideCommentMouseUpHandler); }; }, [showInlineSideComment]); const commentsRC = useMemo(() => { const rangesMapping = rangesMap(comments); console.log('commentData---333', comments, rangesMapping); let result = []; for (const rangeId in rangesMapping) { const filteredCommentContent = rangesMapping[rangeId]?.commentContent?.filter(item => item.rangeId === rangeId); const commentItem = (
{ if (editingCommentId) { e.preventDefault(); e.stopPropagation(); } }} onMouseOver={e => { if (editingCommentId) { e.preventDefault(); e.stopPropagation(); } else { setFocusedRangeId(rangeId); } }} >
{rangesMapping[rangeId]?.text}
{filteredCommentContent?.map((content: any, index: number, array: any) => { return ( ); })}
); result.push(commentItem); } return result; }, [showInlineSideComment, editingCommentId, JSON.stringify(comments), isReplyingComment]); return ( <> { setShowInlineSideComment(true); e.stopPropagation(); e.preventDefault(); }} > {showInlineSideComment && comments && ( <>
{}} > {commentsRC}
)} ); }; export const CommentContent = ({ editor, text, content, index, rangeId, editingCommentId, setEditingCommentId, isReplyingComment, setIsReplyingComment, isShowHoveringCommentButton, contentCollapseLength, }: any) => { const { docId, userInfo } = React.useContext(TripdocsSdkContext); const { commentId } = content; const [commentValue, setCommentValue] = useState(content.content); const editCommentEditorRef = useRef(); const [isExpanded, setIsExpanded] = useState(true); const [value, setValue] = useState(deserialize(commentValue)); const toggleExpanded = () => { setIsExpanded(prev => !prev); }; useEffect(() => { console.log('content.content', commentValue); setCommentValue(prev => { if (prev !== content.content) { setValue(deserialize(content.content)); return content.content; } else { return prev; } }); }, [content.content]); const editCommentEditor = useMemo(() => { const commentValueLength = commentValue?.replace(/[\@|\!]\[\[(.*?)\]\]/g, '').length; return (
{content.replyTarget && ( )}
500 ? '#f04f4f' : null }}>{commentValueLength} /500
); }, [commentId, editingCommentId, commentValue, docId]); const { banCommentNesting } = getCache(docId, 'options'); const commentDisplay = useMemo( () => (
{!content?.creator?.headPortrait && !(userInfo.userName === content.userName && userInfo.headPortrait) ? ( {content.userName?.split(')')[0].slice(-2)} ) : ( } /> )}
{}
{content?.creator?.displayName || content.userName}
{} {timeFormat(new Date(content.time)) === new Date().getFullYear().toString() ? timeFormat(new Date(content.time)).slice(5, 16) : timeFormat(new Date(content.time)).slice(2, 16)} {}
{content?.content?.replace(/\@\[\[.*?\]\]/g, '')?.length < contentCollapseLength ? null : }
{} {content.replyTarget && ( )}
{replaceInlineElements(content.content)}
{commentId && isShowHoveringCommentButton && ( <> {!(banCommentNesting && content.replyTarget) && ( { const replyCommentId = createRandomId(); const contentObj = { userName: content.userName, content: '', commentId: replyCommentId, rangeId, time: timeFormat(), mentionedMemberList: [], }; const replyTargetObj = { rangeId, ...content }; setEditingCommentId(replyCommentId); setIsReplyingComment(true); insertSideComment(editor, docId, contentObj, true, replyTargetObj); }} /> )} {content.userName === userInfo.userName && ( { setIsReplyingComment(false); setEditingCommentId(commentId); }} /> )} {content.userName === userInfo.userName && ( { deleteCommentByCommentId(editor, commentId, docId, false); }} /> )} )}
), [editingCommentId, commentId, commentValue, isExpanded, isReplyingComment, content.content] ); return commentId === editingCommentId ? editCommentEditor : commentDisplay; }; const commentActionsMap = function () { const cMap = new Map(); cMap.set('edit', f('edit')); cMap.set('delete', f('delete')); cMap.set('reply', f('reply')); return cMap; }; export const CommentActionButton = ({ action, onClickFn }: any) => { if (!commentActionsMap().has(action)) return; return (
{' '} {commentActionsMap().get(action)}
); }; export const ReplyTargetContainer = ({ editor, replyTarget, docId, contentCollapseLength }) => { const targetCommentId = replyTarget?.commentId; let targetObj = null; const commentContent = window.tripdocs.editorsMap[docId].commentData; commentContent && (targetObj = (commentContent as any).find(item => item.commentId === targetCommentId)); const [isExpanded, setIsExpanded] = useState(false); const toggleExpanded = () => { setIsExpanded(prev => !prev); }; return (
{!targetObj ? ( <>{f('commentHasBeenDeleted')} ) : ( <> {}
{f('replyTo')} {targetObj?.userName}
{targetObj?.content?.replace(/\@\[\[.*?\]\]/g, '')?.length < contentCollapseLength ? null : }
{}
{replaceInlineElements(targetObj?.content)}
)}
); }; export { SideCommentCreator, InlineSideCommentButton };