Compare commits

...

5 commits

Author SHA1 Message Date
f0x ceba7bc3bc refactor password change form 2023-01-04 21:12:57 +00:00
f0x f6369ccae1 refactor user post settings 2023-01-04 20:12:28 +00:00
f0x 0898aa28eb use rtk query api for profile settings 2023-01-04 15:31:13 +00:00
f0x 72b039adfb fully refactor user profile settings form 2023-01-04 15:31:12 +00:00
f0x 7f42aea8ae yakshave new form field structure 2023-01-04 15:31:12 +00:00
20 changed files with 529 additions and 152 deletions

View file

@ -23,7 +23,7 @@ const React = require("react");
const { useRoute, Link, Redirect } = require("wouter"); const { useRoute, Link, Redirect } = require("wouter");
const { CategorySelect } = require("../category-select"); const { CategorySelect } = require("../category-select");
const { useComboBoxInput, useFileInput } = require("../../../components/form"); const { useComboBoxInput, useFileInput } = require("../../../lib/form");
const query = require("../../../lib/query"); const query = require("../../../lib/query");
const FakeToot = require("../../../components/fake-toot"); const FakeToot = require("../../../components/fake-toot");

View file

@ -22,13 +22,13 @@ const Promise = require('bluebird');
const React = require("react"); const React = require("react");
const FakeToot = require("../../../components/fake-toot"); const FakeToot = require("../../../components/fake-toot");
const MutateButton = require("../../../components/mutation-button"); const MutationButton = require("../../../components/form/mutation-button");
const { const {
useTextInput, useTextInput,
useFileInput, useFileInput,
useComboBoxInput useComboBoxInput
} = require("../../../components/form"); } = require("../../../lib/form");
const query = require("../../../lib/query"); const query = require("../../../lib/query");
const { CategorySelect } = require('../category-select'); const { CategorySelect } = require('../category-select');
@ -161,7 +161,7 @@ module.exports = function NewEmojiForm({ emoji }) {
categoryState={categoryState} categoryState={categoryState}
/> />
<MutateButton text="Upload emoji" result={result} /> <MutationButton text="Upload emoji" result={result} />
</form> </form>
</div> </div>
); );

View file

@ -26,7 +26,7 @@ const syncpipe = require("syncpipe");
const { const {
useTextInput, useTextInput,
useComboBoxInput useComboBoxInput
} = require("../../../components/form"); } = require("../../../lib/form");
const { CategorySelect } = require('../category-select'); const { CategorySelect } = require('../category-select');

View file

