DocSpace-client/packages/common/store/UserStore.js

136 lines
2.8 KiB
JavaScript

import React from "react";
import { toastr } from "@docspace/components";
import { makeAutoObservable } from "mobx";
import { Trans } from "react-i18next";
import api from "../api";
import { EmployeeActivationStatus } from "../constants";
class UserStore {
user = null;
isLoading = false;
isLoaded = false;
userIsUpdate = false;
withSendAgain = true;
constructor() {
makeAutoObservable(this);
}
loadCurrentUser = async () => {
let user = null;
if (window?.__ASC_INITIAL_EDITOR_STATE__?.user)
user = window.__ASC_INITIAL_EDITOR_STATE__.user;
else user = await api.people.getUser();
this.setUser(user);
};
init = async () => {
if (this.isLoaded) return;
this.setIsLoading(true);
try {
await this.loadCurrentUser();
} catch (e) {
console.error(e);
}
this.setIsLoading(false);
this.setIsLoaded(true);
};
setIsLoading = (isLoading) => {
this.isLoading = isLoading;
};
setIsLoaded = (isLoaded) => {
this.isLoaded = isLoaded;
};
setUser = (user) => {
this.user = user;
};
changeEmail = async (userId, email, key) => {
this.setIsLoading(true);
const user = await api.people.changeEmail(userId, email, key);
this.setUser(user);
this.setIsLoading(false);
};
changeTheme = async (key) => {
this.setIsLoading(true);
const { theme } = await api.people.changeTheme(key);
this.user.theme = theme;
this.setIsLoading(false);
return theme;
};
setUserIsUpdate = (isUpdate) => {
//console.log("setUserIsUpdate");
this.userIsUpdate = isUpdate;
};
setWithSendAgain = (withSendAgain) => {
this.withSendAgain = withSendAgain;
};
sendActivationLink = (t) => {
const { email, id } = this.user;
return api.people
.resendUserInvites([id])
.then(() => {
toastr.success(
<Trans
i18nKey="MessageEmailActivationInstuctionsSentOnEmail"
ns="People"
t={t}
>
The email activation instructions have been sent to the
<strong>{{ email: email }}</strong> email address
</Trans>
);
})
.finally(() => {
this.setWithSendAgain(false);
});
};
get withActivationBar() {
return (
this.user &&
this.user.activationStatus === EmployeeActivationStatus.Pending &&
this.withSendAgain
);
}
get isAuthenticated() {
return !!this.user;
}
get userTheme() {
const systemTheme =
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
? "Dark"
: "Light";
const theme = this.user?.theme || systemTheme;
if (theme === "System") {
return systemTheme;
}
return theme;
}
}
export default UserStore;