+import { NoOptionI18nKeys } from "i18next";
import { Component, linkEvent } from "inferno";
import {
- BlockCommunity,
BlockCommunityResponse,
- BlockPerson,
BlockPersonResponse,
- ChangePassword,
CommunityBlockView,
- CommunityView,
- DeleteAccount,
+ DeleteAccountResponse,
GetSiteResponse,
ListingType,
LoginResponse,
PersonBlockView,
- PersonViewSafe,
- SaveUserSettings,
SortType,
- UserOperation,
- wsJsonToRes,
- wsUserOp,
} from "lemmy-js-client";
-import { Subscription } from "rxjs";
import { i18n, languages } from "../../i18next";
-import { UserService, WebSocketService } from "../../services";
+import { UserService } from "../../services";
+import { HttpService, RequestState } from "../../services/HttpService";
import {
+ Choice,
capitalizeFirstLetter,
- choicesConfig,
- communitySelectName,
communityToChoice,
debounce,
elementUrl,
+ emDash,
enableNsfw,
fetchCommunities,
fetchThemeList,
fetchUsers,
getLanguages,
- isBrowser,
myAuth,
- personSelectName,
+ myAuthRequired,
personToChoice,
relTags,
setIsoData,
toast,
updateCommunityBlock,
updatePersonBlock,
- wsClient,
- wsSubscribe,
} from "../../utils";
import { HtmlTags } from "../common/html-tags";
import { Icon, Spinner } from "../common/icon";
import { LanguageSelect } from "../common/language-select";
import { ListingTypeSelect } from "../common/listing-type-select";
import { MarkdownTextArea } from "../common/markdown-textarea";
+import { SearchableSelect } from "../common/searchable-select";
import { SortSelect } from "../common/sort-select";
+import Tabs from "../common/tabs";
import { CommunityLink } from "../community/community-link";
import { PersonListing } from "./person-listing";
-var Choices: any;
-if (isBrowser()) {
- Choices = require("choices.js");
-}
-
interface SettingsState {
+ saveRes: RequestState<LoginResponse>;
+ changePasswordRes: RequestState<LoginResponse>;
+ deleteAccountRes: RequestState<DeleteAccountResponse>;
// TODO redo these forms
saveUserSettingsForm: {
show_nsfw?: boolean;
theme?: string;
- default_sort_type?: number;
- default_listing_type?: number;
+ default_sort_type?: SortType;
+ default_listing_type?: ListingType;
interface_language?: string;
avatar?: string;
banner?: string;
password?: string;
};
personBlocks: PersonBlockView[];
- blockPerson?: PersonViewSafe;
communityBlocks: CommunityBlockView[];
- blockCommunityId: number;
- blockCommunity?: CommunityView;
currentTab: string;
themeList: string[];
- saveUserSettingsLoading: boolean;
- changePasswordLoading: boolean;
- deleteAccountLoading: boolean;
deleteAccountShowConfirm: boolean;
siteRes: GetSiteResponse;
+ searchCommunityLoading: boolean;
+ searchCommunityOptions: Choice[];
+ searchPersonLoading: boolean;
+ searchPersonOptions: Choice[];
}
+type FilterType = "user" | "community";
+
+const Filter = ({
+ filterType,
+ options,
+ onChange,
+ onSearch,
+ loading,
+}: {
+ filterType: FilterType;
+ options: Choice[];
+ onSearch: (text: string) => void;
+ onChange: (choice: Choice) => void;
+ loading: boolean;
+}) => (
+ <div className="form-group row">
+ <label
+ className="col-md-4 col-form-label"
+ htmlFor={`block-${filterType}-filter`}
+ >
+ {i18n.t(`block_${filterType}` as NoOptionI18nKeys)}
+ </label>
+ <div className="col-md-8">
+ <SearchableSelect
+ id={`block-${filterType}-filter`}
+ options={[
+ { label: emDash, value: "0", disabled: true } as Choice,
+ ].concat(options)}
+ loading={loading}
+ onChange={onChange}
+ onSearch={onSearch}
+ />
+ </div>
+ </div>
+);
+
export class Settings extends Component<any, SettingsState> {
private isoData = setIsoData(this.context);
- private blockPersonChoices: any;
- private blockCommunityChoices: any;
- private subscription?: Subscription;
state: SettingsState = {
+ saveRes: { state: "empty" },
+ deleteAccountRes: { state: "empty" },
+ changePasswordRes: { state: "empty" },
saveUserSettingsForm: {},
changePasswordForm: {},
- saveUserSettingsLoading: false,
- changePasswordLoading: false,
- deleteAccountLoading: false,
deleteAccountShowConfirm: false,
deleteAccountForm: {},
personBlocks: [],
communityBlocks: [],
- blockCommunityId: 0,
currentTab: "settings",
siteRes: this.isoData.site_res,
themeList: [],
+ searchCommunityLoading: false,
+ searchCommunityOptions: [],
+ searchPersonLoading: false,
+ searchPersonOptions: [],
};
constructor(props: any, context: any) {
this.handleBannerUpload = this.handleBannerUpload.bind(this);
this.handleBannerRemove = this.handleBannerRemove.bind(this);
+ this.userSettings = this.userSettings.bind(this);
+ this.blockCards = this.blockCards.bind(this);
- this.parseMessage = this.parseMessage.bind(this);
- this.subscription = wsSubscribe(this.parseMessage);
+ this.handleBlockPerson = this.handleBlockPerson.bind(this);
+ this.handleBlockCommunity = this.handleBlockCommunity.bind(this);
- let mui = UserService.Instance.myUserInfo;
+ const mui = UserService.Instance.myUserInfo;
if (mui) {
- let luv = mui.local_user_view;
+ const {
+ local_user: {
+ show_nsfw,
+ theme,
+ default_sort_type,
+ default_listing_type,
+ interface_language,
+ show_avatars,
+ show_bot_accounts,
+ show_scores,
+ show_read_posts,
+ show_new_post_notifs,
+ send_notifications_to_email,
+ email,
+ },
+ person: {
+ avatar,
+ banner,
+ display_name,
+ bot_account,
+ bio,
+ matrix_user_id,
+ },
+ } = mui.local_user_view;
+
this.state = {
...this.state,
personBlocks: mui.person_blocks,
communityBlocks: mui.community_blocks,
saveUserSettingsForm: {
...this.state.saveUserSettingsForm,
- show_nsfw: luv.local_user.show_nsfw,
- theme: luv.local_user.theme ? luv.local_user.theme : "browser",
- default_sort_type: luv.local_user.default_sort_type,
- default_listing_type: luv.local_user.default_listing_type,
- interface_language: luv.local_user.interface_language,
+ show_nsfw,
+ theme: theme ?? "browser",
+ default_sort_type,
+ default_listing_type,
+ interface_language,
discussion_languages: mui.discussion_languages,
- avatar: luv.person.avatar,
- banner: luv.person.banner,
- display_name: luv.person.display_name,
- show_avatars: luv.local_user.show_avatars,
- bot_account: luv.person.bot_account,
- show_bot_accounts: luv.local_user.show_bot_accounts,
- show_scores: luv.local_user.show_scores,
- show_read_posts: luv.local_user.show_read_posts,
- show_new_post_notifs: luv.local_user.show_new_post_notifs,
- email: luv.local_user.email,
- bio: luv.person.bio,
- send_notifications_to_email:
- luv.local_user.send_notifications_to_email,
- matrix_user_id: luv.person.matrix_user_id,
+ avatar,
+ banner,
+ display_name,
+ show_avatars,
+ bot_account,
+ show_bot_accounts,
+ show_scores,
+ show_read_posts,
+ show_new_post_notifs,
+ email,
+ bio,
+ send_notifications_to_email,
+ matrix_user_id,
},
};
}
this.setState({ themeList: await fetchThemeList() });
}
- componentWillUnmount() {
- this.subscription?.unsubscribe();
- }
-
get documentTitle(): string {
return i18n.t("settings");
}
render() {
return (
<div className="container-lg">
- <>
- <HtmlTags
- title={this.documentTitle}
- path={this.context.router.route.match.url}
- description={this.documentTitle}
- image={this.state.saveUserSettingsForm.avatar}
- />
- <ul className="nav nav-tabs mb-2">
- <li className="nav-item">
- <button
- className={`nav-link btn ${
- this.state.currentTab == "settings" && "active"
- }`}
- onClick={linkEvent(
- { ctx: this, tab: "settings" },
- this.handleSwitchTab
- )}
- >
- {i18n.t("settings")}
- </button>
- </li>
- <li className="nav-item">
- <button
- className={`nav-link btn ${
- this.state.currentTab == "blocks" && "active"
- }`}
- onClick={linkEvent(
- { ctx: this, tab: "blocks" },
- this.handleSwitchTab
- )}
- >
- {i18n.t("blocks")}
- </button>
- </li>
- </ul>
- {this.state.currentTab == "settings" && this.userSettings()}
- {this.state.currentTab == "blocks" && this.blockCards()}
- </>
+ <HtmlTags
+ title={this.documentTitle}
+ path={this.context.router.route.match.url}
+ description={this.documentTitle}
+ image={this.state.saveUserSettingsForm.avatar}
+ />
+ <Tabs
+ tabs={[
+ {
+ key: "settings",
+ label: i18n.t("settings"),
+ getNode: this.userSettings,
+ },
+ {
+ key: "blocks",
+ label: i18n.t("blocks"),
+ getNode: this.blockCards,
+ },
+ ]}
+ />
</div>
);
}
</div>
<div className="form-group">
<button type="submit" className="btn btn-block btn-secondary mr-4">
- {this.state.changePasswordLoading ? (
+ {this.state.changePasswordRes.state === "loading" ? (
<Spinner />
) : (
capitalizeFirstLetter(i18n.t("save"))
}
blockUserCard() {
+ const { searchPersonLoading, searchPersonOptions } = this.state;
+
return (
<div>
- {this.blockUserForm()}
+ <Filter
+ filterType="user"
+ loading={searchPersonLoading}
+ onChange={this.handleBlockPerson}
+ onSearch={this.handlePersonSearch}
+ options={searchPersonOptions}
+ />
{this.blockedUsersList()}
</div>
);
);
}
- blockUserForm() {
- let blockPerson = this.state.blockPerson;
- return (
- <div className="form-group row">
- <label
- className="col-md-4 col-form-label"
- htmlFor="block-person-filter"
- >
- {i18n.t("block_user")}
- </label>
- <div className="col-md-8">
- <select
- className="form-control"
- id="block-person-filter"
- value={blockPerson?.person.id ?? 0}
- >
- <option value="0">—</option>
- {blockPerson && (
- <option value={blockPerson.person.id}>
- {personSelectName(blockPerson)}
- </option>
- )}
- </select>
- </div>
- </div>
- );
- }
-
blockCommunityCard() {
+ const { searchCommunityLoading, searchCommunityOptions } = this.state;
+
return (
<div>
- {this.blockCommunityForm()}
+ <Filter
+ filterType="community"
+ loading={searchCommunityLoading}
+ onChange={this.handleBlockCommunity}
+ onSearch={this.handleCommunitySearch}
+ options={searchCommunityOptions}
+ />
{this.blockedCommunitiesList()}
</div>
);
);
}
- blockCommunityForm() {
- return (
- <div className="form-group row">
- <label
- className="col-md-4 col-form-label"
- htmlFor="block-community-filter"
- >
- {i18n.t("block_community")}
- </label>
- <div className="col-md-8">
- <select
- className="form-control"
- id="block-community-filter"
- value={this.state.blockCommunityId}
- >
- <option value="0">—</option>
- {this.state.blockCommunity && (
- <option value={this.state.blockCommunity.community.id}>
- {communitySelectName(this.state.blockCommunity)}
- </option>
- )}
- </select>
- </div>
- </div>
- );
- }
-
saveUserSettingsHtmlForm() {
- let selectedLangs = this.state.saveUserSettingsForm.discussion_languages;
+ const selectedLangs = this.state.saveUserSettingsForm.discussion_languages;
return (
<>
siteLanguages={this.state.siteRes.discussion_languages}
selectedLanguageIds={selectedLangs}
multiple={true}
+ showLanguageWarning={true}
showSite
onChange={this.handleDiscussionLanguageChange}
/>
<div className="col-sm-9">
<ListingTypeSelect
type_={
- Object.values(ListingType)[
- this.state.saveUserSettingsForm.default_listing_type ?? 1
- ]
+ this.state.saveUserSettingsForm.default_listing_type ??
+ "Local"
}
showLocal={showLocal(this.isoData)}
showSubscribed
<div className="col-sm-9">
<SortSelect
sort={
- Object.values(SortType)[
- this.state.saveUserSettingsForm.default_sort_type ?? 0
- ]
+ this.state.saveUserSettingsForm.default_sort_type ?? "Active"
}
onChange={this.handleSortTypeChange}
/>
{this.totpSection()}
<div className="form-group">
<button type="submit" className="btn btn-block btn-secondary mr-4">
- {this.state.saveUserSettingsLoading ? (
+ {this.state.saveRes.state === "loading" ? (
<Spinner />
) : (
capitalizeFirstLetter(i18n.t("save"))
disabled={!this.state.deleteAccountForm.password}
onClick={linkEvent(this, this.handleDeleteAccount)}
>
- {this.state.deleteAccountLoading ? (
+ {this.state.deleteAccountRes.state === "loading" ? (
<Spinner />
) : (
capitalizeFirstLetter(i18n.t("delete"))
}
totpSection() {
- let totpUrl =
+ const totpUrl =
UserService.Instance.myUserInfo?.local_user_view.local_user.totp_2fa_url;
return (
);
}
- setupBlockPersonChoices() {
- if (isBrowser()) {
- let selectId: any = document.getElementById("block-person-filter");
- if (selectId) {
- this.blockPersonChoices = new Choices(selectId, choicesConfig);
- this.blockPersonChoices.passedElement.element.addEventListener(
- "choice",
- (e: any) => {
- this.handleBlockPerson(Number(e.detail.choice.value));
- },
- false
- );
- this.blockPersonChoices.passedElement.element.addEventListener(
- "search",
- debounce(async (e: any) => {
- try {
- let persons = (await fetchUsers(e.detail.value)).users;
- let choices = persons.map(pvs => personToChoice(pvs));
- this.blockPersonChoices.setChoices(
- choices,
- "value",
- "label",
- true
- );
- } catch (err) {
- console.error(err);
- }
- }),
- false
- );
- }
+ handlePersonSearch = debounce(async (text: string) => {
+ this.setState({ searchPersonLoading: true });
+
+ const searchPersonOptions: Choice[] = [];
+
+ if (text.length > 0) {
+ searchPersonOptions.push(...(await fetchUsers(text)).map(personToChoice));
}
- }
- setupBlockCommunityChoices() {
- if (isBrowser()) {
- let selectId: any = document.getElementById("block-community-filter");
- if (selectId) {
- this.blockCommunityChoices = new Choices(selectId, choicesConfig);
- this.blockCommunityChoices.passedElement.element.addEventListener(
- "choice",
- (e: any) => {
- this.handleBlockCommunity(Number(e.detail.choice.value));
- },
- false
- );
- this.blockCommunityChoices.passedElement.element.addEventListener(
- "search",
- debounce(async (e: any) => {
- try {
- let communities = (await fetchCommunities(e.detail.value))
- .communities;
- let choices = communities.map(cv => communityToChoice(cv));
- this.blockCommunityChoices.setChoices(
- choices,
- "value",
- "label",
- true
- );
- } catch (err) {
- console.log(err);
- }
- }),
- false
- );
- }
+ this.setState({
+ searchPersonLoading: false,
+ searchPersonOptions,
+ });
+ });
+
+ handleCommunitySearch = debounce(async (text: string) => {
+ this.setState({ searchCommunityLoading: true });
+
+ const searchCommunityOptions: Choice[] = [];
+
+ if (text.length > 0) {
+ searchCommunityOptions.push(
+ ...(await fetchCommunities(text)).map(communityToChoice)
+ );
}
- }
- handleBlockPerson(personId: number) {
- let auth = myAuth();
- if (auth && personId != 0) {
- let blockUserForm: BlockPerson = {
- person_id: personId,
+ this.setState({
+ searchCommunityLoading: false,
+ searchCommunityOptions,
+ });
+ });
+
+ async handleBlockPerson({ value }: Choice) {
+ if (value !== "0") {
+ const res = await HttpService.client.blockPerson({
+ person_id: Number(value),
block: true,
- auth,
- };
- WebSocketService.Instance.send(wsClient.blockPerson(blockUserForm));
+ auth: myAuthRequired(),
+ });
+ this.personBlock(res);
}
}
- handleUnblockPerson(i: { ctx: Settings; recipientId: number }) {
- let auth = myAuth();
- if (auth) {
- let blockUserForm: BlockPerson = {
- person_id: i.recipientId,
- block: false,
- auth,
- };
- WebSocketService.Instance.send(wsClient.blockPerson(blockUserForm));
- }
+ async handleUnblockPerson({
+ ctx,
+ recipientId,
+ }: {
+ ctx: Settings;
+ recipientId: number;
+ }) {
+ const res = await HttpService.client.blockPerson({
+ person_id: recipientId,
+ block: false,
+ auth: myAuthRequired(),
+ });
+ ctx.personBlock(res);
}
- handleBlockCommunity(community_id: number) {
- let auth = myAuth();
- if (auth && community_id != 0) {
- let blockCommunityForm: BlockCommunity = {
- community_id,
+ async handleBlockCommunity({ value }: Choice) {
+ if (value !== "0") {
+ const res = await HttpService.client.blockCommunity({
+ community_id: Number(value),
block: true,
- auth,
- };
- WebSocketService.Instance.send(
- wsClient.blockCommunity(blockCommunityForm)
- );
+ auth: myAuthRequired(),
+ });
+ this.communityBlock(res);
}
}
- handleUnblockCommunity(i: { ctx: Settings; communityId: number }) {
- let auth = myAuth();
+ async handleUnblockCommunity(i: { ctx: Settings; communityId: number }) {
+ const auth = myAuth();
if (auth) {
- let blockCommunityForm: BlockCommunity = {
+ const res = await HttpService.client.blockCommunity({
community_id: i.communityId,
block: false,
- auth,
- };
- WebSocketService.Instance.send(
- wsClient.blockCommunity(blockCommunityForm)
- );
+ auth: myAuthRequired(),
+ });
+ i.ctx.communityBlock(res);
}
}
handleShowNsfwChange(i: Settings, event: any) {
- i.state.saveUserSettingsForm.show_nsfw = event.target.checked;
- i.setState(i.state);
+ i.setState(
+ s => ((s.saveUserSettingsForm.show_nsfw = event.target.checked), s)
+ );
}
handleShowAvatarsChange(i: Settings, event: any) {
- i.state.saveUserSettingsForm.show_avatars = event.target.checked;
- let mui = UserService.Instance.myUserInfo;
+ const mui = UserService.Instance.myUserInfo;
if (mui) {
mui.local_user_view.local_user.show_avatars = event.target.checked;
}
- i.setState(i.state);
+ i.setState(
+ s => ((s.saveUserSettingsForm.show_avatars = event.target.checked), s)
+ );
}
handleBotAccount(i: Settings, event: any) {
- i.state.saveUserSettingsForm.bot_account = event.target.checked;
- i.setState(i.state);
+ i.setState(
+ s => ((s.saveUserSettingsForm.bot_account = event.target.checked), s)
+ );
}
handleShowBotAccounts(i: Settings, event: any) {
- i.state.saveUserSettingsForm.show_bot_accounts = event.target.checked;
- i.setState(i.state);
+ i.setState(
+ s => (
+ (s.saveUserSettingsForm.show_bot_accounts = event.target.checked), s
+ )
+ );
}
handleReadPosts(i: Settings, event: any) {
- i.state.saveUserSettingsForm.show_read_posts = event.target.checked;
- i.setState(i.state);
+ i.setState(
+ s => ((s.saveUserSettingsForm.show_read_posts = event.target.checked), s)
+ );
}
handleShowNewPostNotifs(i: Settings, event: any) {
- i.state.saveUserSettingsForm.show_new_post_notifs = event.target.checked;
- i.setState(i.state);
+ i.setState(
+ s => (
+ (s.saveUserSettingsForm.show_new_post_notifs = event.target.checked), s
+ )
+ );
}
handleShowScoresChange(i: Settings, event: any) {
- i.state.saveUserSettingsForm.show_scores = event.target.checked;
- let mui = UserService.Instance.myUserInfo;
+ const mui = UserService.Instance.myUserInfo;
if (mui) {
mui.local_user_view.local_user.show_scores = event.target.checked;
}
- i.setState(i.state);
+ i.setState(
+ s => ((s.saveUserSettingsForm.show_scores = event.target.checked), s)
+ );
}
handleGenerateTotp(i: Settings, event: any) {
// Coerce false to undefined here, so it won't generate it.
- let checked: boolean | undefined = event.target.checked || undefined;
+ const checked: boolean | undefined = event.target.checked || undefined;
if (checked) {
toast(i18n.t("two_factor_setup_instructions"));
}
- i.state.saveUserSettingsForm.generate_totp_2fa = checked;
- i.setState(i.state);
+ i.setState(s => ((s.saveUserSettingsForm.generate_totp_2fa = checked), s));
}
handleRemoveTotp(i: Settings, event: any) {
// Coerce true to undefined here, so it won't generate it.
- let checked: boolean | undefined = !event.target.checked && undefined;
- i.state.saveUserSettingsForm.generate_totp_2fa = checked;
- i.setState(i.state);
+ const checked: boolean | undefined = !event.target.checked && undefined;
+ i.setState(s => ((s.saveUserSettingsForm.generate_totp_2fa = checked), s));
}
handleSendNotificationsToEmailChange(i: Settings, event: any) {
- i.state.saveUserSettingsForm.send_notifications_to_email =
- event.target.checked;
- i.setState(i.state);
+ i.setState(
+ s => (
+ (s.saveUserSettingsForm.send_notifications_to_email =
+ event.target.checked),
+ s
+ )
+ );
}
handleThemeChange(i: Settings, event: any) {
- i.state.saveUserSettingsForm.theme = event.target.value;
+ i.setState(s => ((s.saveUserSettingsForm.theme = event.target.value), s));
setTheme(event.target.value, true);
- i.setState(i.state);
}
handleInterfaceLangChange(i: Settings, event: any) {
- i.state.saveUserSettingsForm.interface_language = event.target.value;
+ i.setState(
+ s => ((s.saveUserSettingsForm.interface_language = event.target.value), s)
+ );
i18n.changeLanguage(
getLanguages(i.state.saveUserSettingsForm.interface_language).at(0)
);
- i.setState(i.state);
}
handleDiscussionLanguageChange(val: number[]) {
}
handleSortTypeChange(val: SortType) {
- this.setState(
- s => (
- (s.saveUserSettingsForm.default_sort_type =
- Object.keys(SortType).indexOf(val)),
- s
- )
- );
+ this.setState(s => ((s.saveUserSettingsForm.default_sort_type = val), s));
}
handleListingTypeChange(val: ListingType) {
this.setState(
- s => (
- (s.saveUserSettingsForm.default_listing_type =
- Object.keys(ListingType).indexOf(val)),
- s
- )
+ s => ((s.saveUserSettingsForm.default_listing_type = val), s)
);
}
handleEmailChange(i: Settings, event: any) {
- i.state.saveUserSettingsForm.email = event.target.value;
- i.setState(i.state);
+ i.setState(s => ((s.saveUserSettingsForm.email = event.target.value), s));
}
handleBioChange(val: string) {
}
handleDisplayNameChange(i: Settings, event: any) {
- i.state.saveUserSettingsForm.display_name = event.target.value;
- i.setState(i.state);
+ i.setState(
+ s => ((s.saveUserSettingsForm.display_name = event.target.value), s)
+ );
}
handleMatrixUserIdChange(i: Settings, event: any) {
- i.state.saveUserSettingsForm.matrix_user_id = event.target.value;
- i.setState(i.state);
+ i.setState(
+ s => ((s.saveUserSettingsForm.matrix_user_id = event.target.value), s)
+ );
}
handleNewPasswordChange(i: Settings, event: any) {
- i.state.changePasswordForm.new_password = event.target.value;
- if (i.state.changePasswordForm.new_password == "") {
- i.state.changePasswordForm.new_password = undefined;
- }
- i.setState(i.state);
+ const newPass: string | undefined =
+ event.target.value == "" ? undefined : event.target.value;
+ i.setState(s => ((s.changePasswordForm.new_password = newPass), s));
}
handleNewPasswordVerifyChange(i: Settings, event: any) {
- i.state.changePasswordForm.new_password_verify = event.target.value;
- if (i.state.changePasswordForm.new_password_verify == "") {
- i.state.changePasswordForm.new_password_verify = undefined;
- }
- i.setState(i.state);
+ const newPassVerify: string | undefined =
+ event.target.value == "" ? undefined : event.target.value;
+ i.setState(
+ s => ((s.changePasswordForm.new_password_verify = newPassVerify), s)
+ );
}
handleOldPasswordChange(i: Settings, event: any) {
- i.state.changePasswordForm.old_password = event.target.value;
- if (i.state.changePasswordForm.old_password == "") {
- i.state.changePasswordForm.old_password = undefined;
- }
- i.setState(i.state);
+ const oldPass: string | undefined =
+ event.target.value == "" ? undefined : event.target.value;
+ i.setState(s => ((s.changePasswordForm.old_password = oldPass), s));
}
- handleSaveSettingsSubmit(i: Settings, event: any) {
+ async handleSaveSettingsSubmit(i: Settings, event: any) {
event.preventDefault();
- i.setState({ saveUserSettingsLoading: true });
- let auth = myAuth();
- if (auth) {
- let form: SaveUserSettings = { ...i.state.saveUserSettingsForm, auth };
- WebSocketService.Instance.send(wsClient.saveUserSettings(form));
+ i.setState({ saveRes: { state: "loading" } });
+
+ const saveRes = await HttpService.client.saveUserSettings({
+ ...i.state.saveUserSettingsForm,
+ auth: myAuthRequired(),
+ });
+ if (saveRes.state === "success") {
+ UserService.Instance.login(saveRes.data);
+ location.reload();
+ toast(i18n.t("saved"));
+ window.scrollTo(0, 0);
}
+
+ i.setState({ saveRes });
}
- handleChangePasswordSubmit(i: Settings, event: any) {
+ async handleChangePasswordSubmit(i: Settings, event: any) {
event.preventDefault();
- i.setState({ changePasswordLoading: true });
- let auth = myAuth();
- let pForm = i.state.changePasswordForm;
- let new_password = pForm.new_password;
- let new_password_verify = pForm.new_password_verify;
- let old_password = pForm.old_password;
- if (auth && new_password && old_password && new_password_verify) {
- let form: ChangePassword = {
+ const { new_password, new_password_verify, old_password } =
+ i.state.changePasswordForm;
+
+ if (new_password && old_password && new_password_verify) {
+ i.setState({ changePasswordRes: { state: "loading" } });
+ const changePasswordRes = await HttpService.client.changePassword({
new_password,
new_password_verify,
old_password,
- auth,
- };
+ auth: myAuthRequired(),
+ });
+ if (changePasswordRes.state === "success") {
+ UserService.Instance.login(changePasswordRes.data);
+ window.scrollTo(0, 0);
+ toast(i18n.t("password_changed"));
+ }
- WebSocketService.Instance.send(wsClient.changePassword(form));
+ i.setState({ changePasswordRes });
}
}
- handleDeleteAccountShowConfirmToggle(i: Settings, event: any) {
- event.preventDefault();
+ handleDeleteAccountShowConfirmToggle(i: Settings) {
i.setState({ deleteAccountShowConfirm: !i.state.deleteAccountShowConfirm });
}
handleDeleteAccountPasswordChange(i: Settings, event: any) {
- i.state.deleteAccountForm.password = event.target.value;
- i.setState(i.state);
+ i.setState(s => ((s.deleteAccountForm.password = event.target.value), s));
}
- handleDeleteAccount(i: Settings, event: any) {
- event.preventDefault();
- i.setState({ deleteAccountLoading: true });
- let auth = myAuth();
- let password = i.state.deleteAccountForm.password;
- if (auth && password) {
- let form: DeleteAccount = {
+ async handleDeleteAccount(i: Settings) {
+ const password = i.state.deleteAccountForm.password;
+ if (password) {
+ i.setState({ deleteAccountRes: { state: "loading" } });
+ const deleteAccountRes = await HttpService.client.deleteAccount({
password,
- auth,
- };
- WebSocketService.Instance.send(wsClient.deleteAccount(form));
+ auth: myAuthRequired(),
+ });
+ if (deleteAccountRes.state === "success") {
+ UserService.Instance.logout();
+ this.context.router.history.replace("/");
+ }
+
+ i.setState({ deleteAccountRes });
}
}
handleSwitchTab(i: { ctx: Settings; tab: string }) {
i.ctx.setState({ currentTab: i.tab });
-
- if (i.ctx.state.currentTab == "blocks") {
- i.ctx.setupBlockPersonChoices();
- i.ctx.setupBlockCommunityChoices();
- }
}
- parseMessage(msg: any) {
- let op = wsUserOp(msg);
- console.log(msg);
- if (msg.error) {
- this.setState({
- saveUserSettingsLoading: false,
- changePasswordLoading: false,
- deleteAccountLoading: false,
- });
- toast(i18n.t(msg.error), "danger");
- return;
- } else if (op == UserOperation.SaveUserSettings) {
- let data = wsJsonToRes<LoginResponse>(msg);
- UserService.Instance.login(data);
- location.reload();
- this.setState({ saveUserSettingsLoading: false });
- toast(i18n.t("saved"));
- window.scrollTo(0, 0);
- } else if (op == UserOperation.ChangePassword) {
- let data = wsJsonToRes<LoginResponse>(msg);
- UserService.Instance.login(data);
- this.setState({ changePasswordLoading: false });
- window.scrollTo(0, 0);
- toast(i18n.t("password_changed"));
- } else if (op == UserOperation.DeleteAccount) {
- this.setState({
- deleteAccountLoading: false,
- deleteAccountShowConfirm: false,
- });
- UserService.Instance.logout();
- window.location.href = "/";
- } else if (op == UserOperation.BlockPerson) {
- let data = wsJsonToRes<BlockPersonResponse>(msg);
- updatePersonBlock(data);
- let mui = UserService.Instance.myUserInfo;
+ personBlock(res: RequestState<BlockPersonResponse>) {
+ if (res.state === "success") {
+ updatePersonBlock(res.data);
+ const mui = UserService.Instance.myUserInfo;
if (mui) {
this.setState({ personBlocks: mui.person_blocks });
}
- } else if (op == UserOperation.BlockCommunity) {
- let data = wsJsonToRes<BlockCommunityResponse>(msg);
- updateCommunityBlock(data);
- let mui = UserService.Instance.myUserInfo;
+ }
+ }
+
+ communityBlock(res: RequestState<BlockCommunityResponse>) {
+ if (res.state === "success") {
+ updateCommunityBlock(res.data);
+ const mui = UserService.Instance.myUserInfo;
if (mui) {
this.setState({ communityBlocks: mui.community_blocks });
}