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

570 lines
14 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";
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,
//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,
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 } from "files/utils";
import i18n from "./i18n";
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";
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;
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);
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 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;
successAuth = user !== null;
} 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);
} 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 = 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);
loadDocApi(docApiUrl, () => 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 loadDocApi = (docApiUrl, onLoadCallback) => {
2021-03-05 18:15:48 +00:00
const script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("id", "scripDocServiceAddress");
script.onload = onLoadCallback;
script.src = docApiUrl;
script.async = true;
console.log("PureEditor componentDidMount: added script");
document.body.appendChild(script);
};
2021-03-06 15:50:06 +00:00
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,
};
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
)}`
);
}
let onRequestSharingSettings;
2021-07-27 07:36:21 +00:00
let onRequestRename;
if (isSharingAccess) {
onRequestSharingSettings = onSDKRequestSharingSettings;
}
if (fileInfo && fileInfo.canEdit) {
onRequestRename = onSDKRequestRename;
}
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-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("+", " ");
message && toastr.info(message);
history.pushState({}, null, url.substring(0, index));
}
if (fileInfo && fileInfo.canShare) {
loadUsersRightsList();
}
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-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;
};
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-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-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;