import { CloseOutlined, LoadingOutlined } from '@ant-design/icons'; import { css, cx } from '@emotion/css'; import { AllCommentsList } from '@src/components/docs/plugins/SideComment/renderAllCommentsList'; import { ReactEditor } from '@src/components/slate-packages/slate-react'; import '@src/style/less/slatedocs.less'; import { Button, Drawer, Layout, Select, Spin, Tooltip } from 'antd'; import classNames from 'classnames'; import $ from 'jquery'; import { debounce } from 'lodash'; import React, { useEffect, useMemo, useRef, useState } from 'react'; import ReactDOM from 'react-dom'; import { ErrorBoundary } from 'react-error-boundary'; import { HistoryManager } from './components/app/HistoryManager'; import { FallbackComponent } from './components/app/FallbackComponent'; import { HotkeyHelperContent } from './components/app/HotkeyHelper'; import { SideTipContainer } from './components/app/SideTipContainer'; import EditorNative from './components/docs/nativeEditor'; import { IconBtn } from './components/docs/plugins/Components'; import { ELTYPE } from './components/docs/plugins/config'; import { findAndReplace } from './components/docs/plugins/findAndReplace'; import { GlobalComment } from './components/docs/plugins/GlobalComment'; import { MobileToolbar } from './components/docs/plugins/MobileToolbar'; import { OlList, UlList } from './components/docs/plugins/OLULList/OlList'; import { DocTocTitle, OutlineAnchor } from './components/docs/plugins/OutlineAnchor/renderOutlineAnchor'; import { SideCommentCreator } from './components/docs/plugins/SideComment'; import { StaticToolbar } from './components/docs/plugins/StaticToolbar'; import { getEditorEventEmitter } from './components/docs/plugins/table/selection'; import Editor from './components/docs/yjsEditor'; import { Range, Transforms } from './components/slate-packages/slate'; import { f } from './resource/string'; import './style/less/slatedocs-sdk.less'; import { useForceUpdate } from './utils/apiOperations/hooks/useForceUpdate'; import { useWindowUnloadEffect } from './utils/apiOperations/hooks/useWindowUnloadEffect'; import { getCache, setCache } from './utils/cacheUtils'; import { EditorContainerBottomPortal, EditorContainerInnerPortal, EditorContainerOuterPortal } from './utils/createPortal'; import { getDefaultValueByBase64 } from './utils/getDefaultValue'; import './Docs.less'; import { TODOList } from './components/docs/plugins/TodoList/todoList'; import useMeasure from './utils/useMeasure'; const { Content } = Layout; const { Option } = Select; export const TripdocsSdkContext = React.createContext(null); type DocsProps = { userInfo: any; readOnly: boolean; tocPlacement: 'left' | 'right'; deepestDisplayAnchorHeading: 3 | 4 | 5 | 6; socketUrl: string; fileUploadUrl: string; mentionCallback: (mention: any) => void; shareCallback: (share: any) => void; commentCallback: (comment: any) => void; docId: string; defaultValue: any[]; docToken: string; fake: boolean; identityauth2: string; secure: boolean; isMdEditor: boolean; isWideMode: boolean; defaultCommentData: any; showHoveringCommentButton: boolean; showGlobalComment: boolean; showHelpBlock: boolean; theme: { backgroundColor: string }; }; const setEdit = debounce((setIsReadOnly, isNoEdit, docId) => { if (window.tripdocs.editorsMap?.[docId]?.editor && !getCache(docId, 'timeCheck')) { setIsReadOnly(isNoEdit); } }, 1000); const Docs = (props: DocsProps) => { let { userInfo, readOnly, tocPlacement = 'left', deepestDisplayAnchorHeading = 6, socketUrl: sUrl, fileUploadUrl, mentionCallback, shareCallback, commentCallback, docId = 'default', defaultValue: propsDefaultValue, docToken: propsDocToken, fake, identityauth2: idAuth, secure, isMdEditor, isWideMode: propsIsWideMode, defaultCommentData, showHoveringCommentButton, showGlobalComment, showHelpBlock, theme, } = props; const [socketUrl, setSocketUrl] = useState(sUrl); const [defaultValue, setDefaultValue] = useState(propsDefaultValue); const [socketToken, setSocketToken] = useState(propsDocToken); const [socketAuth, setSocketAuth] = useState(idAuth); const [docIds, setDocIds] = useState('default'); const [isShowHotkeyHelper, setIsShowHotkeyHelper] = useState(false); const [isShowHelpBlock, setIsShowHelpBlock] = useState(showHelpBlock); const [isShowHoveringCommentButton, setIsShowHoveringCommentButton] = useState(showHoveringCommentButton); const [isShowGlobalComment, setIsShowGlobalComment] = useState(showGlobalComment); useWindowUnloadEffect(() => { if (window.tripdocs.editorsMap[docId]?.editor?.selection) { window.tripdocs.editorsMap[docId].Transforms.deselect(window.tripdocs.editorsMap[docId].editor); } }, false); try { const [mail, setMail] = useState(''); const [me, setMe] = useState({ id: userInfo.userId, name: userInfo.userName, mail: '', }); useEffect(() => { const newMe = JSON.parse(JSON.stringify(me)); newMe.mail = mail; if (JSON.stringify(newMe) === JSON.stringify(me)) { return; } setMe(newMe); }, [me, mail]); const overlayContainerRef = useRef(); const anchorContainerRef = useRef(); const [filename, setFilename] = useState('未命名文档'); const [foldername, setFoldername] = useState(null); const [fileId, setFileId] = useState(''); const [templateBarShow, setTemplateBar] = useState(true); const [template, setTemplate] = useState(null); const [users, setUsers] = useState([]); const [lastName, setLastName] = useState(''); const [drawerVisible, setDrawerVisible] = useState(false); const [openFindAndReplaceDia, setFindAndReplaceDia] = useState(false); const [searchText, setSearchText] = useState(''); const [replaceText, setReplaceText] = useState(''); const [findSelection, setFindSelection] = useState(''); const [titleLoading, setTitleLoading] = useState(true); const [templateLoading, setTemplateLoading] = useState(true); const [placeholderContentVisible, setPlaceholderContentVisible] = useState(false); const [isReadOnly, setIsReadOnly] = useState(readOnly); const [isNoEdit, setIsNoEdit] = useState(readOnly); const [tocPlace, setTocPlace] = useState(tocPlacement); const [sideCommentRowNum, setSideCommentRowNum] = useState(-1); const [curRangeId, setCurRangeId] = useState(''); const [chars, setChars] = useState([]); const [placeholderRects, setPlaceholderRects] = useState({ titleRect: { top: '34px', left: '74px' }, contentRect: { top: '90px', left: '70px' }, }); const [deepestDisplayAnchor, setDeepestDisplayAnchor] = useState<3 | 4 | 5 | 6>(deepestDisplayAnchorHeading); const [currentColor, setCurrentColor] = useState({ fontColor: 'rgb(255, 0, 0)', bgColor: 'rgb(255, 217, 102)', cellBgColor: 'rgb(243, 243, 243)', }); const [findAndReplaceMethods, setFindAndReplaceMethods] = useState({ highlightRanges: [], editor: undefined as any, setValue: () => {}, }); const [editorSelection, setEditorSelection] = useState({ selection: '', elementPath: [0], elementType: '', }); const [modalState, setModalState] = useState({ setIsModalVisible: () => {}, setModalTitle: () => {}, }); const [docWidth, setDocWidth] = useState(800); const scrollRef = useRef(null); const [editorContainerScrollTop, setEditorContainerScrollTop] = useState(0); const { dep: anchorDep, trigger: anchorTrigger } = useForceUpdate(); const options: Options = getCache(docId, 'options'); const isInElectron: boolean = getCache(docId, 'options')?.isInElectron; const [contentWrapRect, setContentWrapRect] = useState(document?.getElementById(`editor-content-wrap-${docId}`)?.getBoundingClientRect?.()); const [contentRect, setContentRect] = useState(document?.getElementById(`editor-content-${docId}`)?.getBoundingClientRect?.()); const [anchorContainerMaxWidth, setAnchorContainerMaxWidth] = useState(null); const isMobile = useMemo(judgePhone, []); const [ref, { x, y, width, height: minHeight, top, right, bottom, left }] = useMeasure(); const [isLarge, setIsLarge] = useState(true); const [isMiddle, setIsMiddle] = useState(false); const [isWideMode, setIsWideMode] = useState(propsIsWideMode); const [editorHeight, setEditorHeight] = useState(isReadOnly ? '100%' : isMobile ? '100%' : 'calc(100% - 32px)'); const [WIPCommentRangeId, setWIPCommentRangeId] = useState(null); const [isShowHistoryManager, setIsShowHistoryManager] = useState(false); const [loading, setLoading] = useState(false); useEffect(() => { setEditorHeight(isReadOnly ? '100%' : isMobile ? '100%' : 'calc(100% - 32px)'); }, [isReadOnly, isMobile]); useEffect(() => { setTemplateLoading(false); setTitleLoading(false); const contentWrapListener = obj => { setContentWrapRect(obj); }; const contentListener = obj => { setContentRect(obj); }; getEditorEventEmitter(docId).on('resizeContentWrap', contentWrapListener, docId); getEditorEventEmitter(docId).on('resizeContent', contentListener, docId); return () => { getEditorEventEmitter(docId).off('resizeContentWrap', contentWrapListener, docId); getEditorEventEmitter(docId).off('resizeContent', contentListener, docId); }; }, []); useEffect(() => { if (typeof ResizeObserver !== 'undefined' && typeof window !== 'undefined') { const resizeObservers = []; resizeObservers[0] = new ResizeObserver(entries => { const entry = entries[0]; const rect = entry.contentRect; console.log('[resizeContentWrap] resize', rect.width, rect.height); getEditorEventEmitter(docId).emit('resizeContentWrap', docId, rect); getEditorEventEmitter(docId).emit('updateOutlineAnchor', docId); }); document.getElementById(`editor-content-wrap-${docId}`) && resizeObservers[0].observe(document.getElementById(`editor-content-wrap-${docId}`)); resizeObservers[1] = new ResizeObserver(entries => { const rect = entries[0].contentRect; console.log('[resizeContent] resize', rect.width, rect.height); getEditorEventEmitter(docId).emit('resizeContent', docId, rect); }); document.getElementById(`editor-content-${docId}`) && resizeObservers[1].observe(document.getElementById(`editor-content-${docId}`)); } }, [docId]); useEffect(() => { const docDirectoryTitle = document.getElementById(`editor-content-wrap-${docId}`)?.getElementsByClassName('doc-directory-title')?.[0]; console.log('[docDirectoryTitle]', docDirectoryTitle); const maxWidth = (docDirectoryTitle && docDirectoryTitle.getBoundingClientRect().width + 36) || 250; setAnchorContainerMaxWidth(`${Math.floor(maxWidth) - 16}px`); }, [isReadOnly, isWideMode, contentWrapRect?.width, contentRect?.width]); useEffect(() => { window.tripdocs.editorsMap[docId].readOnly = isReadOnly; window.tripdocs.editorsMap[docId].editor.history.undos = []; window.tripdocs.editorsMap[docId].editor.history.redos = []; }, [isReadOnly]); useEffect(() => { setEdit(setIsReadOnly, isNoEdit, docId); setCache(docId, 'isNoEdit', isNoEdit); }, [isNoEdit, socketUrl]); useEffect(() => { window.tripdocs.editorsMap[docId].api.setIsReadOnly = setIsNoEdit; window.tripdocs.editorsMap[docId].api.setSocketUrl = function ( url: string, opt: { defaultValue?: any[]; defaultValue2?: string; docToken?: string; docUrl?: string; identityauth2?: string } = {} ) { Transforms.deselect(window.tripdocs.editorsMap[docId].editor); setCache(docId, 'initTimestamp', new Date().getTime()); setCache(docId, 'timeCheck', true); setCache(docId, 'renderedToDom', false); const { defaultValue, defaultValue2, docToken, docUrl = '', identityauth2 } = opt; let defaultVal; if (defaultValue2) { defaultVal = getDefaultValueByBase64(defaultValue2); } else { defaultVal = defaultValue; } console.log('options', getCache(docId, 'options')); setTemplateLoading(true); const options = getCache(docId, 'options'); setDefaultValue(defaultVal || options.defaultValue); setSocketToken(docToken || options.docToken); setSocketAuth(identityauth2 || options.identityauth2); setCache(docId, 'options', { ...options, socketUrl: url, defaultValue: defaultVal || options.defaultValue, docToken: docToken || options.docToken, docUrl: docUrl, identityauth2: identityauth2, }); console.log('options', getCache(docId, 'options')); setTemplateLoading(false); window.tripdocs.editorsMap[docId].editor.history.undos = []; window.tripdocs.editorsMap[docId].editor.history.redos = []; setSocketUrl(url); }; window.tripdocs.editorsMap[docId].api.setTocPlacement = setTocPlace; window.tripdocs.editorsMap[docId].api.setDeepestDisplayAnchorHeading = setDeepestDisplayAnchor; window.tripdocs.editorsMap[docId].api.setIsShowHoveringCommentButton = setIsShowHoveringCommentButton; window.tripdocs.editorsMap[docId].api.setIsShowGlobalComment = setIsShowGlobalComment; window.tripdocs.editorsMap[docId].api.setIsShowHelpBlock = setIsShowHelpBlock; window.tripdocs.editorsMap[docId].api.setIsShowHistoryManager = setIsShowHistoryManager; }, []); useEffect(() => { if (socketUrl === 'offline') { setCache(docId, 'kickedOut', true); window.tripdocs.editorsMap[docId]?.socket?.provider?.disconnect(); } else { setCache(docId, 'kickedOut', false); } }, [socketUrl]); useEffect(() => { let timeout; if (scrollRef.current) { setCache(docId, 'editorWrapDom', scrollRef.current); } const handler = () => { if (scrollRef.current) { if (timeout) clearTimeout(timeout); timeout = setTimeout(() => { if (!getCache(docId, 'options')?.isMdEditor) { setEditorContainerScrollTop(scrollRef.current.scrollTop); } }, 500); } }; if (scrollRef.current) { (scrollRef.current as any).addEventListener('scroll', handler, { capture: false, passive: true, }); } return () => { if (scrollRef.current) { (scrollRef.current as any).removeEventListener('scroll', handler); } }; }, [scrollRef]); useEffect(() => { me && me.name && setLastName(me?.name?.split(')')[0].slice(-2)); }, [me]); useEffect(() => { const editor = findAndReplaceMethods?.editor; if (typeof window !== 'undefined' && window.document.getElementById(`editorContainer-${docId}`) && editor) { const childrenArr = editor.children.slice(); const titleEl = childrenArr.shift(); const titleDom = ReactEditor.toDOMNode(editor, titleEl); titleDom && titleDom.classList.add('editor-titleEl'); } }, []); const titleCallback = (title: any) => { const callback = window.tripdocs.editorsMap[docId]?.api?.titleCallback; callback && callback(title); if (title) setFilename(title); else setFilename('未命名文档'); }; const isEmptyCallback = (boo: boolean) => { if (boo) { setTemplateBar(false); } else { setTemplateBar(true); } }; useEffect(() => { if (width > 1280) { setIsLarge(true); setDrawerVisible(false); } else if (width > 936) { setIsMiddle(true); setIsLarge(false); } else if (0 < width && width < 936) { setIsLarge(false); setIsMiddle(false); } }, [width]); const [isShowAnchor, setIsShowAnchor] = useState(true); const [isAnchorCollapsed, setIsAnchorCollapsed] = useState(false); const handleDeepestHeading = e => { console.log(3000000, e); setDeepestDisplayAnchor(e.target.value); }; const getHeadTablevel = (type, oldType) => { let ret = {}; ret[ELTYPE.HEADING_ONE] = 0; ret[ELTYPE.HEADING_TWO] = 1; ret[ELTYPE.HEADING_THREE] = 2; ret[ELTYPE.HEADING_FOUR] = 3; ret[ELTYPE.HEADING_FIVE] = 4; ret[ELTYPE.HEADING_SIX] = 5; return ret[type] || ret[oldType] || 0; }; const getText = el => { if (el && el.text) return el.text; if (el && el.children) return getText(el.children); if (el && Array.isArray(el)) return el.map((item: any) => getText(item)); return ''; }; const wrapTextWithStyle = (item, text) => { if (!item?.type) return text; const { type } = item; let styled = text; switch (type) { case 'bulleted-list': if (isMobile) { styled =