@ -19,24 +19,21 @@
"use strict"; "use strict";
const React = require("react"); const React = require("react");
const Redux = require("react-redux");
module.exports = function FakeProfile({}) {
const account = Redux.useSelector(state => state.user.profile);
module.exports = function FakeProfile({avatar, header, display_name, username, role}) {
return ( // Keep in sync with web/template/profile.tmpl return ( // Keep in sync with web/template/profile.tmpl
<div className="profile"> <div className="profile">
<div className="headerimage"> <div className="headerimage">
<img className="headerpreview" src={account.header} alt={account.header ? `header image for ${account.username}` : "None set"} /> <img className="headerpreview" src={header} alt={header ? `header image for ${username}` : "None set"} />
</div> </div>
<div className="basic"> <div className="basic">
<div id="profile-basic-filler2"></div> <div id="profile-basic-filler2"></div>
<span className="avatar"><img className="avatarpreview" src={account.avatar} alt={account.avatar ? `avatar image for ${account.username}` : "None set"} /></span> <span className="avatar"><img className="avatarpreview" src={avatar} alt={avatar ? `avatar image for ${username}` : "None set"} /></span>
<div className="displayname">{account.display_name.trim().length > 0 ? account.display_name : account.username}</div> <div className="displayname">{display_name.trim().length > 0 ? display_name : username}</div>
<div className="usernamecontainer"> <div className="usernamecontainer">
<div className="username"><span>@{account.username}</span></div> <div className="username"><span>@{username}</span></div>
{(account.role && account.role != "user") && {(role && role != "user") &&
<div className={`role ${account.role}`}>{account.role}</div> <div className={`role ${role}`}>{role}</div>
} }
</div> </div>
</div> </div>

View file

@ -0,0 +1,119 @@
/*
GoToSocial
Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const React = require("react");
function TextInput({label, field, ...inputProps}) {
const {onChange, value, ref} = field;
return (
<div className="form-field text">
<label>
{label}
<input
type="text"
{...{onChange, value, ref}}
{...inputProps}
/>
</label>
</div>
);
}
function TextArea({label, field, ...inputProps}) {
const {onChange, value, ref} = field;
return (
<div className="form-field textarea">
<label>
{label}
<textarea
type="text"
{...{onChange, value, ref}}
{...inputProps}
/>
</label>
</div>
);
}
function FileInput({label, field, ...inputProps}) {
const {onChange, ref, infoComponent} = field;
return (
<div className="form-field file">
<label>
{label}
<div className="file-input button">Browse</div>
{infoComponent}
{/* <a onClick={removeFile("header")}>remove</a> */}
<input
type="file"
className="hidden"
{...{onChange, ref}}
{...inputProps}
/>
</label>
</div>
);
}
function Checkbox({label, field, ...inputProps}) {
const {onChange, value} = field;
return (
<div className="form-field checkbox">
<label>
<input
type="checkbox"
checked={value}
onChange={onChange}
{...inputProps}
/> {label}
</label>
</div>
);
}
function Select({label, field, options, ...inputProps}) {
const {onChange, value, ref} = field;
return (
<div className="form-field select">
<label>
{label}
<select
{...{onChange, value, ref}}
{...inputProps}
>
{options}
</select>
</label>
</div>
);
}
module.exports = {
TextInput,
TextArea,
FileInput,
Checkbox,
Select
};

View file

@ -37,6 +37,7 @@ module.exports = function MutateButton({text, result}) {
disabled={result.isLoading} disabled={result.isLoading}
value={buttonText} value={buttonText}
/> />
{result.isSuccess && "Success!"}
</div> </div>
); );
}; };

View file

