DocSpace-client/web/ASC.Web.Editor/src/Editor.jsx

790 lines
21 KiB
React
Raw Normal View History

2021-03-06 15:50:06 +00:00
import React, { useEffect, useState } from "react";
2021-03-05 18:15:48 +00:00
import Toast from "@appserver/components/toast";
import toastr from "studio/toastr";
import { toast } from "react-toastify";
import { Trans } from "react-i18next";
2021-03-05 18:15:48 +00:00
import Box from "@appserver/components/box";
import { regDesktop } from "@appserver/common/desktop";
import Loaders from "@appserver/common/components/Loaders";
import {
2021-03-22 09:12:34 +00:00
combineUrl,
2021-03-05 18:15:48 +00:00
getObjectByLocation,
2021-08-19 10:31:17 +00:00
loadScript,
2021-03-05 18:15:48 +00:00
//showLoader,
//hideLoader,
} from "@appserver/common/utils";
import {
getDocServiceUrl,
openEdit,
setEncryptionKeys,
getEncryptionAccess,
getFileInfo,
2021-07-27 06:51:56 +00:00
getRecentFolderList,
getFolderInfo,
2021-07-27 07:36:21 +00:00
updateFile,
removeFromFavorite,
markAsFavorite,
getPresignedUri,
convertFile,
2021-03-05 18:15:48 +00:00
} from "@appserver/common/api/files";
import FilesFilter from "@appserver/common/api/files/filter";
2021-03-05 18:15:48 +00:00
import throttle from "lodash/throttle";
2021-03-06 15:50:06 +00:00
import { isIOS, deviceType } from "react-device-detect";
import { homepage } from "../package.json";
import { AppServerConfig, FolderType } from "@appserver/common/constants";
import SharingDialog from "files/SharingDialog";
import { getDefaultFileName, SaveAs, canConvert } from "files/utils";
2021-07-08 11:13:00 +00:00
import SelectFileDialog from "files/SelectFileDialog";
2021-07-09 07:49:57 +00:00
import SelectFolderDialog from "files/SelectFolderDialog";
2021-08-04 09:42:59 +00:00
import { StyledSelectFolder, StyledSelectFile } from "./StyledEditor";
import i18n from "./i18n";
import Text from "@appserver/components/text";
import TextInput from "@appserver/components/text-input";
import Checkbox from "@appserver/components/checkbox";
2021-08-05 11:05:09 +00:00
import store from "studio/store";
const { auth: authStore } = store;
2021-03-05 18:15:48 +00:00
let documentIsReady = false;
const text = "text";
const spreadSheet = "spreadsheet";
const presentation = "presentation";
const insertImageAction = "imageFileType";
const mailMergeAction = "mailMergeFileType";
const compareFilesAction = "documentsFileType";
2021-03-05 18:15:48 +00:00
let docTitle = null;
let actionLink;
2021-03-05 18:15:48 +00:00
let docSaved = null;
2021-03-26 12:05:41 +00:00
let docEditor;
let fileInfo;
let successAuth;
let isSharingAccess;
let user = null;
let personal;
const url = window.location.href;
const filesUrl = url.substring(0, url.indexOf("/doceditor"));
toast.configure();
2021-04-01 08:50:30 +00:00
const Editor = () => {
2021-03-06 15:50:06 +00:00
const urlParams = getObjectByLocation(window.location);
const fileId = urlParams
? urlParams.fileId || urlParams.fileid || null
: null;
2021-04-23 15:00:05 +00:00
const version = urlParams ? urlParams.version || null : null;
2021-03-06 15:50:06 +00:00
const doc = urlParams ? urlParams.doc || null : null;
const isDesktop = window["AscDesktopEditor"] !== undefined;
const [isLoading, setIsLoading] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(true);
const [titleSelectorFolder, setTitleSelectorFolder] = useState("");
2021-08-03 07:09:08 +00:00
const [extension, setExtension] = useState();
const [urlSelectorFolder, setUrlSelectorFolder] = useState("");
const [openNewTab, setNewOpenTab] = useState(false);
2021-03-05 18:15:48 +00:00
const throttledChangeTitle = throttle(() => changeTitle(), 500);
2021-03-26 12:05:41 +00:00
useEffect(() => {
init();
2021-03-26 12:05:41 +00:00
}, []);
const loadUsersRightsList = () => {
SharingDialog.getSharingSettings(fileId).then((sharingSettings) => {
docEditor.setSharingSettings({
sharingSettings,
});
});
};
const insertImage = (link) => {
docEditor.insertImage({
c: "add",
fileType: link.filetype,
url: link.url,
});
};
const mailMerge = (link) => {
2021-08-04 08:32:14 +00:00
docEditor.setMailMergeRecipients({
fileType: link.filetype,
url: link.url,
2021-08-04 08:32:14 +00:00
});
};
const compareFiles = (link) => {
docEditor.setRevisedFile({
fileType: link.filetype,
url: link.url,
});
};
const updateFavorite = (favorite) => {
docEditor.setFavorite(favorite);
};
const getRecent = async (config) => {
try {
const recentFolderList = await getRecentFolderList();
const filesArray = recentFolderList.files.slice(0, 25);
const recentFiles = filesArray.filter(
(file) =>
file.rootFolderType !== FolderType.SHARE &&
((config.documentType === text && file.fileType === 7) ||
(config.documentType === spreadSheet && file.fileType === 5) ||
(config.documentType === presentation && file.fileType === 6))
);
const groupedByFolder = recentFiles.reduce((r, a) => {
r[a.folderId] = [...(r[a.folderId] || []), a];
return r;
}, {});
const requests = Object.entries(groupedByFolder).map((item) =>
getFolderInfo(item[0])
.then((folderInfo) =>
Promise.resolve({
files: item[1],
folderInfo: folderInfo,
})
)
.catch((e) => console.error(e))
);
let recent = [];
let responses = await Promise.all(requests);
for (let res of responses) {
res.files.forEach((file) => {
const convertedData = convertRecentData(file, res.folderInfo);
if (Object.keys(convertedData).length !== 0)
recent.push(convertedData);
});
}
return recent;
} catch (e) {
console.error(e);
}
return null;
};
const initDesktop = (config) => {
const isEncryption = config.editorConfig["encryptionKeys"] !== undefined;
regDesktop(
user,
isEncryption,
config.editorConfig.encryptionKeys,
(keys) => {
setEncryptionKeys(keys);
},
true,
(callback) => {
getEncryptionAccess(fileId)
.then((keys) => {
var data = {
keys,
};
callback(data);
})
.catch((error) => {
console.log(error);
toastr.error(
typeof error === "string" ? error : error.message,
null,
0,
true
);
});
},
i18n.t
);
};
2021-03-06 15:50:06 +00:00
const init = async () => {
try {
2021-03-05 18:15:48 +00:00
if (!fileId) return;
2021-04-23 15:00:05 +00:00
console.log(
`Editor componentDidMount fileId=${fileId}, version=${version}, doc=${doc}`
);
2021-03-05 18:15:48 +00:00
if (isIPad()) {
const vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty("--vh", `${vh}px`);
}
//showLoader();
const docApiUrl = await getDocServiceUrl();
try {
await authStore.init(true);
user = authStore.userStore.user;
personal = authStore.settingsStore.personal;
2021-08-23 15:20:36 +00:00
successAuth = !!user;
} catch (e) {
successAuth = false;
}
2021-03-05 18:15:48 +00:00
if (!doc && !successAuth) {
window.open(
combineUrl(AppServerConfig.proxyURL, "/login"),
"_self",
"",
true
);
return;
}
2021-03-05 18:15:48 +00:00
if (successAuth) {
try {
fileInfo = await getFileInfo(fileId);
if (url.indexOf("#message/") > -1) {
const needConvert = canConvert(fileInfo.fileExst);
if (needConvert) {
const convert = await convertFile(fileId, true);
location.href = convert[0].result.webUrl;
}
}
} catch (err) {
console.error(err);
2021-03-06 15:50:06 +00:00
}
setIsAuthenticated(successAuth);
2021-03-05 18:15:48 +00:00
}
const config = await openEdit(fileId, version, doc);
actionLink = config?.editorConfig?.actionLink;
2021-03-05 18:15:48 +00:00
if (isDesktop) {
initDesktop();
2021-03-05 18:15:48 +00:00
}
2021-07-27 06:51:56 +00:00
if (successAuth) {
const recent = await getRecent(config); //TODO: too slow for 1st loading
if (recent) {
config.editorConfig = {
...config.editorConfig,
recent: recent,
};
2021-07-27 06:51:56 +00:00
}
}
2021-03-05 18:15:48 +00:00
isSharingAccess = fileInfo && fileInfo.canShare;
if (url.indexOf("action=view") !== -1) {
config.editorConfig.mode = "view";
}
2021-03-06 15:50:06 +00:00
setIsLoading(false);
2021-08-19 10:31:17 +00:00
loadScript(docApiUrl, "scripDocServiceAddress", () => onLoad(config));
2021-03-05 18:15:48 +00:00
} catch (error) {
console.log(error);
toastr.error(
typeof error === "string" ? error : error.message,
null,
0,
true
);
}
2021-03-06 15:50:06 +00:00
};
2021-07-27 06:51:56 +00:00
const convertRecentData = (file, folder) => {
let obj = {};
const folderName = folder.title;
const fileName = file.title;
if (+fileId !== file.id)
2021-07-27 06:51:56 +00:00
obj = {
folder: folderName,
title: fileName,
url: file.webUrl,
2021-07-27 06:51:56 +00:00
};
return obj;
};
2021-03-06 15:50:06 +00:00
const isIPad = () => {
return isIOS && deviceType === "tablet";
};
2021-08-09 13:15:17 +00:00
const setFavicon = (documentType) => {
2021-03-06 15:50:06 +00:00
const favicon = document.getElementById("favicon");
if (!favicon) return;
let icon = null;
2021-08-09 13:15:17 +00:00
switch (documentType) {
case "text":
2021-03-06 15:50:06 +00:00
icon = "text.ico";
break;
2021-08-09 13:15:17 +00:00
case "presentation":
2021-03-06 15:50:06 +00:00
icon = "presentation.ico";
break;
2021-08-09 13:15:17 +00:00
case "spreadsheet":
2021-03-06 15:50:06 +00:00
icon = "spreadsheet.ico";
break;
default:
break;
}
if (icon) favicon.href = `${homepage}/images/${icon}`;
};
const changeTitle = () => {
2021-03-06 15:50:06 +00:00
docSaved ? setDocumentTitle(docTitle) : setDocumentTitle(`*${docTitle}`);
};
const setDocumentTitle = (subTitle = null) => {
//const { isAuthenticated, settingsStore, product: currentModule } = auth;
//const { organizationName } = settingsStore;
const organizationName = "ONLYOFFICE"; //TODO: Replace to API variant
const moduleTitle = "Documents"; //TODO: Replace to API variant
let title;
if (subTitle) {
if (isAuthenticated && moduleTitle) {
title = subTitle + " - " + moduleTitle;
} else {
title = subTitle + " - " + organizationName;
}
} else if (moduleTitle && organizationName) {
title = moduleTitle + " - " + organizationName;
} else {
title = organizationName;
}
document.title = title;
};
const onLoad = (config) => {
2021-03-05 18:15:48 +00:00
try {
if (!window.DocsAPI) throw new Error("DocsAPI is not defined");
console.log("Editor config: ", config);
2021-03-05 18:15:48 +00:00
docTitle = config.document.title;
2021-08-09 13:15:17 +00:00
setFavicon(config.documentType);
2021-03-05 18:15:48 +00:00
setDocumentTitle(docTitle);
if (window.innerWidth < 720) {
config.type = "mobile";
}
let goBack;
if (fileInfo) {
const filterObj = FilesFilter.getDefault();
filterObj.folder = fileInfo.folderId;
const urlFilter = filterObj.toUrlParams();
goBack = {
blank: true,
requestClose: false,
text: i18n.t("FileLocation"),
url: `${combineUrl(filesUrl, `/filter?${urlFilter}`)}`,
};
}
config.editorConfig.customization = {
...config.editorConfig.customization,
goback: goBack,
};
if (personal && !fileInfo) {
//TODO: add conditions for SaaS
config.document.info.favorite = null;
}
2021-08-05 11:05:09 +00:00
if (url.indexOf("anchor") !== -1) {
const splitUrl = url.split("anchor=");
const decodeURI = decodeURIComponent(splitUrl[1]);
const obj = JSON.parse(decodeURI);
config.editorConfig.actionLink = {
action: obj.action,
};
}
if (successAuth) {
const documentType = config.documentType;
const fileExt =
documentType === text
? "docx"
: documentType === presentation
? "pptx"
: "xlsx";
const defaultFileName = getDefaultFileName(fileExt);
if (!user.isVisitor)
config.editorConfig.createUrl = combineUrl(
window.location.origin,
AppServerConfig.proxyURL,
"products/files/",
`/httphandlers/filehandler.ashx?action=create&doctype=text&title=${encodeURIComponent(
defaultFileName
)}`
);
}
2021-07-30 12:16:53 +00:00
let onRequestSharingSettings,
onRequestRename,
onRequestSaveAs,
2021-08-04 08:32:14 +00:00
onRequestInsertImage,
onRequestMailMergeRecipients,
onRequestCompareFile;
if (isSharingAccess) {
onRequestSharingSettings = onSDKRequestSharingSettings;
}
if (fileInfo && fileInfo.canEdit) {
onRequestRename = onSDKRequestRename;
}
if (successAuth) {
onRequestSaveAs = onSDKRequestSaveAs;
onRequestInsertImage = onSDKRequestInsertImage;
2021-08-04 08:32:14 +00:00
onRequestMailMergeRecipients = onSDKRequestMailMergeRecipients;
onRequestCompareFile = onSDKRequestCompareFile;
}
2021-03-05 18:15:48 +00:00
const events = {
events: {
2021-03-06 15:50:06 +00:00
onAppReady: onSDKAppReady,
onDocumentStateChange: onDocumentStateChange,
onMetaChange: onMetaChange,
onDocumentReady: onDocumentReady,
onInfo: onSDKInfo,
onWarning: onSDKWarning,
onError: onSDKError,
onRequestSharingSettings,
2021-07-27 07:36:21 +00:00
onRequestRename,
2021-08-05 11:05:09 +00:00
onMakeActionLink: onMakeActionLink,
2021-07-08 10:57:53 +00:00
onRequestInsertImage,
2021-07-09 07:49:57 +00:00
onRequestSaveAs,
2021-08-04 08:32:14 +00:00
onRequestMailMergeRecipients,
onRequestCompareFile,
2021-03-05 18:15:48 +00:00
},
};
const newConfig = Object.assign(config, events);
2021-03-26 12:05:41 +00:00
docEditor = window.DocsAPI.DocEditor("editor", newConfig);
2021-03-05 18:15:48 +00:00
} catch (error) {
console.log(error);
toastr.error(error.message, null, 0, true);
}
};
2021-03-06 15:50:06 +00:00
const onSDKAppReady = () => {
2021-03-26 14:35:44 +00:00
console.log("ONLYOFFICE Document Editor is ready");
const index = url.indexOf("#message/");
if (index > -1) {
const splitUrl = url.split("#message/");
const message = decodeURIComponent(splitUrl[1]).replaceAll("+", " ");
history.pushState({}, null, url.substring(0, index));
docEditor.showMessage(message);
}
2021-03-05 18:15:48 +00:00
};
2021-03-06 15:50:06 +00:00
const onSDKInfo = (event) => {
2021-03-05 18:15:48 +00:00
console.log(
"ONLYOFFICE Document Editor is opened in mode " + event.data.mode
);
};
const [isVisible, setIsVisible] = useState(false);
2021-07-09 07:51:26 +00:00
const [isFileDialogVisible, setIsFileDialogVisible] = useState(false);
2021-07-09 07:49:57 +00:00
const [isFolderDialogVisible, setIsFolderDialogVisible] = useState(false);
2021-08-04 09:42:59 +00:00
const [filesType, setFilesType] = useState("");
2021-03-26 12:05:41 +00:00
const onSDKRequestSharingSettings = () => {
setIsVisible(true);
};
2021-07-27 07:36:21 +00:00
const onSDKRequestRename = (event) => {
const title = event.data;
updateFile(fileInfo.id, title);
};
2021-08-05 11:05:09 +00:00
const onMakeActionLink = (event) => {
var ACTION_DATA = event.data;
const link = generateLink(ACTION_DATA);
const urlFormation = !actionLink ? url : url.split("&anchor=")[0];
2021-08-05 11:05:09 +00:00
const linkFormation = `${urlFormation}&anchor=${link}`;
docEditor.setActionLink(linkFormation);
};
const generateLink = (actionData) => {
return encodeURIComponent(JSON.stringify(actionData));
};
const onCancel = () => {
setIsVisible(false);
2021-03-26 12:05:41 +00:00
};
2021-03-06 15:50:06 +00:00
const onSDKWarning = (event) => {
2021-03-05 18:15:48 +00:00
console.log(
"ONLYOFFICE Document Editor reports a warning: code " +
event.data.warningCode +
", description " +
event.data.warningDescription
);
};
2021-03-06 15:50:06 +00:00
const onSDKError = (event) => {
2021-03-05 18:15:48 +00:00
console.log(
"ONLYOFFICE Document Editor reports an error: code " +
event.data.errorCode +
", description " +
event.data.errorDescription
);
};
2021-03-06 15:50:06 +00:00
const onDocumentStateChange = (event) => {
2021-03-05 18:15:48 +00:00
if (!documentIsReady) return;
docSaved = !event.data;
throttledChangeTitle();
};
2021-03-06 15:50:06 +00:00
const onDocumentReady = () => {
2021-03-05 18:15:48 +00:00
documentIsReady = true;
if (isSharingAccess) {
loadUsersRightsList();
}
2021-03-05 18:15:48 +00:00
};
2021-03-06 15:50:06 +00:00
const onMetaChange = (event) => {
2021-03-05 18:15:48 +00:00
const newTitle = event.data.title;
const favorite = event.data.favorite;
2021-03-05 18:15:48 +00:00
if (newTitle && newTitle !== docTitle) {
setDocumentTitle(newTitle);
docTitle = newTitle;
}
if (!newTitle)
favorite
? markAsFavorite([+fileId])
.then(() => updateFavorite(favorite))
.catch((error) => console.log("error", error))
: removeFromFavorite([+fileId])
.then(() => updateFavorite(favorite))
.catch((error) => console.log("error", error));
2021-03-05 18:15:48 +00:00
};
2021-08-17 09:52:33 +00:00
const onSDKRequestInsertImage = () => {
2021-08-04 08:32:14 +00:00
setFilesType(insertImageAction);
setIsFileDialogVisible(true);
};
2021-08-17 09:52:33 +00:00
const onSDKRequestMailMergeRecipients = () => {
2021-08-04 08:32:14 +00:00
setFilesType(mailMergeAction);
2021-07-09 07:51:26 +00:00
setIsFileDialogVisible(true);
2021-07-08 10:57:53 +00:00
};
const onSDKRequestCompareFile = () => {
setFilesType(compareFilesAction);
setIsFileDialogVisible(true);
};
const onSelectFile = async (file) => {
try {
const link = await getPresignedUri(file.id);
if (filesType === insertImageAction) insertImage(link);
if (filesType === mailMergeAction) mailMerge(link);
if (filesType === compareFilesAction) compareFiles(link);
} catch (e) {
console.error(e);
}
2021-07-08 10:57:53 +00:00
};
2021-07-09 07:51:26 +00:00
const onCloseFileDialog = () => {
setIsFileDialogVisible(false);
2021-07-08 10:57:53 +00:00
};
const onSDKRequestSaveAs = (event) => {
setTitleSelectorFolder(event.data.title);
setUrlSelectorFolder(event.data.url);
2021-08-03 07:09:08 +00:00
setExtension(event.data.title.split(".").pop());
2021-07-09 07:49:57 +00:00
setIsFolderDialogVisible(true);
2021-07-09 07:49:57 +00:00
};
const onCloseFolderDialog = () => {
setIsFolderDialogVisible(false);
setNewOpenTab(false);
2021-07-09 07:49:57 +00:00
};
const onClickSaveSelectFolder = (e, folderId) => {
const currentExst = titleSelectorFolder.split(".").pop();
const title =
currentExst !== extension
? titleSelectorFolder.concat(`.${extension}`)
: titleSelectorFolder;
SaveAs(title, urlSelectorFolder, folderId, openNewTab);
};
const onChangeInput = (e) => {
setTitleSelectorFolder(e.target.value);
};
2021-08-04 08:32:14 +00:00
const onClickCheckbox = () => {
setNewOpenTab(!openNewTab);
};
2021-08-04 08:32:14 +00:00
const getFileTypeTranslation = () => {
2021-08-27 11:21:51 +00:00
switch (filesType) {
case mailMergeAction:
return i18n.t("MailMergeFileType");
case insertImageAction:
return i18n.t("ImageFileType");
case compareFilesAction:
return i18n.t("DocumentsFileType");
}
};
const SelectFileHeader = () => {
return (
<StyledSelectFile>
<Text className="editor-select-file_text">
{filesType === mailMergeAction ? (
2021-08-27 11:13:50 +00:00
getFileTypeTranslation()
) : (
<Trans i18n={i18n} i18nKey="SelectFilesType" ns="Editor">
Select files of type: {{ fileType: getFileTypeTranslation() }}
</Trans>
)}
</Text>
</StyledSelectFile>
);
};
2021-08-04 08:32:14 +00:00
const insertImageActionProps = {
isImageOnly: true,
};
const mailMergeActionProps = {
isTablesOnly: true,
searchParam: "xlsx",
};
const compareFilesActionProps = {
isDocumentsOnly: true,
};
2021-08-04 08:32:14 +00:00
const fileTypeDetection = () => {
if (filesType === insertImageAction) {
return insertImageActionProps;
}
if (filesType === mailMergeAction) {
return mailMergeActionProps;
}
if (filesType === compareFilesAction) {
return compareFilesActionProps;
}
};
2021-08-04 08:32:14 +00:00
2021-03-06 15:50:06 +00:00
return (
<Box
widthProp="100vw"
heightProp={isIPad() ? "calc(var(--vh, 1vh) * 100)" : "100vh"}
>
<Toast />
2021-03-06 15:50:06 +00:00
{!isLoading ? (
<>
<div id="editor"></div>
{isSharingAccess && (
<SharingDialog
isVisible={isVisible}
sharingObject={fileInfo}
onCancel={onCancel}
onSuccess={loadUsersRightsList}
/>
)}
2021-07-08 10:57:53 +00:00
{isFileDialogVisible && (
<SelectFileDialog
2021-08-19 16:08:58 +00:00
resetTreeFolders
onSelectFile={onSelectFile}
isPanelVisible={isFileDialogVisible}
onClose={onCloseFileDialog}
foldersType="exceptTrashFolder"
{...fileTypeDetection()}
2021-08-04 08:32:14 +00:00
header={<SelectFileHeader />}
headerName={i18n.t("SelectFileTitle")}
/>
)}
2021-07-09 07:49:57 +00:00
{isFolderDialogVisible && (
<SelectFolderDialog
2021-08-19 16:08:58 +00:00
resetTreeFolders
showButtons
isPanelVisible={isFolderDialogVisible}
isSetFolderImmediately
asideHeightContent="calc(100% - 50px)"
onClose={onCloseFolderDialog}
foldersType="exceptSortedByTags"
onSave={onClickSaveSelectFolder}
header={
2021-08-04 09:42:59 +00:00
<StyledSelectFolder>
<Text className="editor-select-folder_text">
{i18n.t("FileName")}
</Text>
<TextInput
2021-08-04 09:42:59 +00:00
className="editor-select-folder_text-input"
scale
onChange={onChangeInput}
value={titleSelectorFolder}
/>
2021-08-04 09:42:59 +00:00
</StyledSelectFolder>
}
headerName={i18n.t("FolderForSave")}
2021-08-03 07:09:08 +00:00
{...(extension !== "fb2" && {
footer: (
2021-08-04 09:42:59 +00:00
<StyledSelectFolder>
<Checkbox
className="editor-select-folder_checkbox"
label={i18n.t("OpenSavedDocument")}
onChange={onClickCheckbox}
isChecked={openNewTab}
/>
</StyledSelectFolder>
2021-08-03 07:09:08 +00:00
),
})}
/>
)}
</>
2021-03-06 15:50:06 +00:00
) : (
<Box paddingProp="16px">
<Loaders.Rectangle height="96vh" />
</Box>
)}
</Box>
);
};
2021-03-05 18:15:48 +00:00
export default Editor;