/** * Copyright 2023-present DreamNum Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { IUser, LocaleType, UniverInstanceType } from '@univerjs/core'; import type { IAddCommentCommandParams, IThreadComment, IUpdateCommentCommandParams } from '@univerjs/thread-comment'; import type { IUniverUIConfig } from '@univerjs/ui'; import { dateKit, generateRandomId, ICommandService, isSafeUrl, LOCALE_META, LocaleService, RegionService, UserManagerService, } from '@univerjs/core'; import { borderClassName, clsx, Dropdown, scrollbarClassName, Tooltip } from '@univerjs/design'; import { DeleteIcon, MoreHorizontalIcon, ReplyToCommentIcon, SuccessIcon, SuccessOutlineIcon } from '@univerjs/icons'; import { AddCommentCommand, DeleteCommentCommand, DeleteCommentTreeCommand, getDT, IThreadCommentAuthzService, ResolveCommentCommand, ThreadCommentModel, UpdateCommentCommand, } from '@univerjs/thread-comment'; import { UI_PLUGIN_CONFIG_KEY, useConfigValue, useDependency, useEvent, useObservable, UserInfo } from '@univerjs/ui'; import { useEffect, useMemo, useRef, useState } from 'react'; import { debounceTime, map, of, startWith } from 'rxjs'; import type { LocaleKey } from '../locale/types'; import type { IThreadCommentEditorInstance } from './ThreadCommentEditor'; import { SetActiveCommentOperation } from '../commands/operations/comment.operations'; import { transformDocument2TextNodes, transformTextNodes2Document } from './thread-comment-editor/util'; import { getThreadCommentEditorId } from './thread-comment-tree/util'; import { ThreadCommentEditor } from './ThreadCommentEditor'; export enum ThreadCommentTreeLocation { CELL = 'CELL', PANEL = 'PANEL', }; export interface IThreadCommentTreeProps { full?: boolean; id?: string; unitId: string; subUnitId: string; type: UniverInstanceType; refStr?: string; displayRef?: string; showEdit?: boolean; onClick?: () => void; showHighlight?: boolean; onClose?: () => void; getSubUnitName: (subUnitId: string) => string; location: ThreadCommentTreeLocation; autoFocus?: boolean; onMouseEnter?: () => void; onMouseLeave?: () => void; onAddComment?: (comment: IThreadComment) => boolean | void | Promise; onDeleteComment?: (comment: IThreadComment) => boolean; onAfterDeleteComment?: (comment: IThreadComment) => void | Promise; onResolve?: (resolved: boolean) => void; style?: React.CSSProperties; DropdownComponent?: typeof Dropdown; EditorComponent?: typeof ThreadCommentEditor; } export interface IThreadCommentItemProps { item: IThreadComment; unitId: string; subUnitId: string; onEditingChange?: (editing: boolean) => void; editing?: boolean; onClick?: () => void; resolved?: boolean; onReply: (user: IUser | undefined) => void; isRoot?: boolean; onClose?: () => void; onDeleteComment?: (comment: IThreadComment) => boolean; onAfterDeleteComment?: (comment: IThreadComment) => void | Promise; type: UniverInstanceType; threadCommentEditorId: string; DropdownComponent: typeof Dropdown; EditorComponent: typeof ThreadCommentEditor; } const MOCK_ID = '__mock__'; const ThreadCommentItem = (props: IThreadCommentItemProps) => { const { item, unitId, subUnitId, editing, onEditingChange, onReply, resolved, isRoot, onClose, onDeleteComment, onAfterDeleteComment, type, threadCommentEditorId, DropdownComponent, EditorComponent, } = props; const commandService = useDependency(ICommandService); const localeService = useDependency(LocaleService); const regionService = useDependency(RegionService); const userManagerService = useDependency(UserManagerService); useObservable(userManagerService.userChange$); const user = userManagerService.getUser(item.personId); const userInfo = { userId: item.personId, name: user?.name || item.authorName, avatar: user?.avatar }; const userContext = { scene: 'comment-author' as const, unitId, subUnitId, commentId: item.id, threadId: item.threadId }; const authzService = useDependency(IThreadCommentAuthzService); const isMock = item.id === MOCK_ID; const canEdit = !isMock && authzService.canWrite('update', item); const canDelete = !isMock && authzService.canWrite('delete', item); const canReply = !isMock && authzService.canWrite('reply', item); const [showReply, setShowReply] = useState(false); const uiConfig = useConfigValue(UI_PLUGIN_CONFIG_KEY); const avatarFallback = uiConfig?.avatarFallback; const currentRegion = useObservable(regionService.currentRegion$, regionService.getCurrentRegion()); const direction = useObservable(localeService.direction$, localeService.getDirection()); function formatCommentDateTime(value: string, region: LocaleType): string { const date = dateKit(value); const regionTag = LOCALE_META[region].tag; return date.formatIntl(regionTag, { year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false, numberingSystem: 'latn', }); } const dateText = isMock ? null : formatCommentDateTime(item.dT, currentRegion); const handleDeleteItem = async () => { if (onDeleteComment?.(item) === false) { return; } try { const success = await commandService.executeCommand( isRoot ? DeleteCommentTreeCommand.id : DeleteCommentCommand.id, { unitId, subUnitId, commentId: item.id, } ); if (success) { try { await onAfterDeleteComment?.(item); } catch { // The comment is already deleted; auxiliary anchor cleanup must not reopen it. } if (isRoot) { onClose?.(); } } } catch { // Keep the thread visible so the user can retry after the remote failure. } }; return (
setShowReply(false)} onMouseEnter={() => setShowReply(true)} > {item.personId || user || item.authorName ? (
{(isMock || resolved || !canReply) ? null : ( showReply && user ? ( ) : null )} {(canEdit || canDelete) && !resolved ? (
    {canEdit ? (
  • ) : null} {canDelete ? (
  • ) : null}
)} > ) : null}
) : null} {dateText && ( )} {editing ? ( onEditingChange?.(false)} autoFocus unitId={unitId} subUnitId={subUnitId} editorId={threadCommentEditorId} onSave={async ({ text, attachments }) => { const success = await commandService.executeCommand( UpdateCommentCommand.id, { unitId, subUnitId, payload: { commentId: item.id, text, attachments, }, } as IUpdateCommentCommandParams ); if (success) { onEditingChange?.(false); } return success; }} /> ) : (
{transformDocument2TextNodes(item.text).map((paragraph, paragraphIndex) => { let offset = 0; return (
{paragraph.map((node) => { const key = offset; offset += node.type === 'mention' ? node.content.label.length : node.content.length; switch (node.type) { case 'mention': return ( {node.content.label} {' '} ); case 'hyperlink': { const url = node.range.properties?.url; if (!isSafeUrl(url)) { return node.content; } return ( event.stopPropagation()} > {node.content} ); } default: return node.content; } })}
); })}
)} ); }; export const ThreadCommentTree = (props: IThreadCommentTreeProps) => { const { id, unitId, subUnitId, refStr, displayRef, showEdit = true, onClick, showHighlight, onClose, getSubUnitName, location, autoFocus, onMouseEnter, onMouseLeave, onAddComment, onDeleteComment, onAfterDeleteComment, onResolve, type, style, full, DropdownComponent = Dropdown, EditorComponent = ThreadCommentEditor, } = props; const threadCommentModel = useDependency(ThreadCommentModel); const [isHover, setIsHover] = useState(false); const [editingId, setEditingId] = useState(''); const updte$ = useMemo(() => threadCommentModel.commentUpdate$.pipe(debounceTime(16)), [threadCommentModel]); const comments = useObservable( () => id ? updte$.pipe( map(() => threadCommentModel.getCommentWithChildren(unitId, subUnitId, id)), startWith(threadCommentModel.getCommentWithChildren(unitId, subUnitId, id)) ) : of(null), null, false, [id, subUnitId, threadCommentModel, unitId, updte$] ); const commandService = useDependency(ICommandService); const localeService = useDependency(LocaleService); const userManagerService = useDependency(UserManagerService); const resolved = comments?.root.resolved; const currentUser = useObservable(userManagerService.currentUser$); const authzService = useDependency(IThreadCommentAuthzService); const canResolve = comments ? authzService.canWrite('resolve', comments.root) : false; const canDeleteRoot = comments ? authzService.canWrite('delete', comments.root) : false; const canComment = comments ? authzService.canWrite('reply', comments.root) : authzService.canWrite('add', { unitId, subUnitId, ref: refStr ?? '' }); const editorRef = useRef(null); const fallbackEditorId = useMemo(() => generateRandomId(6), []); const renderComments: IThreadComment[] = [ ...comments ? [comments.root] : // mock empty comment [{ id: MOCK_ID, text: { dataStream: '\n\r', }, personId: currentUser?.userID ?? '', ref: refStr ?? '', dT: '', unitId, subUnitId, threadId: '', }], ...(comments?.children ?? []) as IThreadComment[], ]; const scrollerRef = useRef(null); const handleMouseLeave = useEvent(onMouseLeave); const handleResolve: React.MouseEventHandler = async (e) => { e.stopPropagation(); try { const success = await commandService.executeCommand(ResolveCommentCommand.id, { unitId, subUnitId, commentId: id, resolved: !resolved, }); if (!success) { return; } await commandService.executeCommand(SetActiveCommentOperation.id, resolved ? { unitId, subUnitId, commentId: id } : undefined); onResolve?.(!resolved); } catch { // Keep the current resolved state when the remote write fails. } }; const handleDeleteRoot: React.MouseEventHandler = async (e) => { e.stopPropagation(); const root = comments?.root; if (!root || onDeleteComment?.(root) === false) { return; } try { const success = await commandService.executeCommand( DeleteCommentTreeCommand.id, { unitId, subUnitId, commentId: id, } ); if (success) { try { await onAfterDeleteComment?.(root); } catch { // The comment is already deleted; auxiliary anchor cleanup must not reopen it. } await commandService.executeCommand(SetActiveCommentOperation.id); onClose?.(); } } catch { // Keep the thread visible so the user can retry after the remote failure. } }; useEffect(() => { return handleMouseLeave; }, [handleMouseLeave]); const subUnitName = getSubUnitName(comments?.root.subUnitId ?? subUnitId); const editorVisible = showEdit && !editingId && !resolved && canComment; const title = `${displayRef ?? refStr ?? comments?.root.ref ?? ''}${subUnitName ? ' ยท ' : ''}${subUnitName}`; const resolveLabel = localeService.t(resolved ? 'thread-comment-ui.item.markUnresolved' : 'thread-comment-ui.item.markResolved'); const deleteLabel = localeService.t('thread-comment-ui.item.delete'); const threadCommentEditorId = getThreadCommentEditorId({ location, unitId, subUnitId, commentId: id, fallbackId: fallbackEditorId, }); return (
{ const selection = event.currentTarget.ownerDocument.getSelection(); if (selection && !selection.isCollapsed && selection.anchorNode && selection.focusNode && event.currentTarget.contains(selection.anchorNode) && event.currentTarget.contains(selection.focusNode)) { return; } onClick?.(); }} onMouseEnter={() => { onMouseEnter?.(); setIsHover(true); }} onMouseLeave={() => { onMouseLeave?.(); setIsHover(false); }} > {!resolved && showHighlight && (
)}
{title}
{!!comments && (canResolve || canDeleteRoot) && (
{canResolve ? ( ) : null} {canDeleteRoot ? ( ) : null}
)}
{renderComments.map( (item) => ( { if (editing) { setEditingId(item.id); } else { setEditingId(''); } }} onReply={(user) => { if (!user) { return; } requestAnimationFrame(() => { editorRef.current?.reply(transformTextNodes2Document([ { type: 'mention', content: { id: user.userID, label: `@${user.name}`, }, }, { type: 'text', content: ' ', }, ])); }); }} onDeleteComment={onDeleteComment} onAfterDeleteComment={onAfterDeleteComment} /> ) )}
{editorVisible && (
{ const comment: IThreadComment = { text, attachments, dT: getDT(), id: generateRandomId(), ref: refStr!, personId: currentUser?.userID ?? '', parentId: comments?.root.id, unitId, subUnitId, threadId: comments?.root.threadId ?? '', }; if (await onAddComment?.(comment) === false) { if (!comments) { onClose?.(); } return true; } const success = await commandService.executeCommand( AddCommentCommand.id, { unitId, subUnitId, comment, } as IAddCommentCommandParams ); if (success && scrollerRef.current) { scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight; } if (success && !comments) { onClose?.(); } return success; }} autoFocus={autoFocus || (!comments)} onCancel={() => { if (!comments) { onClose?.(); } }} />
)}
); };