@ -0,0 +1,50 @@
/*
GoToSocial
Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const React = require("react");
module.exports = function useBoolInput({name, Name}, {defaultValue=false} = {}) {
const [value, setValue] = React.useState(defaultValue);
function onChange(e) {
setValue(e.target.checked);
}
function reset() {
setValue(defaultValue);
}
// Array / Object hybrid, for easier access in different contexts
return Object.assign([
onChange,
reset,
{
[name]: value,
[`set${Name}`]: setValue
}
], {
name,
onChange,
reset,
value,
setter: setValue,
hasChanged: () => value != defaultValue
});
};

View file

@ -20,7 +20,7 @@
const { useComboboxState } = require("ariakit/combobox"); const { useComboboxState } = require("ariakit/combobox");
module.exports = function useComboBoxInput({name, Name}, {validator, defaultValue} = {}) { module.exports = function useComboBoxInput({name, Name}, {defaultValue} = {}) {
const state = useComboboxState({ const state = useComboboxState({
defaultValue, defaultValue,
gutter: 0, gutter: 0,
@ -31,11 +31,16 @@ module.exports = function useComboBoxInput({name, Name}, {validator, defaultValu
state.setValue(""); state.setValue("");
} }
return [ return Object.assign([
state, state,
reset, reset,
name,
{ {
[name]: state.value, [name]: state.value,
} }
]; ], {
name,
value: state.value,
reset
});
}; };

View file

@ -61,18 +61,31 @@ module.exports = function useFileInput({name, _Name}, {
setInfo(); setInfo();
} }
return [ const infoComponent = (
<span className="form-info">
{info
? info
: initialInfo
}
</span>
);
// Array / Object hybrid, for easier access in different contexts
return Object.assign([
onChange, onChange,
reset, reset,
{ {
[name]: file, [name]: file,
[`${name}URL`]: imageURL, [`${name}URL`]: imageURL,
[`${name}Info`]: <span className="form-info"> [`${name}Info`]: infoComponent,
{info
? info
: initialInfo
}
</span>
} }
]; ], {
onChange,
reset,
name,
value: file,
previewValue: imageURL,
hasChanged: () => file != undefined,
infoComponent
});
}; };

View file

@ -33,5 +33,6 @@ function makeHook(func) {
module.exports = { module.exports = {
useTextInput: makeHook(require("./text")), useTextInput: makeHook(require("./text")),
useFileInput: makeHook(require("./file")), useFileInput: makeHook(require("./file")),
useBoolInput: makeHook(require("./bool")),
useComboBoxInput: makeHook(require("./combobox")) useComboBoxInput: makeHook(require("./combobox"))
}; };

View file

@ -0,0 +1,50 @@
/*
GoToSocial
Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const syncpipe = require("syncpipe");
module.exports = function useFormSubmit(form, [mutationQuery, result]) {
return [
result,
function submitForm(e) {
e.preventDefault();
// transform the field definitions into an object with just their values
let updatedFields = [];
const mutationData = syncpipe(form, [
(_) => Object.values(_),
(_) => _.map((field) => {
if (field.hasChanged()) {
updatedFields.push(field);
return [field.name, field.value];
} else {
return null;
}
}),
(_) => _.filter((value) => value != null),
(_) => Object.fromEntries(_)
]);
if (updatedFields.length > 0) {
return mutationQuery(mutationData);
}
},
];
};

View file

@ -39,18 +39,27 @@ module.exports = function useTextInput({name, Name}, {validator, defaultValue=""
let res = validator(text); let res = validator(text);
setValid(res == ""); setValid(res == "");
textRef.current.setCustomValidity(res); textRef.current.setCustomValidity(res);
textRef.current.reportValidity();
} }
}, [text, textRef, validator]); }, [text, textRef, validator]);
return [ // Array / Object hybrid, for easier access in different contexts
return Object.assign([
onChange, onChange,
reset, reset,
{ {
[name]: text, [name]: text,
[`${name}Ref`]: textRef, [`${name}Ref`]: textRef,
[`set${Name}`]: setText, [`set${Name}`]: setText,
[`${name}Valid`]: valid [`${name}Valid`]: valid,
} }
]; ], {
onChange,
reset,
name,
value: text,
ref: textRef,
setter: setText,
valid,
hasChanged: () => text != defaultValue
});
}; };

View file

@ -50,6 +50,6 @@ function instanceBasedQuery(args, api, extraOptions) {
module.exports = createApi({ module.exports = createApi({
reducerPath: "api", reducerPath: "api",
baseQuery: instanceBasedQuery, baseQuery: instanceBasedQuery,
tagTypes: ["Emojis"], tagTypes: ["Emojis", "User"],
endpoints: () => ({}) endpoints: () => ({})
}); });

View file

@ -20,16 +20,9 @@
const Promise = require("bluebird"); const Promise = require("bluebird");
const { unwrapRes } = require("./lib");
const base = require("./base"); const base = require("./base");
function unwrap(res) {
if (res.error != undefined) {
throw res.error;
} else {
return res.data;
}
}
const endpoints = (build) => ({ const endpoints = (build) => ({
getAllEmoji: build.query({ getAllEmoji: build.query({
query: (params = {}) => ({ query: (params = {}) => ({
@ -132,7 +125,7 @@ const endpoints = (build) => ({
filter: `domain:${domain},shortcode:${emoji.shortcode}`, filter: `domain:${domain},shortcode:${emoji.shortcode}`,
limit: 1 limit: 1
} }
}).then(unwrap); }).then(unwrapRes);
}).then(([lookup]) => { }).then(([lookup]) => {
if (lookup == undefined) { throw "not found"; } if (lookup == undefined) { throw "not found"; }
@ -152,7 +145,7 @@ const endpoints = (build) => ({
url: `/api/v1/admin/custom_emojis/${lookup.id}`, url: `/api/v1/admin/custom_emojis/${lookup.id}`,
asForm: true, asForm: true,
body: body body: body
}).then(unwrap); }).then(unwrapRes);
}).then((res) => { }).then((res) => {
data.push([emoji.shortcode, res]); data.push([emoji.shortcode, res]);
}).catch((e) => { }).catch((e) => {

View file

@ -20,5 +20,6 @@
module.exports = { module.exports = {
...require("./base"), ...require("./base"),
...require("./custom-emoji.js") ...require("./custom-emoji.js"),
...require("./user-settings")
}; };

View file

@ -0,0 +1,43 @@
/*
GoToSocial
Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const base = require("./base");
module.exports = {
unwrapRes(res) {
if (res.error != undefined) {
throw res.error;
} else {
return res.data;
}
},
updateCacheOnMutation(queryName, arg = undefined) {
// https://redux-toolkit.js.org/rtk-query/usage/manual-cache-updates#pessimistic-updates
return {
onQueryStarted: (_, { dispatch, queryFulfilled}) => {
queryFulfilled.then(({data: newData}) => {
dispatch(base.util.updateQueryData(queryName, arg, (draft) => {
Object.assign(draft, newData);
}));
});
}
};
}
};

View file

@ -0,0 +1,48 @@
/*
GoToSocial
Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
const { updateCacheOnMutation } = require("./lib");
const base = require("./base");
const endpoints = (build) => ({
verifyCredentials: build.query({
query: () => ({
url: `/api/v1/accounts/verify_credentials`
})
}),
updateCredentials: build.mutation({
query: (formData) => ({
method: "PATCH",
url: `/api/v1/accounts/update_credentials`,
asForm: true,
body: formData
}),
...updateCacheOnMutation("verifyCredentials")
}),
passwordChange: build.mutation({
query: (data) => ({
method: "POST",
url: `/api/v1/user/password_change`,
body: data
})
})
});
module.exports = base.injectEndpoints({endpoints});

View file

@ -40,7 +40,7 @@ section {
border-top-left-radius: 0; border-top-left-radius: 0;
border-bottom-left-radius: 0; border-bottom-left-radius: 0;
& > div { & > div, & > form {
border-left: 0.2rem solid $border-accent; border-left: 0.2rem solid $border-accent;
padding-left: 0.4rem; padding-left: 0.4rem;
display: flex; display: flex;
@ -213,7 +213,7 @@ input, select, textarea {
) !important; ) !important;
} }
section.with-sidebar > div { section.with-sidebar > div, section.with-sidebar > form {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 1rem; gap: 1rem;
@ -337,22 +337,28 @@ section.with-sidebar > div {
} }
} }
form {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.form-field label { .form-field label {
font-weight: bold; font-weight: bold;
} }
.form-field.file { .form-field.file label {
width: 100%; width: 100%;
display: flex; display: flex;
} }
span.form-info { span.form-info {
flex: 1 1 auto; flex: 1 1 auto;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
padding: 0.3rem 0; padding: 0.3rem 0;
font-weight: initial;
} }
.list { .list {

View file

@ -21,86 +21,122 @@
const React = require("react"); const React = require("react");
const Redux = require("react-redux"); const Redux = require("react-redux");
const Submit = require("../components/submit"); const query = require("../lib/query");
const api = require("../lib/api"); const {
const user = require("../redux/reducers/user").actions; useTextInput,
const submit = require("../lib/submit"); useFileInput,
useBoolInput
} = require("../lib/form");
const FakeProfile = require("../components/fake-profile"); const useFormSubmit = require("../lib/form/submit");
const { formFields } = require("../components/form-fields");
const { const {
TextInput, TextInput,
TextArea, TextArea,
Checkbox, FileInput,
File Checkbox
} = formFields(user.setProfileVal, (state) => state.user.profile); } = require("../components/form/inputs");
const FakeProfile = require("../components/fake-profile");
const MutationButton = require("../components/form/mutation-button");
const Loading = require("../components/loading");
module.exports = function UserProfile() { module.exports = function UserProfile() {
const dispatch = Redux.useDispatch(); const {data: profile = {}, isLoading} = query.useVerifyCredentialsQuery();
const instance = Redux.useSelector(state => state.instances.current);
const allowCustomCSS = instance.configuration.accounts.allow_custom_css; if (isLoading) {
return <Loading/>;
} else {
return <UserProfileForm profile={profile} />;
}
};
const [errorMsg, setError] = React.useState(""); function UserProfileForm({profile}) {
const [statusMsg, setStatus] = React.useState(""); /*
User profile update form keys
- bool bot
- bool locked
- string display_name
- string note
- file avatar
- file header
- bool enable_rss
- string custom_css (if enabled)
*/
const saveProfile = submit( const form = {
() => dispatch(api.user.updateProfile()), avatar: useFileInput("avatar", {withPreview: true, }),
{setStatus, setError} header: useFileInput("header", {withPreview: true, }),
); displayName: useTextInput("display_name", {defaultValue: profile.display_name}),
note: useTextInput("note", {defaultValue: profile.source?.note}),
customCSS: useTextInput("custom_css", {defaultValue: profile.custom_css}),
bot: useBoolInput("bot", {defaultValue: profile.bot}),
locked: useBoolInput("locked", {defaultValue: profile.locked}),
enableRSS: useBoolInput("enable_rss", {defaultValue: profile.enable_rss}),
};
const allowCustomCSS = Redux.useSelector(state => state.instances.current.configuration.accounts.allow_custom_css);
const [result, submitForm] = useFormSubmit(form, query.useUpdateCredentialsMutation());
return ( return (
<div className="user-profile"> <form className="user-profile" onSubmit={submitForm}>
<h1>Profile</h1> <h1>Profile</h1>
<div className="overview"> <div className="overview">
<FakeProfile/> <FakeProfile
avatar={form.avatar.previewValue ?? profile.avatar}
header={form.header.previewValue ?? profile.header}
display_name={form.displayName.value ?? profile.username}
username={profile.username}
role={profile.role}
/>
<div className="files"> <div className="files">
<div> <div>
<h3>Header</h3> <h3>Header</h3>
<File <FileInput
id="header" field={form.header}
fileType="image/*" accept="image/*"
/> />
</div> </div>
<div> <div>
<h3>Avatar</h3> <h3>Avatar</h3>
<File <FileInput
id="avatar" field={form.avatar}
fileType="image/*" accept="image/*"
/> />
</div> </div>
</div> </div>
</div> </div>
<TextInput <TextInput
id="display_name" field={form.displayName}
name="Name" label="Name"
placeHolder="A GoToSocial user" placeholder="A GoToSocial user"
/> />
<TextArea <TextArea
id="source.note" field={form.note}
name="Bio" label="Bio"
placeHolder="Just trying out GoToSocial, my pronouns are they/them and I like sloths." placeholder="Just trying out GoToSocial, my pronouns are they/them and I like sloths."
rows={8}
/> />
<Checkbox <Checkbox
id="locked" field={form.locked}
name="Manually approve follow requests" label="Manually approve follow requests"
/> />
<Checkbox <Checkbox
id="enable_rss" field={form.enableRSS}
name="Enable RSS feed of Public posts" label="Enable RSS feed of Public posts"
/> />
{ !allowCustomCSS ? null : { !allowCustomCSS ? null :
<TextArea <TextArea
id="custom_css" field={form.customCSS}
name="Custom CSS" label="Custom CSS"
className="monospace" className="monospace"
rows={8}
> >
<a href="https://docs.gotosocial.org/en/latest/user_guide/custom_css" target="_blank" className="moreinfolink" rel="noreferrer">Learn more about custom profile CSS (opens in a new tab)</a> <a href="https://docs.gotosocial.org/en/latest/user_guide/custom_css" target="_blank" className="moreinfolink" rel="noreferrer">Learn more about custom profile CSS (opens in a new tab)</a>
</TextArea> </TextArea>
} }
<Submit onClick={saveProfile} label="Save profile info" errorMsg={errorMsg} statusMsg={statusMsg} /> <MutationButton text="Save profile info" result={result}/>
</div> </form>
); );
}; }

