Files
cinny/src/app/organisms/profile-editor/ProfileEditor.jsx
T

91 lines
2.7 KiB
React
Raw Normal View History

2021-09-09 00:47:26 -05:00
import React, { useState, useRef } from 'react';
import PropTypes from 'prop-types';
import initMatrix from '../../../client/initMatrix';
import colorMXID from '../../../util/colorMXID';
import Button from '../../atoms/button/Button';
2021-09-12 22:25:58 -05:00
import ImageUpload from '../../molecules/image-upload/ImageUpload';
2021-09-09 00:47:26 -05:00
import Input from '../../atoms/input/Input';
import Text from '../../atoms/text/Text';
import './ProfileEditor.scss';
// TODO Fix bug that prevents 'Save' button from enabling up until second changed.
function ProfileEditor({
userId,
}) {
const mx = initMatrix.matrixClient;
const displayNameRef = useRef(null);
const bgColor = colorMXID(userId);
2021-09-13 12:27:55 +05:30
const [avatarSrc, setAvatarSrc] = useState(mx.mxcUrlToHttp(mx.getUser(mx.getUserId()).avatarUrl, 80, 80, 'crop') || null);
2021-09-09 00:47:26 -05:00
const [disabled, setDisabled] = useState(true);
let username = mx.getUser(mx.getUserId()).displayName;
2021-09-09 00:59:17 -05:00
// Sets avatar URL and updates the avatar component in profile editor to reflect new upload
2021-09-13 12:27:55 +05:30
function handleAvatarUpload(url) {
if (url === null) {
if (confirm('Are you sure you want to remove avatar?')) {
mx.setAvatarUrl('');
setAvatarSrc(null);
}
return;
}
mx.setAvatarUrl(url);
setAvatarSrc(mx.mxcUrlToHttp(url, 80, 80, 'crop'));
2021-09-09 00:47:26 -05:00
}
function saveDisplayName() {
const newDisplayName = displayNameRef.current.value;
if (newDisplayName !== null && newDisplayName !== username) {
mx.setDisplayName(newDisplayName);
username = newDisplayName;
2021-09-09 00:47:26 -05:00
setDisabled(true);
}
}
function onDisplayNameInputChange() {
setDisabled(username === displayNameRef.current.value || displayNameRef.current.value == null);
}
function cancelDisplayNameChanges() {
displayNameRef.current.value = username;
onDisplayNameInputChange();
2021-09-09 00:47:26 -05:00
}
return (
<form
className="profile-editor"
onSubmit={(e) => { e.preventDefault(); saveDisplayName(); }}
>
2021-09-13 12:27:55 +05:30
<ImageUpload
text={username}
bgColor={bgColor}
imageSrc={avatarSrc}
onUpload={handleAvatarUpload}
onRequestRemove={() => handleAvatarUpload(null)}
/>
<div className="profile-editor__input-wrapper">
<Input
label={`Display name of ${mx.getUserId()}`}
onChange={onDisplayNameInputChange}
value={mx.getUser(mx.getUserId()).displayName}
forwardRef={displayNameRef}
/>
<Button variant="primary" type="submit" disabled={disabled}>Save</Button>
<Button onClick={cancelDisplayNameChanges}>Cancel</Button>
2021-09-09 00:47:26 -05:00
</div>
</form>
);
}
ProfileEditor.defaultProps = {
userId: null,
};
ProfileEditor.propTypes = {
userId: PropTypes.string,
};
export default ProfileEditor;