slate/components/core/Application.js

550 lines
17 KiB
JavaScript
Raw Normal View History

import * as React from "react";
import * as NavigationData from "~/common/navigation-data";
import * as Actions from "~/common/actions";
import * as Strings from "~/common/strings";
2021-05-06 03:08:14 +03:00
import * as Styles from "~/common/styles";
import * as Credentials from "~/common/credentials";
2020-10-05 00:30:28 +03:00
import * as Constants from "~/common/constants";
import * as Validations from "~/common/validations";
2020-09-12 08:54:54 +03:00
import * as Window from "~/common/window";
import * as Websockets from "~/common/browser-websockets";
2020-11-19 21:14:09 +03:00
import * as UserBehaviors from "~/common/user-behaviors";
import * as Events from "~/common/custom-events";
import * as Logging from "~/common/logging";
2021-07-27 15:01:44 +03:00
import * as Environment from "~/common/environment";
// NOTE(jim):
// Scenes each have an ID and can be navigated to with _handleAction
2021-05-06 03:08:14 +03:00
import SceneError from "~/scenes/SceneError";
import SceneEditAccount from "~/scenes/SceneEditAccount";
import SceneFile from "~/scenes/SceneFile";
import SceneFilesFolder from "~/scenes/SceneFilesFolder";
import SceneSettings from "~/scenes/SceneSettings";
import SceneSlates from "~/scenes/SceneSlates";
import SceneSettingsDeveloper from "~/scenes/SceneSettingsDeveloper";
2021-06-09 01:53:30 +03:00
import SceneAuth from "~/scenes/SceneAuth";
import SceneSlate from "~/scenes/SceneSlate";
2020-08-08 03:17:54 +03:00
import SceneActivity from "~/scenes/SceneActivity";
import SceneDirectory from "~/scenes/SceneDirectory";
import SceneProfile from "~/scenes/SceneProfile";
import SceneArchive from "~/scenes/SceneArchive";
import SceneMakeFilecoinDeal from "~/scenes/SceneMakeFilecoinDeal";
// NOTE(jim):
// Sidebars each have a decorator and can be shown to with _handleAction
import SidebarCreateSlate from "~/components/sidebars/SidebarCreateSlate";
import SidebarCreateWalletAddress from "~/components/sidebars/SidebarCreateWalletAddress";
import SidebarWalletSendFunds from "~/components/sidebars/SidebarWalletSendFunds";
import SidebarFileStorageDeal from "~/components/sidebars/SidebarFileStorageDeal";
2020-09-23 23:52:00 +03:00
import SidebarAddFileToSlate from "~/components/sidebars/SidebarAddFileToSlate";
import SidebarDragDropNotice from "~/components/sidebars/SidebarDragDropNotice";
import SidebarSingleSlateSettings from "~/components/sidebars/SidebarSingleSlateSettings";
import SidebarFilecoinArchive from "~/components/sidebars/SidebarFilecoinArchive";
2020-09-17 02:26:15 +03:00
import SidebarHelp from "~/components/sidebars/SidebarHelp";
2020-11-10 00:20:38 +03:00
import SidebarFAQ from "~/components/sidebars/SidebarFAQ";
2021-03-30 05:06:42 +03:00
import SidebarEditTags from "~/components/sidebars/SidebarEditTags";
// NOTE(jim):
// Core components to the application structure.
import ApplicationHeader from "~/components/core/ApplicationHeader";
import ApplicationLayout from "~/components/core/ApplicationLayout";
import WebsitePrototypeWrapper from "~/components/core/WebsitePrototypeWrapper";
2021-05-06 03:08:14 +03:00
import CTATransition from "~/components/core/CTATransition";
import { GlobalModal } from "~/components/system/components/GlobalModal";
2020-10-27 07:14:13 +03:00
import { OnboardingModal } from "~/components/core/OnboardingModal";
2020-11-10 00:20:38 +03:00
import { SearchModal } from "~/components/core/SearchModal";
import { CollectionSharingModal } from "~/components/core/ShareModals/CollectionSharingModal";
import { Alert } from "~/components/core/Alert";
import { announcements } from "~/components/core/OnboardingModal";
import { Logo } from "~/common/logo";
2021-05-06 03:08:14 +03:00
import { LoaderSpinner } from "~/components/system/components/Loaders";
2020-09-03 09:00:02 +03:00
const SIDEBARS = {
SIDEBAR_FILECOIN_ARCHIVE: <SidebarFilecoinArchive />,
SIDEBAR_FILE_STORAGE_DEAL: <SidebarFileStorageDeal />,
SIDEBAR_WALLET_SEND_FUNDS: <SidebarWalletSendFunds />,
SIDEBAR_CREATE_WALLET_ADDRESS: <SidebarCreateWalletAddress />,
2020-09-23 23:52:00 +03:00
SIDEBAR_ADD_FILE_TO_SLATE: <SidebarAddFileToSlate />,
SIDEBAR_CREATE_SLATE: <SidebarCreateSlate />,
SIDEBAR_DRAG_DROP_NOTICE: <SidebarDragDropNotice />,
SIDEBAR_SINGLE_SLATE_SETTINGS: <SidebarSingleSlateSettings />,
2020-09-17 02:26:15 +03:00
SIDEBAR_HELP: <SidebarHelp />,
2020-11-10 00:20:38 +03:00
SIDEBAR_FAQ: <SidebarFAQ />,
2021-03-30 05:06:42 +03:00
SIDEBAR_EDIT_TAGS: <SidebarEditTags />,
};
const SCENES = {
2021-05-06 03:08:14 +03:00
NAV_ERROR: <SceneError />,
2021-06-09 01:53:30 +03:00
NAV_SIGN_IN: <SceneAuth />,
2021-07-27 15:01:44 +03:00
...(Environment.ACTIVITY_FEATURE_FLAG ? { NAV_ACTIVITY: <SceneActivity /> } : {}),
2021-05-06 03:08:14 +03:00
NAV_DIRECTORY: <SceneDirectory />,
NAV_PROFILE: <SceneProfile />,
NAV_DATA: <SceneFilesFolder />,
// NAV_FILE: <SceneFile />,
NAV_SLATE: <SceneSlate />,
NAV_API: <SceneSettingsDeveloper />,
NAV_SETTINGS: <SceneEditAccount />,
NAV_SLATES: <SceneSlates />,
NAV_FILECOIN: <SceneArchive />,
NAV_STORAGE_DEAL: <SceneMakeFilecoinDeal />,
};
let mounted;
export default class ApplicationPage extends React.Component {
_body;
state = {
selected: {},
viewer: this.props.viewer,
2021-05-06 03:08:14 +03:00
page: this.props.page || {},
data: this.props.data,
activePage: this.props.page?.id,
sidebar: null,
2020-08-03 00:09:55 +03:00
online: null,
isMobile: this.props.isMobile,
2021-02-04 12:21:59 +03:00
activeUsers: null,
2021-05-06 03:08:14 +03:00
loading: false,
};
async componentDidMount() {
2021-07-07 23:50:57 +03:00
// window.iframely && iframely.load();
2021-05-06 03:08:14 +03:00
this._handleWindowResize();
if (mounted) {
return false;
}
mounted = true;
2020-08-03 00:09:55 +03:00
window.addEventListener("online", this._handleOnlineStatus);
window.addEventListener("offline", this._handleOnlineStatus);
window.addEventListener("resize", this._handleWindowResize);
2020-12-19 08:25:50 +03:00
window.onpopstate = this._handleBackForward;
2020-09-12 08:54:54 +03:00
if (this.state.viewer) {
2020-11-20 07:03:30 +03:00
await this._handleSetupWebsocket();
}
}
componentWillUnmount() {
window.removeEventListener("online", this._handleOnlineStatus);
window.removeEventListener("offline", this._handleOnlineStatus);
window.removeEventListener("resize", this._handleWindowResize);
mounted = false;
let wsclient = Websockets.getClient();
if (wsclient) {
Websockets.deleteClient();
}
}
2021-05-06 03:08:14 +03:00
_handleUpdateViewer = ({ viewer, callback }) => {
// _handleUpdateViewer = (newViewerState, callback) => {
2020-12-15 04:43:16 +03:00
// let setAsyncState = (newState) =>
// new Promise((resolve) =>
// this.setState(
// {
// viewer: { ...this.state.viewer, ...newState, type: "VIEWER" },
// },
// resolve
// )
// );
// await setAsyncState(newViewerState);
//NOTE(martina): if updating viewer affects this.state.data (e.g. you're viewing your own slate), update data as well
2021-05-06 03:08:14 +03:00
if (viewer?.slates?.length) {
const page = this.state.page;
if (page?.id === "NAV_SLATE" && this.state.data?.ownerId === this.state.viewer.id) {
let data = this.state.data;
2021-05-06 03:08:14 +03:00
for (let slate of viewer.slates) {
if (slate.id === data.id) {
data = slate;
break;
}
}
this.setState(
{
2021-05-06 03:08:14 +03:00
viewer: { ...this.state.viewer, ...viewer },
data,
},
() => {
if (callback) {
callback();
}
}
);
return;
}
}
this.setState(
{
2021-05-06 03:08:14 +03:00
viewer: { ...this.state.viewer, ...viewer },
},
() => {
if (callback) {
callback();
}
}
);
2020-12-15 04:43:16 +03:00
};
2021-05-06 03:08:14 +03:00
_handleUpdateData = ({ data, callback }) => {
// _handleUpdateData = (data, callback) => {
//TODO(martina): maybe add a default window.history.replacestate where it pushes the new data to browser?
this.setState({ data }, () => {
if (callback) {
callback();
}
});
};
2020-11-20 07:03:30 +03:00
_handleSetupWebsocket = async () => {
let wsclient = Websockets.getClient();
if (wsclient) {
await Websockets.deleteClient();
wsclient = null;
}
if (!this.state.viewer) {
Logging.error("WEBSOCKET: NOT AUTHENTICATED");
return;
}
wsclient = Websockets.init({
resource: Environment.URI_FIJI,
viewer: this.state.viewer,
onUpdate: this._handleUpdateViewer,
onNewActiveUser: this._handleNewActiveUser,
});
2020-11-20 07:03:30 +03:00
if (!wsclient) {
Events.dispatchMessage({
message:
"We cannot connect to our live update server. You may have to refresh to see updates.",
2020-11-20 07:03:30 +03:00
});
}
return;
};
2021-02-04 13:47:39 +03:00
_handleNewActiveUser = (users) => {
2021-02-04 12:21:59 +03:00
this.setState({ activeUsers: users });
};
_handleWindowResize = () => {
const { width } = Window.getViewportSize();
// (1) is Window.isMobileBrowser checks, that one holds.
// (2) then if the viewport is smaller than the width
let isMobile = width > Constants.sizes.mobile ? this.props.isMobile : true;
// only change if necessary.
if (this.state.isMobile !== isMobile) {
Logging.log("changing to mobile?", isMobile);
this.setState({ isMobile });
}
};
2020-08-03 00:09:55 +03:00
_handleOnlineStatus = async () => {
2020-09-12 01:25:33 +03:00
if (navigator.onLine) {
Events.dispatchMessage({ message: "Back online!", status: "INFO" });
2020-09-12 01:25:33 +03:00
} else {
Events.dispatchMessage({ message: "Offline. Trying to reconnect" });
2020-09-12 01:25:33 +03:00
}
2020-08-03 00:09:55 +03:00
this.setState({ online: navigator.onLine });
};
2021-06-09 01:53:30 +03:00
_withAuthenticationBehavior = (authenticate) => async (state, newAccount) => {
let response = await authenticate(state);
if (Events.hasError(response)) {
return response;
}
if (response.shouldMigrate) {
return response;
2020-11-22 05:24:26 +03:00
}
2020-11-20 07:03:30 +03:00
let viewer = await UserBehaviors.hydrate();
2021-06-09 01:53:30 +03:00
if (Events.hasError(viewer)) {
return viewer;
}
2020-11-22 05:24:26 +03:00
this.setState({ viewer });
2020-11-20 07:03:30 +03:00
await this._handleSetupWebsocket();
let unseenAnnouncements = [];
for (let feature of announcements) {
if (!viewer.onboarding || !Object.keys(viewer.onboarding).includes(feature)) {
2020-11-04 00:43:11 +03:00
unseenAnnouncements.push(feature);
}
}
if (newAccount || unseenAnnouncements.length) {
Events.dispatchCustomEvent({
2020-10-27 07:14:13 +03:00
name: "create-modal",
detail: {
modal: (
<OnboardingModal
2020-11-04 00:43:11 +03:00
onAction={this._handleAction}
2020-11-22 05:24:26 +03:00
viewer={viewer}
newAccount={newAccount}
unseenAnnouncements={unseenAnnouncements}
/>
),
2020-10-27 07:14:13 +03:00
noBoundary: true,
},
});
}
2020-11-10 00:20:38 +03:00
if (newAccount) {
Actions.updateSearch("create-user");
}
2021-05-06 03:08:14 +03:00
// let redirected = this._handleURLRedirect();
// if (!redirected) {
// this._handleAction({ type: "NAVIGATE", value: "NAV_DATA" });
// }
2021-07-27 15:01:44 +03:00
this._handleNavigateTo({ href: "/_/data", redirect: true });
2021-06-09 01:53:30 +03:00
2020-11-20 07:03:30 +03:00
return response;
};
_handleSelectedChange = (e) => {
this.setState({
selected: { ...this.state.selected, [e.target.name]: e.target.value },
});
};
_handleDismissSidebar = () => {
this.setState({ sidebar: null, sidebarData: null });
};
_handleAction = (options) => {
if (options.type === "NAVIGATE") {
2021-05-06 03:08:14 +03:00
return this._handleNavigateTo(options);
}
2021-05-06 03:08:14 +03:00
if (options.type === "UPDATE_VIEWER") {
return this._handleUpdateViewer(options);
}
2021-05-06 03:08:14 +03:00
if (options.type === "UPDATE_PARAMS") {
return this._handleUpdatePageParams(options);
}
if (options.type === "SIDEBAR") {
return this.setState({
2021-07-07 23:50:57 +03:00
sidebar: options.value,
sidebarData: options.data,
});
}
2021-05-06 03:08:14 +03:00
if (options.type === "NEW_WINDOW") {
return window.open(options.value);
}
Logging.error("Error: Failed to _handleAction because TYPE did not match any known actions");
};
2021-05-06 03:08:14 +03:00
_handleNavigateTo = async ({ href, redirect = false, popstate = false }) => {
const { page, details } = NavigationData.getByHref(href, this.state.viewer);
Events.dispatchCustomEvent({ name: "slate-global-close-carousel", detail: {} });
if (redirect || popstate) {
window.history.replaceState(null, "Slate", page.pathname);
2020-12-19 08:25:50 +03:00
} else {
2021-05-06 03:08:14 +03:00
window.history.pushState(null, "Slate", page.pathname);
}
2021-05-06 03:08:14 +03:00
let state = { data: null, sidebar: null, page };
if (!next.ignore) {
state.activePage = page.id;
}
let body = document.documentElement || document.body;
2021-05-06 03:08:14 +03:00
if (page.id === "NAV_SLATE" || page.id === "NAV_PROFILE") {
state.loading = true;
}
2021-05-06 03:08:14 +03:00
this.setState(state, () => {
if (!popstate) {
body.scrollTo(0, 0);
}
if (page.id === "NAV_SLATE" || page.id === "NAV_PROFILE") {
this.updateDataAndPathname({ page, details });
}
});
};
2021-05-06 03:08:14 +03:00
updateDataAndPathname = async ({ page, details }) => {
let pathname = page.pathname.split("?")[0];
let search = Strings.getQueryStringFromParams(page.params);
let data;
if (page?.id === "NAV_SLATE") {
let response = await Actions.getSerializedSlate(details);
if (!response || response.error) {
this.setState({ loading: false });
this._handleNavigateTo({ href: "/_/404", redirect: true });
return;
}
data = response.data;
pathname = `/${data.user.username}/${data.slatename}${search}`;
} else if (page?.id === "NAV_PROFILE") {
let response = await Actions.getSerializedProfile(details);
if (!response || response.error) {
this.setState({ loading: false });
this._handleNavigateTo({ href: "/_/404", redirect: true });
return;
}
data = response.data;
pathname = `/${data.username}${search}`;
}
2021-05-06 03:08:14 +03:00
this.setState({ data, loading: false });
window.history.replaceState(null, "Slate", pathname);
};
_handleUpdatePageParams = ({ params, callback, redirect = false }) => {
let query = Strings.getQueryStringFromParams(params);
const href = window.location.pathname.concat(query);
if (redirect) {
window.history.replaceState(null, "Slate", href);
} else {
window.history.pushState(null, "Slate", href);
}
2021-05-06 03:08:14 +03:00
this.setState({ page: { ...this.state.page, params } }, () => {
if (callback) {
callback();
}
});
};
2021-05-06 03:08:14 +03:00
_handleBackForward = () => {
let href = window.location.pathname.concat(
window.location.search ? `${window.location.search}` : ""
);
2021-05-06 03:08:14 +03:00
this._handleNavigateTo({ href, popstate: true });
};
2021-05-06 03:08:14 +03:00
render() {
let page = this.state.page;
if (!page?.id) {
page = NavigationData.getById(null, this.state.viewer);
}
let headerElement;
if (page.id !== "NAV_SIGN_IN") {
headerElement = (
<ApplicationHeader
viewer={this.state.viewer}
data={this.state.data}
2021-05-06 03:08:14 +03:00
page={page}
navigation={NavigationData.navigation}
2021-05-06 03:08:14 +03:00
onAction={this._handleAction}
isMobile={this.state.isMobile}
isMac={this.props.isMac}
activePage={this.state.activePage}
/>
);
}
const scene = React.cloneElement(SCENES[page.id], {
key: this.state.data?.id,
2021-01-22 00:53:33 +03:00
page: page,
data: this.state.data,
viewer: this.state.viewer,
selected: this.state.selected,
onSelectedChange: this._handleSelectedChange,
2021-06-09 01:53:30 +03:00
onAuthenticate: this._withAuthenticationBehavior(UserBehaviors.authenticate),
onTwitterAuthenticate: this._withAuthenticationBehavior(UserBehaviors.authenticateViaTwitter),
onAction: this._handleAction,
isMobile: this.state.isMobile,
isMac: this.props.isMac,
2021-02-04 12:21:59 +03:00
activeUsers: this.state.activeUsers,
2021-05-06 03:08:14 +03:00
external: !!!this.state.viewer,
});
let sidebarElement;
if (this.state.sidebar) {
2021-07-07 23:50:57 +03:00
sidebarElement = React.cloneElement(SIDEBARS[this.state.sidebar], {
2021-05-06 03:08:14 +03:00
page: page,
selected: this.state.selected,
viewer: this.state.viewer,
data: this.state.data,
2020-09-23 23:52:00 +03:00
sidebarData: this.state.sidebarData,
onSelectedChange: this._handleSelectedChange,
2020-09-17 02:26:15 +03:00
onCancel: this._handleDismissSidebar,
onAction: this._handleAction,
});
}
2021-05-06 03:08:14 +03:00
const title = `Slate: ${page.pageTitle}`;
const description = "";
const url = "https://slate.host/_";
2021-05-06 03:08:14 +03:00
// if (!this.state.loaded) {
// return (
// <WebsitePrototypeWrapper description={description} title={title} url={url}>
// <div
// style={{
// height: "100vh",
// display: "flex",
// alignItems: "center",
// justifyContent: "center",
// }}
// >
// <Logo style={{ width: "20vw", maxWidth: "200px" }} />
// </div>
// </WebsitePrototypeWrapper>
// );
// }
return (
<React.Fragment>
<ApplicationLayout
2021-07-07 23:50:57 +03:00
sidebarName={this.state.sidebar}
2021-05-25 01:19:48 +03:00
page={page}
onAction={this._handleAction}
header={headerElement}
sidebar={sidebarElement}
onDismissSidebar={this._handleDismissSidebar}
isMobile={this.state.isMobile}
isMac={this.props.isMac}
viewer={this.state.viewer}
>
{this.state.loading ? (
<div
css={Styles.CONTAINER_CENTERED}
style={{
width: "100vw",
height: "100vh",
}}
>
<LoaderSpinner style={{ height: 32, width: 32 }} />
</div>
) : (
scene
)}
</ApplicationLayout>
<GlobalModal />
<SearchModal
viewer={this.state.viewer}
onAction={this._handleAction}
isMobile={this.props.isMobile}
/>
<CollectionSharingModal />
<CTATransition onAction={this._handleAction} />
{/* {!this.state.loaded ? (
2021-01-13 23:43:29 +03:00
<div
style={{
position: "absolute",
width: "100vw",
height: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Logo style={{ width: "20vw", maxWidth: "200px" }} />
</div>
2021-05-06 03:08:14 +03:00
) : null} */}
</React.Fragment>
);
}
}