View file

@ -23,37 +23,64 @@ const React = require("react");
const Redux = require("react-redux"); const Redux = require("react-redux");
const api = require("../lib/api"); const api = require("../lib/api");
const user = require("../redux/reducers/user").actions;
const submit = require("../lib/submit");
const Languages = require("../components/languages"); const Languages = require("../components/languages");
const Submit = require("../components/submit"); const Submit = require("../components/submit");
const query = require("../lib/query");
const {
useTextInput,
useBoolInput
} = require("../lib/form");
const useFormSubmit = require("../lib/form/submit");
const { const {
Checkbox,
Select, Select,
} = require("../components/form-fields").formFields(user.setSettingsVal, (state) => state.user.settings); TextInput,
Checkbox
} = require("../components/form/inputs");
const MutationButton = require("../components/form/mutation-button");
const Loading = require("../components/loading");
module.exports = function UserSettings() { module.exports = function UserSettings() {
const dispatch = Redux.useDispatch(); const {data: profile, isLoading} = query.useVerifyCredentialsQuery();
const [errorMsg, setError] = React.useState(""); if (isLoading) {
const [statusMsg, setStatus] = React.useState(""); return <Loading/>;
} else {
return <UserSettingsForm source={profile.source} />;
}
};
const updateSettings = submit( function UserSettingsForm({source}) {
() => dispatch(api.user.updateSettings()), /* form keys
{setStatus, setError} - string source[privacy]
); - bool source[sensitive]
- string source[language]
- string source[status_format]
*/
const form = {
defaultPrivacy: useTextInput("source[privacy]", {defaultValue: source.privacy ?? "unlisted"}),
isSensitive: useBoolInput("source[sensitive]", {defaultValue: source.sensitive}),
language: useTextInput("source[language]", {defaultValue: source.language ?? "EN"}),
format: useTextInput("source[status_format]", {defaultValue: source.status_format ?? "plain"}),
};
const [result, submitForm] = useFormSubmit(form, query.useUpdateCredentialsMutation());
return ( return (
<> <>
<div className="user-settings"> <form className="user-settings" onSubmit={submitForm}>
<h1>Post settings</h1> <h1>Post settings</h1>
<Select id="source.language" name="Default post language" options={ <Select field={form.language} label="Default post language" options={
<Languages/> <Languages/>
}> }>
</Select> </Select>
<Select id="source.privacy" name="Default post privacy" options={ <Select field={form.defaultPrivacy} label="Default post privacy" options={
<> <>
<option value="private">Private / followers-only</option> <option value="private">Private / followers-only</option>
<option value="unlisted">Unlisted</option> <option value="unlisted">Unlisted</option>
@ -62,7 +89,7 @@ module.exports = function UserSettings() {
}> }>
<a href="https://docs.gotosocial.org/en/latest/user_guide/posts/#privacy-settings" target="_blank" className="moreinfolink" rel="noreferrer">Learn more about post privacy settings (opens in a new tab)</a> <a href="https://docs.gotosocial.org/en/latest/user_guide/posts/#privacy-settings" target="_blank" className="moreinfolink" rel="noreferrer">Learn more about post privacy settings (opens in a new tab)</a>
</Select> </Select>
<Select id="source.status_format" name="Default post (and bio) format" options={ <Select field={form.format} label="Default post (and bio) format" options={
<> <>
<option value="plain">Plain (default)</option> <option value="plain">Plain (default)</option>
<option value="markdown">Markdown</option> <option value="markdown">Markdown</option>
@ -71,70 +98,48 @@ module.exports = function UserSettings() {
<a href="https://docs.gotosocial.org/en/latest/user_guide/posts/#input-types" target="_blank" className="moreinfolink" rel="noreferrer">Learn more about post format settings (opens in a new tab)</a> <a href="https://docs.gotosocial.org/en/latest/user_guide/posts/#input-types" target="_blank" className="moreinfolink" rel="noreferrer">Learn more about post format settings (opens in a new tab)</a>
</Select> </Select>
<Checkbox <Checkbox
id="source.sensitive" field={form.isSensitive}
name="Mark my posts as sensitive by default" label="Mark my posts as sensitive by default"
/> />
<Submit onClick={updateSettings} label="Save post settings" errorMsg={errorMsg} statusMsg={statusMsg}/> <MutationButton text="Save settings" result={result}/>
</div> </form>
<div> <div>
<PasswordChange/> <PasswordChange/>
</div> </div>
</> </>
); );
}; }
function PasswordChange() { function PasswordChange() {
const dispatch = Redux.useDispatch(); const form = {
oldPassword: useTextInput("old_password"),
newPassword: useTextInput("old_password", {validator(val) {
if (val != "" && val == form.oldPassword.value) {
return "New password same as old password";
}
return "";
}})
};
const [errorMsg, setError] = React.useState(""); const verifyNewPassword = useTextInput("verifyNewPassword", {
const [statusMsg, setStatus] = React.useState(""); validator(val) {
if (val != "" && val != form.newPassword.value) {
const [oldPassword, setOldPassword] = React.useState(""); return "Passwords do not match";
const [newPassword, setNewPassword] = React.useState(""); }
const [newPasswordConfirm, setNewPasswordConfirm] = React.useState(""); return "";
function changePassword() {
if (newPassword !== newPasswordConfirm) {
setError("New password and confirm new password did not match!");
return;
} }
});
setStatus("PATCHing"); const [result, submitForm] = useFormSubmit(form, query.usePasswordChangeMutation());
setError("");
return Promise.try(() => {
let data = {
old_password: oldPassword,
new_password: newPassword
};
return dispatch(api.apiCall("POST", "/api/v1/user/password_change", data, "form"));
}).then(() => {
setStatus("Saved!");
setOldPassword("");
setNewPassword("");
setNewPasswordConfirm("");
}).catch((e) => {
setError(e.message);
setStatus("");
});
}
return ( return (
<> <form className="change-password" onSubmit={submitForm}>
<h1>Change password</h1> <h1>Change password</h1>
<div className="labelinput"> <TextInput type="password" field={form.oldPassword} label="Current password"/>
<label htmlFor="password">Current password</label> <TextInput type="password" field={form.newPassword} label="New password"/>
<input name="password" id="password" type="password" autoComplete="current-password" value={oldPassword} onChange={(e) => setOldPassword(e.target.value)} /> <TextInput type="password" field={verifyNewPassword} label="Confirm new password"/>
</div> <MutationButton text="Change password" result={result}/>
<div className="labelinput"> </form>
<label htmlFor="new-password">New password</label>
<input name="new-password" id="new-password" type="password" autoComplete="new-password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />
</div>
<div className="labelinput">
<label htmlFor="confirm-new-password">Confirm new password</label>
<input name="confirm-new-password" id="confirm-new-password" type="password" autoComplete="new-password" value={newPasswordConfirm} onChange={(e) => setNewPasswordConfirm(e.target.value)} />
</div>
<Submit onClick={changePassword} label="Save new password" errorMsg={errorMsg} statusMsg={statusMsg}/>
</>
); );
} }