Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c9e32b6c4 | ||
|
|
fc470d0622 | ||
|
|
a3270041e3 | ||
|
|
956068d0d6 | ||
|
|
3776e32364 | ||
|
|
fb5a54dd17 | ||
|
|
916d564f82 | ||
|
|
364def188a | ||
|
|
d1228a085b | ||
|
|
6c5a29fb48 | ||
|
|
a83aecaa69 | ||
|
|
3d885ec262 | ||
|
|
6fdace07c8 | ||
|
|
8711658e75 | ||
|
|
e25dc46863 | ||
|
|
f53f54af7f | ||
|
|
763aa8865b | ||
|
|
2194cb65a2 | ||
|
|
60435d505f | ||
|
|
af983c76b8 | ||
|
|
ef161bbb31 | ||
|
|
ac364e5ab7 | ||
|
|
2e2b1c6f18 | ||
|
|
1fa1496d7f | ||
|
|
8fb9365eaa | ||
|
|
92ab8331d0 | ||
|
|
603d373cee | ||
|
|
aca2c3a9dd | ||
|
|
f544dab3e0 | ||
|
|
c489940f8b | ||
|
|
dc7ddeaa9b | ||
|
|
9b5f42cda9 | ||
|
|
4022e4969d | ||
|
|
ed62d06b5e | ||
|
|
f11e4f6626 | ||
|
|
59eec5241a | ||
|
|
d287486165 | ||
|
|
f70270a0b3 | ||
|
|
36380fe5fd | ||
|
|
dc7fca4f4c | ||
|
|
977759145e | ||
|
|
76c3660cb2 | ||
|
|
fa10a67811 | ||
|
|
8d95fd0ca0 | ||
|
|
332e95701e | ||
|
|
124b24ab76 | ||
|
|
6ccd1e43bc | ||
|
|
5c09d04912 | ||
|
|
119325c3a2 | ||
|
|
462a559bd3 | ||
|
|
1bd58a0103 | ||
|
|
6c97d08027 |
30
.github/workflows/pull-request.yml
vendored
Normal file
30
.github/workflows/pull-request.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
name: 'Netlify Preview Deploy'
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: ['opened', 'synchronize']
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: "Deploy to Netlify"
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: jsmrcaga/action-netlify-deploy@master
|
||||
with:
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE3_ID }}
|
||||
BUILD_DIRECTORY: "dist"
|
||||
- name: Post on PR
|
||||
uses: nwtgck/actions-netlify@v1.1
|
||||
with:
|
||||
publish-dir: "dist"
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
deploy-message: "Deploy from GitHub Actions"
|
||||
enable-pull-request-comment: true
|
||||
enable-commit-comment: false
|
||||
overwrites-pull-request-comment: true
|
||||
env:
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE3_ID }}
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,4 +1,6 @@
|
||||
experiment
|
||||
dist
|
||||
node_modules
|
||||
devAssets
|
||||
devAssets
|
||||
|
||||
.DS_Store
|
||||
|
||||
@@ -51,6 +51,10 @@ navigating to `http://localhost:8080`.
|
||||
|
||||
Alternatively you can just pull the [DockerHub image](https://hub.docker.com/r/ajbura/cinny) by `docker pull ajbura/cinny`.
|
||||
|
||||
### Configuring default Homeserver
|
||||
|
||||
To set default Homeserver on login and register page, place a customized [`config.json`](config.json) in webroot of your choice.
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2021 Ajay Bura (ajbura) and other contributors
|
||||
|
||||
12
config.json
Normal file
12
config.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"defaultHomeserver": 5,
|
||||
"homeserverList": [
|
||||
"boba.best",
|
||||
"converser.eu",
|
||||
"envs.net",
|
||||
"halogen.city",
|
||||
"kde.org",
|
||||
"matrix.org",
|
||||
"mozilla.modular.im"
|
||||
]
|
||||
}
|
||||
26266
package-lock.json
generated
26266
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
12
package.json
12
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cinny",
|
||||
"version": "1.3.2",
|
||||
"version": "1.5.0",
|
||||
"description": "Yet another matrix client",
|
||||
"main": "index.js",
|
||||
"engines": {
|
||||
@@ -22,8 +22,10 @@
|
||||
"dateformat": "^4.5.1",
|
||||
"emojibase-data": "^6.2.0",
|
||||
"flux": "^4.0.1",
|
||||
"formik": "^2.2.9",
|
||||
"html-react-parser": "^1.2.7",
|
||||
"linkifyjs": "^3.0.0-beta.3",
|
||||
"linkify-react": "^3.0.3",
|
||||
"linkifyjs": "^3.0.3",
|
||||
"matrix-js-sdk": "^12.4.1",
|
||||
"micromark": "^3.0.3",
|
||||
"micromark-extension-gfm": "^1.0.0",
|
||||
@@ -71,9 +73,9 @@
|
||||
"stream-browserify": "^3.0.0",
|
||||
"style-loader": "^2.0.0",
|
||||
"util": "^0.12.4",
|
||||
"webpack": "^5.28.0",
|
||||
"webpack-cli": "^4.5.0",
|
||||
"webpack-dev-server": "^3.11.2",
|
||||
"webpack": "^5.62.1",
|
||||
"webpack-cli": "^4.9.1",
|
||||
"webpack-dev-server": "^4.4.0",
|
||||
"webpack-merge": "^5.7.3"
|
||||
}
|
||||
}
|
||||
|
||||
7
public/res/ic/outlined/shield-empty.svg
Normal file
7
public/res/ic/outlined/shield-empty.svg
Normal file
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 18.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve">
|
||||
<path d="M12,2L3,6v7c0,5,4,9,9,9c5,0,9-4,9-9V6L12,2z M19,13c0,3.9-3.1,7-7,7s-7-3.1-7-7V7.3l7-3.1l7,3.1V13z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 554 B |
@@ -24,7 +24,6 @@
|
||||
height: var(--av-extra-small);
|
||||
}
|
||||
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
@@ -6,18 +6,20 @@ import Text from '../text/Text';
|
||||
import RawIcon from '../system-icons/RawIcon';
|
||||
import { blurOnBubbling } from './script';
|
||||
|
||||
function Button({
|
||||
const Button = React.forwardRef(({
|
||||
id, className, variant, iconSrc,
|
||||
type, onClick, children, disabled,
|
||||
}) {
|
||||
}, ref) => {
|
||||
const iconClass = (iconSrc === null) ? '' : `btn-${variant}--icon`;
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
id={id === '' ? undefined : id}
|
||||
className={`${className ? `${className} ` : ''}btn-${variant} ${iconClass} noselect`}
|
||||
onMouseUp={(e) => blurOnBubbling(e, `.btn-${variant}`)}
|
||||
onClick={onClick}
|
||||
type={type === 'button' ? 'button' : 'submit'}
|
||||
// eslint-disable-next-line react/button-has-type
|
||||
type={type}
|
||||
disabled={disabled}
|
||||
>
|
||||
{iconSrc !== null && <RawIcon size="small" src={iconSrc} />}
|
||||
@@ -25,7 +27,7 @@ function Button({
|
||||
{typeof children !== 'string' && children }
|
||||
</button>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Button.defaultProps = {
|
||||
id: '',
|
||||
@@ -42,7 +44,7 @@ Button.propTypes = {
|
||||
className: PropTypes.string,
|
||||
variant: PropTypes.oneOf(['surface', 'primary', 'positive', 'caution', 'danger']),
|
||||
iconSrc: PropTypes.string,
|
||||
type: PropTypes.oneOf(['button', 'submit']),
|
||||
type: PropTypes.oneOf(['button', 'submit', 'reset']),
|
||||
onClick: PropTypes.func,
|
||||
children: PropTypes.node.isRequired,
|
||||
disabled: PropTypes.bool,
|
||||
|
||||
@@ -17,7 +17,8 @@ const IconButton = React.forwardRef(({
|
||||
className={`ic-btn ic-btn-${variant}`}
|
||||
onMouseUp={(e) => blurOnBubbling(e, `.ic-btn-${variant}`)}
|
||||
onClick={onClick}
|
||||
type={type === 'button' ? 'button' : 'submit'}
|
||||
// eslint-disable-next-line react/button-has-type
|
||||
type={type}
|
||||
>
|
||||
<RawIcon size={size} src={src} />
|
||||
</button>
|
||||
@@ -45,7 +46,7 @@ IconButton.defaultProps = {
|
||||
IconButton.propTypes = {
|
||||
variant: PropTypes.oneOf(['surface', 'positive', 'caution', 'danger']),
|
||||
size: PropTypes.oneOf(['normal', 'small', 'extra-small']),
|
||||
type: PropTypes.oneOf(['button', 'submit']),
|
||||
type: PropTypes.oneOf(['button', 'submit', 'reset']),
|
||||
tooltip: PropTypes.string,
|
||||
tooltipPlacement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
|
||||
src: PropTypes.string.isRequired,
|
||||
|
||||
@@ -7,13 +7,14 @@ import RawIcon from '../system-icons/RawIcon';
|
||||
|
||||
function Chip({
|
||||
iconSrc, iconColor, text, children,
|
||||
onClick,
|
||||
}) {
|
||||
return (
|
||||
<div className="chip">
|
||||
{iconSrc != null && <RawIcon src={iconSrc} color={iconColor} size="small" />}
|
||||
{(text != null && text !== '') && <Text variant="b2">{text}</Text>}
|
||||
<button className="chip" type="button" onClick={onClick}>
|
||||
{iconSrc != null && <RawIcon src={iconSrc} color={iconColor} size="extra-small" />}
|
||||
{(text != null && text !== '') && <Text variant="b3">{text}</Text>}
|
||||
{children}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,6 +23,7 @@ Chip.propTypes = {
|
||||
iconColor: PropTypes.string,
|
||||
text: PropTypes.string,
|
||||
children: PropTypes.element,
|
||||
onClick: PropTypes.func,
|
||||
};
|
||||
|
||||
Chip.defaultProps = {
|
||||
@@ -29,6 +31,7 @@ Chip.defaultProps = {
|
||||
iconColor: null,
|
||||
text: null,
|
||||
children: null,
|
||||
onClick: null,
|
||||
};
|
||||
|
||||
export default Chip;
|
||||
|
||||
@@ -7,13 +7,27 @@
|
||||
|
||||
background: var(--bg-surface-low);
|
||||
border-radius: var(--bo-radius);
|
||||
border: 1px solid var(--bg-surface-border);
|
||||
box-shadow: var(--bs-surface-border);
|
||||
cursor: pointer;
|
||||
|
||||
@media (hover: hover) {
|
||||
&:hover {
|
||||
background-color: var(--bg-surface-hover);
|
||||
}
|
||||
}
|
||||
|
||||
& > .text {
|
||||
flex: 1;
|
||||
color: var(--tc-surface-high);
|
||||
}
|
||||
|
||||
& > .ic-raw {
|
||||
margin-right: var(--sp-extra-tight);
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin-right: var(--sp-ultra-tight);
|
||||
[dir=rtl] & {
|
||||
margin-right: 0;
|
||||
margin-left: var(--sp-extra-tight);
|
||||
margin-left: var(--sp-ultra-tight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import './Input.scss';
|
||||
import TextareaAutosize from 'react-autosize-textarea';
|
||||
|
||||
function Input({
|
||||
id, label, value, placeholder,
|
||||
id, label, name, value, placeholder,
|
||||
required, type, onChange, forwardRef,
|
||||
resizable, minHeight, onResize, state,
|
||||
onKeyDown,
|
||||
@@ -17,6 +17,7 @@ function Input({
|
||||
? (
|
||||
<TextareaAutosize
|
||||
style={{ minHeight: `${minHeight}px` }}
|
||||
name={name}
|
||||
id={id}
|
||||
className={`input input--resizable${state !== 'normal' ? ` input--${state}` : ''}`}
|
||||
ref={forwardRef}
|
||||
@@ -33,6 +34,7 @@ function Input({
|
||||
<input
|
||||
ref={forwardRef}
|
||||
id={id}
|
||||
name={name}
|
||||
className={`input ${state !== 'normal' ? ` input--${state}` : ''}`}
|
||||
type={type}
|
||||
placeholder={placeholder}
|
||||
@@ -49,6 +51,7 @@ function Input({
|
||||
|
||||
Input.defaultProps = {
|
||||
id: null,
|
||||
name: '',
|
||||
label: '',
|
||||
value: '',
|
||||
placeholder: '',
|
||||
@@ -65,6 +68,7 @@ Input.defaultProps = {
|
||||
|
||||
Input.propTypes = {
|
||||
id: PropTypes.string,
|
||||
name: PropTypes.string,
|
||||
label: PropTypes.string,
|
||||
value: PropTypes.string,
|
||||
placeholder: PropTypes.string,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0px;
|
||||
margin: 0;
|
||||
padding: var(--sp-tight) var(--sp-normal);
|
||||
background-color: var(--bg-surface-low);
|
||||
color: var(--tc-surface-normal);
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
|
||||
@mixin scroll {
|
||||
overflow: hidden;
|
||||
overscroll-behavior: none;
|
||||
@extend .firefox-scrollbar;
|
||||
@extend .webkit-scrollbar;
|
||||
@extend .webkit-scrollbar-track;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './SegmentedControls.scss';
|
||||
|
||||
@@ -17,6 +17,10 @@ function SegmentedControls({
|
||||
onSelect(segmentIndex);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setSelect(selected);
|
||||
}, [selected]);
|
||||
|
||||
return (
|
||||
<div className="segmented-controls">
|
||||
{
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
& a {
|
||||
line-height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.file-container {
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { useRef } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './Message.scss';
|
||||
|
||||
import Linkify from 'linkifyjs/react';
|
||||
import Linkify from 'linkify-react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import gfm from 'remark-gfm';
|
||||
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
|
||||
|
||||
@@ -22,11 +22,12 @@
|
||||
|
||||
&__avatar-container {
|
||||
padding-top: 6px;
|
||||
}
|
||||
|
||||
&__avatar-container{
|
||||
margin-right: var(--sp-tight);
|
||||
|
||||
& button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
[dir=rtl] & {
|
||||
margin: {
|
||||
left: var(--sp-tight);
|
||||
@@ -159,7 +160,7 @@
|
||||
}
|
||||
|
||||
& a {
|
||||
word-break: break-all;
|
||||
word-break: break-word;
|
||||
}
|
||||
&-edited {
|
||||
color: var(--tc-surface-low);
|
||||
@@ -261,6 +262,16 @@
|
||||
right: unset;
|
||||
}
|
||||
}
|
||||
@media (min-width: 1620px) {
|
||||
.message__options {
|
||||
right: unset;
|
||||
left: 770px;
|
||||
[dir=rtl] {
|
||||
left: unset;
|
||||
right: 770px
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// markdown formating
|
||||
.message__content {
|
||||
@@ -398,4 +409,4 @@
|
||||
border-bottom-width: 0px !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@ import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './TimelineChange.scss';
|
||||
|
||||
// import Linkify from 'linkifyjs/react';
|
||||
|
||||
import Text from '../../atoms/text/Text';
|
||||
import RawIcon from '../../atoms/system-icons/RawIcon';
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './RoomIntro.scss';
|
||||
|
||||
import Linkify from 'linkifyjs/react';
|
||||
import Linkify from 'linkify-react';
|
||||
import colorMXID from '../../../util/colorMXID';
|
||||
|
||||
import Text from '../../atoms/text/Text';
|
||||
@@ -28,7 +28,7 @@ function RoomIntro({
|
||||
}
|
||||
|
||||
RoomIntro.defaultProps = {
|
||||
avatarSrc: false,
|
||||
avatarSrc: null,
|
||||
time: null,
|
||||
};
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './RoomTile.scss';
|
||||
|
||||
import Linkify from 'linkifyjs/react';
|
||||
import Linkify from 'linkify-react';
|
||||
import colorMXID from '../../../util/colorMXID';
|
||||
|
||||
import Text from '../../atoms/text/Text';
|
||||
|
||||
41
src/app/molecules/sso-buttons/SSOButtons.jsx
Normal file
41
src/app/molecules/sso-buttons/SSOButtons.jsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './SSOButtons.scss';
|
||||
|
||||
import { createTemporaryClient, startSsoLogin } from '../../../client/action/auth';
|
||||
|
||||
import Button from '../../atoms/button/Button';
|
||||
|
||||
function SSOButtons({ type, identityProviders, baseUrl }) {
|
||||
const tempClient = createTemporaryClient(baseUrl);
|
||||
function handleClick(id) {
|
||||
startSsoLogin(baseUrl, type, id);
|
||||
}
|
||||
return (
|
||||
<div className="sso-buttons">
|
||||
{identityProviders
|
||||
.sort((idp, idp2) => {
|
||||
if (typeof idp.icon !== 'string') return -1;
|
||||
return idp.name.toLowerCase() > idp2.name.toLowerCase() ? 1 : -1;
|
||||
})
|
||||
.map((idp) => (
|
||||
idp.icon
|
||||
? (
|
||||
<button key={idp.id} type="button" className="sso-btn" onClick={() => handleClick(idp.id)}>
|
||||
<img className="sso-btn__img" src={tempClient.mxcUrlToHttp(idp.icon)} alt={idp.name} />
|
||||
</button>
|
||||
) : <Button key={idp.id} className="sso-btn__text-only" onClick={() => handleClick(idp.id)}>{`Login with ${idp.name}`}</Button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
SSOButtons.propTypes = {
|
||||
identityProviders: PropTypes.arrayOf(
|
||||
PropTypes.shape({}),
|
||||
).isRequired,
|
||||
baseUrl: PropTypes.string.isRequired,
|
||||
type: PropTypes.oneOf(['sso', 'cas']).isRequired,
|
||||
};
|
||||
|
||||
export default SSOButtons;
|
||||
25
src/app/molecules/sso-buttons/SSOButtons.scss
Normal file
25
src/app/molecules/sso-buttons/SSOButtons.scss
Normal file
@@ -0,0 +1,25 @@
|
||||
.sso-buttons {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.sso-btn {
|
||||
margin: var(--sp-tight);
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
|
||||
cursor: pointer;
|
||||
|
||||
&__img {
|
||||
height: var(--av-small);
|
||||
width: var(--av-small);
|
||||
}
|
||||
&__text-only {
|
||||
margin-top: var(--sp-normal);
|
||||
flex-basis: 100%;
|
||||
& .text {
|
||||
color: var(--tc-link);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import './CreateRoom.scss';
|
||||
import initMatrix from '../../../client/initMatrix';
|
||||
import { isRoomAliasAvailable } from '../../../util/matrixUtil';
|
||||
import * as roomActions from '../../../client/action/room';
|
||||
import { selectRoom } from '../../../client/action/navigation';
|
||||
|
||||
import Text from '../../atoms/text/Text';
|
||||
import Button from '../../atoms/button/Button';
|
||||
@@ -12,6 +13,7 @@ import Toggle from '../../atoms/button/Toggle';
|
||||
import IconButton from '../../atoms/button/IconButton';
|
||||
import Input from '../../atoms/input/Input';
|
||||
import Spinner from '../../atoms/spinner/Spinner';
|
||||
import SegmentControl from '../../atoms/segmented-controls/SegmentedControls';
|
||||
import PopupWindow from '../../molecules/popup-window/PopupWindow';
|
||||
import SettingTile from '../../molecules/setting-tile/SettingTile';
|
||||
|
||||
@@ -28,6 +30,7 @@ function CreateRoom({ isOpen, onRequestClose }) {
|
||||
const [titleValue, updateTitleValue] = useState(undefined);
|
||||
const [topicValue, updateTopicValue] = useState(undefined);
|
||||
const [addressValue, updateAddressValue] = useState(undefined);
|
||||
const [roleIndex, setRoleIndex] = useState(0);
|
||||
|
||||
const addressRef = useRef(null);
|
||||
const topicRef = useRef(null);
|
||||
@@ -45,6 +48,7 @@ function CreateRoom({ isOpen, onRequestClose }) {
|
||||
updateTitleValue(undefined);
|
||||
updateTopicValue(undefined);
|
||||
updateAddressValue(undefined);
|
||||
setRoleIndex(0);
|
||||
}
|
||||
|
||||
async function createRoom() {
|
||||
@@ -60,12 +64,15 @@ function CreateRoom({ isOpen, onRequestClose }) {
|
||||
if (roomAlias.trim() === '') roomAlias = undefined;
|
||||
}
|
||||
|
||||
const powerLevel = roleIndex === 1 ? 101 : undefined;
|
||||
|
||||
try {
|
||||
await roomActions.create({
|
||||
name, topic, isPublic, roomAlias, isEncrypted,
|
||||
const result = await roomActions.create({
|
||||
name, topic, isPublic, roomAlias, isEncrypted, powerLevel,
|
||||
});
|
||||
|
||||
resetForm();
|
||||
selectRoom(result.room_id);
|
||||
onRequestClose();
|
||||
} catch (e) {
|
||||
if (e.message === 'M_UNKNOWN: Invalid characters in room alias') {
|
||||
@@ -139,6 +146,19 @@ function CreateRoom({ isOpen, onRequestClose }) {
|
||||
content={<Text variant="b3">You can’t disable this later. Bridges & most bots won’t work yet.</Text>}
|
||||
/>
|
||||
)}
|
||||
<SettingTile
|
||||
title="Select your role"
|
||||
options={(
|
||||
<SegmentControl
|
||||
selected={roleIndex}
|
||||
segments={[{ text: 'Admin' }, { text: 'Founder' }]}
|
||||
onSelect={setRoleIndex}
|
||||
/>
|
||||
)}
|
||||
content={(
|
||||
<Text variant="b3">Override the default (100) power level.</Text>
|
||||
)}
|
||||
/>
|
||||
<Input value={topicValue} onChange={handleTopicChange} forwardRef={topicRef} minHeight={174} resizable label="Topic (optional)" />
|
||||
<div className="create-room__name-wrapper">
|
||||
<Input value={titleValue} onChange={handleTitleChange} forwardRef={nameRef} label="Room name" required />
|
||||
|
||||
@@ -9,6 +9,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
& .segment-btn {
|
||||
padding: var(--sp-ultra-tight) 0;
|
||||
&__base {
|
||||
padding: 0 var(--sp-tight);
|
||||
}
|
||||
}
|
||||
|
||||
&__address {
|
||||
display: flex;
|
||||
&__label {
|
||||
|
||||
@@ -80,17 +80,17 @@ EmojiGroup.propTypes = {
|
||||
};
|
||||
|
||||
const asyncSearch = new AsyncSearch();
|
||||
asyncSearch.setup(emojis, { keys: ['shortcode'], limit: 30 });
|
||||
asyncSearch.setup(emojis, { keys: ['shortcode'], isContain: true, limit: 40 });
|
||||
function SearchedEmoji() {
|
||||
const [searchedEmojis, setSearchedEmojis] = useState(null);
|
||||
|
||||
function handleSearchEmoji(resultEmojis, term) {
|
||||
if (term === '' || resultEmojis.length === 0) {
|
||||
if (term === '') setSearchedEmojis(null);
|
||||
else setSearchedEmojis([]);
|
||||
else setSearchedEmojis({ emojis: [] });
|
||||
return;
|
||||
}
|
||||
setSearchedEmojis(resultEmojis);
|
||||
setSearchedEmojis({ emojis: resultEmojis });
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -102,7 +102,7 @@ function SearchedEmoji() {
|
||||
|
||||
if (searchedEmojis === null) return false;
|
||||
|
||||
return <EmojiGroup key="-1" name={searchedEmojis.length === 0 ? 'No search result found' : 'Search results'} groupEmojis={searchedEmojis} />;
|
||||
return <EmojiGroup key="-1" name={searchedEmojis.emojis.length === 0 ? 'No search result found' : 'Search results'} groupEmojis={searchedEmojis.emojis} />;
|
||||
}
|
||||
|
||||
function EmojiBoard({ onSelect }) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import './InviteList.scss';
|
||||
import initMatrix from '../../../client/initMatrix';
|
||||
import cons from '../../../client/state/cons';
|
||||
import * as roomActions from '../../../client/action/room';
|
||||
import { selectRoom, selectSpace } from '../../../client/action/navigation';
|
||||
|
||||
import Text from '../../atoms/text/Text';
|
||||
import Button from '../../atoms/button/Button';
|
||||
@@ -29,13 +30,18 @@ function InviteList({ isOpen, onRequestClose }) {
|
||||
roomActions.leave(roomId, isDM);
|
||||
}
|
||||
function updateInviteList(roomId) {
|
||||
if (procInvite.has(roomId)) {
|
||||
procInvite.delete(roomId);
|
||||
changeProcInvite(new Set(Array.from(procInvite)));
|
||||
} else changeProcInvite(new Set(Array.from(procInvite)));
|
||||
if (procInvite.has(roomId)) procInvite.delete(roomId);
|
||||
changeProcInvite(new Set(Array.from(procInvite)));
|
||||
|
||||
const rl = initMatrix.roomList;
|
||||
const totalInvites = rl.inviteDirects.size + rl.inviteRooms.size;
|
||||
const totalInvites = rl.inviteDirects.size + rl.inviteRooms.size + rl.inviteSpaces.size;
|
||||
const room = initMatrix.matrixClient.getRoom(roomId);
|
||||
const isRejected = room === null || room?.getMyMembership() !== 'join';
|
||||
if (!isRejected) {
|
||||
if (room.isSpaceRoom()) selectSpace(roomId);
|
||||
else selectRoom(roomId);
|
||||
onRequestClose();
|
||||
}
|
||||
if (totalInvites === 0) onRequestClose();
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,28 @@ import PowerIC from '../../../../public/res/ic/outlined/power.svg';
|
||||
|
||||
function ProfileAvatarMenu() {
|
||||
const mx = initMatrix.matrixClient;
|
||||
const [profile, setProfile] = useState({
|
||||
avatarUrl: null,
|
||||
displayName: mx.getUser(mx.getUserId()).displayName,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const user = mx.getUser(mx.getUserId());
|
||||
const setNewProfile = (avatarUrl, displayName) => setProfile({
|
||||
avatarUrl: avatarUrl || null,
|
||||
displayName: displayName || profile.displayName,
|
||||
});
|
||||
const onAvatarChange = (event, myUser) => {
|
||||
setNewProfile(myUser.avatarUrl, myUser.displayName);
|
||||
};
|
||||
mx.getProfileInfo(mx.getUserId()).then((info) => {
|
||||
setNewProfile(info.avatar_url, info.displayname);
|
||||
});
|
||||
user.on('User.avatarUrl', onAvatarChange);
|
||||
return () => {
|
||||
user.removeListener('User.avatarUrl', onAvatarChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ContextMenu
|
||||
@@ -45,10 +67,10 @@ function ProfileAvatarMenu() {
|
||||
render={(toggleMenu) => (
|
||||
<SidebarAvatar
|
||||
onClick={toggleMenu}
|
||||
tooltip={mx.getUser(mx.getUserId()).displayName}
|
||||
imageSrc={mx.getUser(mx.getUserId()).avatarUrl !== null ? mx.mxcUrlToHttp(mx.getUser(mx.getUserId()).avatarUrl, 42, 42, 'crop') : null}
|
||||
tooltip={profile.displayName}
|
||||
imageSrc={profile.avatarUrl !== null ? mx.mxcUrlToHttp(profile.avatarUrl, 42, 42, 'crop') : null}
|
||||
bgColor={colorMXID(mx.getUserId())}
|
||||
text={mx.getUser(mx.getUserId()).displayName.slice(0, 1)}
|
||||
text={profile.displayName.slice(0, 1)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
@@ -99,6 +121,7 @@ function SideBar() {
|
||||
let noti = null;
|
||||
|
||||
orphans.forEach((roomId) => {
|
||||
if (roomList.spaceShortcut.has(roomId)) return;
|
||||
if (!notifications.hasNoti(roomId)) return;
|
||||
if (noti === null) noti = { total: 0, highlight: 0 };
|
||||
const childNoti = notifications.getNoti(roomId);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useRef } from 'react';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
import initMatrix from '../../../client/initMatrix';
|
||||
@@ -17,11 +17,17 @@ function ProfileEditor({
|
||||
const mx = initMatrix.matrixClient;
|
||||
const displayNameRef = useRef(null);
|
||||
const bgColor = colorMXID(userId);
|
||||
const [avatarSrc, setAvatarSrc] = useState(mx.mxcUrlToHttp(mx.getUser(mx.getUserId()).avatarUrl, 80, 80, 'crop') || null);
|
||||
const [avatarSrc, setAvatarSrc] = useState(null);
|
||||
const [disabled, setDisabled] = useState(true);
|
||||
|
||||
let username = mx.getUser(mx.getUserId()).displayName;
|
||||
|
||||
useEffect(() => {
|
||||
mx.getProfileInfo(mx.getUserId()).then((info) => {
|
||||
setAvatarSrc(info.avatar_url ? mx.mxcUrlToHttp(info.avatar_url, 80, 80, 'crop') : null);
|
||||
});
|
||||
}, [userId]);
|
||||
|
||||
// Sets avatar URL and updates the avatar component in profile editor to reflect new upload
|
||||
function handleAvatarUpload(url) {
|
||||
if (url === null) {
|
||||
|
||||
298
src/app/organisms/profile-viewer/ProfileViewer.jsx
Normal file
298
src/app/organisms/profile-viewer/ProfileViewer.jsx
Normal file
@@ -0,0 +1,298 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './ProfileViewer.scss';
|
||||
|
||||
import initMatrix from '../../../client/initMatrix';
|
||||
import cons from '../../../client/state/cons';
|
||||
import navigation from '../../../client/state/navigation';
|
||||
import { selectRoom } from '../../../client/action/navigation';
|
||||
import * as roomActions from '../../../client/action/room';
|
||||
|
||||
import { getUsername, getUsernameOfRoomMember, getPowerLabel } from '../../../util/matrixUtil';
|
||||
import colorMXID from '../../../util/colorMXID';
|
||||
|
||||
import Text from '../../atoms/text/Text';
|
||||
import Chip from '../../atoms/chip/Chip';
|
||||
import IconButton from '../../atoms/button/IconButton';
|
||||
import Avatar from '../../atoms/avatar/Avatar';
|
||||
import Button from '../../atoms/button/Button';
|
||||
import Dialog from '../../molecules/dialog/Dialog';
|
||||
import SettingTile from '../../molecules/setting-tile/SettingTile';
|
||||
|
||||
import ShieldEmptyIC from '../../../../public/res/ic/outlined/shield-empty.svg';
|
||||
import ChevronBottomIC from '../../../../public/res/ic/outlined/chevron-bottom.svg';
|
||||
import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
|
||||
|
||||
function SessionInfo({ userId }) {
|
||||
const [devices, setDevices] = useState(null);
|
||||
const mx = initMatrix.matrixClient;
|
||||
|
||||
useEffect(() => {
|
||||
let isUnmounted = false;
|
||||
|
||||
async function loadDevices() {
|
||||
try {
|
||||
await mx.downloadKeys([userId], true);
|
||||
const myDevices = mx.getStoredDevicesForUser(userId);
|
||||
|
||||
if (isUnmounted) return;
|
||||
setDevices(myDevices);
|
||||
} catch {
|
||||
setDevices([]);
|
||||
}
|
||||
}
|
||||
loadDevices();
|
||||
|
||||
return () => {
|
||||
isUnmounted = true;
|
||||
};
|
||||
}, [userId]);
|
||||
|
||||
function renderSessionChips() {
|
||||
return (
|
||||
<div className="session-info__chips">
|
||||
{devices === null && <Text variant="b3">Loading sessions...</Text>}
|
||||
{devices?.length === 0 && <Text variant="b3">No session found.</Text>}
|
||||
{devices !== null && (devices.map((device) => (
|
||||
<Chip
|
||||
key={device.deviceId}
|
||||
iconSrc={ShieldEmptyIC}
|
||||
text={device.getDisplayName() || device.deviceId}
|
||||
/>
|
||||
)))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="session-info">
|
||||
<SettingTile
|
||||
title="Sessions"
|
||||
content={renderSessionChips()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
SessionInfo.propTypes = {
|
||||
userId: PropTypes.string.isRequired,
|
||||
};
|
||||
|
||||
function ProfileFooter({ roomId, userId, onRequestClose }) {
|
||||
const [isCreatingDM, setIsCreatingDM] = useState(false);
|
||||
const [isIgnoring, setIsIgnoring] = useState(false);
|
||||
const [isUserIgnored, setIsUserIgnored] = useState(initMatrix.matrixClient.isUserIgnored(userId));
|
||||
|
||||
const isMountedRef = useRef(true);
|
||||
const mx = initMatrix.matrixClient;
|
||||
const room = mx.getRoom(roomId);
|
||||
const member = room.getMember(userId);
|
||||
const isInvitable = member?.membership !== 'join' && member?.membership !== 'ban';
|
||||
|
||||
const [isInviting, setIsInviting] = useState(false);
|
||||
const [isInvited, setIsInvited] = useState(member?.membership === 'invite');
|
||||
|
||||
const myPowerlevel = room.getMember(mx.getUserId()).powerLevel;
|
||||
const canIKick = room.currentState.hasSufficientPowerLevelFor('kick', myPowerlevel);
|
||||
|
||||
useEffect(() => () => {
|
||||
isMountedRef.current = false;
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
setIsUserIgnored(initMatrix.matrixClient.isUserIgnored(userId));
|
||||
setIsIgnoring(false);
|
||||
setIsInviting(false);
|
||||
}, [userId]);
|
||||
|
||||
async function openDM() {
|
||||
const directIds = [...initMatrix.roomList.directs];
|
||||
|
||||
// Check and open if user already have a DM with userId.
|
||||
for (let i = 0; i < directIds.length; i += 1) {
|
||||
const dRoom = mx.getRoom(directIds[i]);
|
||||
const roomMembers = dRoom.getMembers();
|
||||
if (roomMembers.length <= 2 && dRoom.currentState.members[userId]) {
|
||||
selectRoom(directIds[i]);
|
||||
onRequestClose();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Create new DM
|
||||
try {
|
||||
setIsCreatingDM(true);
|
||||
const result = await roomActions.create({
|
||||
isEncrypted: true,
|
||||
isDirect: true,
|
||||
invite: [userId],
|
||||
});
|
||||
|
||||
if (isMountedRef.current === false) return;
|
||||
setIsCreatingDM(false);
|
||||
selectRoom(result.room_id);
|
||||
onRequestClose();
|
||||
} catch {
|
||||
setIsCreatingDM(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleIgnore() {
|
||||
const ignoredUsers = mx.getIgnoredUsers();
|
||||
const uIndex = ignoredUsers.indexOf(userId);
|
||||
if (uIndex >= 0) {
|
||||
if (uIndex === -1) return;
|
||||
ignoredUsers.splice(uIndex, 1);
|
||||
} else ignoredUsers.push(userId);
|
||||
|
||||
try {
|
||||
setIsIgnoring(true);
|
||||
await mx.setIgnoredUsers(ignoredUsers);
|
||||
|
||||
if (isMountedRef.current === false) return;
|
||||
setIsUserIgnored(uIndex < 0);
|
||||
setIsIgnoring(false);
|
||||
} catch {
|
||||
setIsIgnoring(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleInvite() {
|
||||
try {
|
||||
setIsInviting(true);
|
||||
let isInviteSent = false;
|
||||
if (isInvited) await roomActions.kick(roomId, userId);
|
||||
else {
|
||||
await roomActions.invite(roomId, userId);
|
||||
isInviteSent = true;
|
||||
}
|
||||
if (isMountedRef.current === false) return;
|
||||
setIsInvited(isInviteSent);
|
||||
setIsInviting(false);
|
||||
} catch {
|
||||
setIsInviting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="profile-viewer__buttons">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={openDM}
|
||||
disabled={isCreatingDM}
|
||||
>
|
||||
{isCreatingDM ? 'Creating room...' : 'Message'}
|
||||
</Button>
|
||||
{ member?.membership === 'join' && <Button>Mention</Button>}
|
||||
{ (isInvited ? canIKick : room.canInvite(mx.getUserId())) && isInvitable && (
|
||||
<Button
|
||||
onClick={toggleInvite}
|
||||
disabled={isInviting}
|
||||
>
|
||||
{
|
||||
isInvited
|
||||
? `${isInviting ? 'Disinviting...' : 'Disinvite'}`
|
||||
: `${isInviting ? 'Inviting...' : 'Invite'}`
|
||||
}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant={isUserIgnored ? 'positive' : 'danger'}
|
||||
onClick={toggleIgnore}
|
||||
disabled={isIgnoring}
|
||||
>
|
||||
{
|
||||
isUserIgnored
|
||||
? `${isIgnoring ? 'Unignoring...' : 'Unignore'}`
|
||||
: `${isIgnoring ? 'Ignoring...' : 'Ignore'}`
|
||||
}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
ProfileFooter.propTypes = {
|
||||
roomId: PropTypes.string.isRequired,
|
||||
userId: PropTypes.string.isRequired,
|
||||
onRequestClose: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
function ProfileViewer() {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [roomId, setRoomId] = useState(null);
|
||||
const [userId, setUserId] = useState(null);
|
||||
|
||||
const mx = initMatrix.matrixClient;
|
||||
const room = roomId ? mx.getRoom(roomId) : null;
|
||||
let username = '';
|
||||
if (room !== null) {
|
||||
const roomMember = room.getMember(userId);
|
||||
if (roomMember) username = getUsernameOfRoomMember(roomMember);
|
||||
else username = getUsername(userId);
|
||||
}
|
||||
|
||||
function loadProfile(uId, rId) {
|
||||
setIsOpen(true);
|
||||
setUserId(uId);
|
||||
setRoomId(rId);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
navigation.on(cons.events.navigation.PROFILE_VIEWER_OPENED, loadProfile);
|
||||
return () => {
|
||||
navigation.removeListener(cons.events.navigation.PROFILE_VIEWER_OPENED, loadProfile);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) return;
|
||||
setUserId(null);
|
||||
setRoomId(null);
|
||||
}, [isOpen]);
|
||||
|
||||
function renderProfile() {
|
||||
const member = room.getMember(userId) || mx.getUser(userId);
|
||||
const avatarMxc = member.getMxcAvatarUrl() || member.avatarUrl;
|
||||
|
||||
return (
|
||||
<div className="profile-viewer">
|
||||
<div className="profile-viewer__user">
|
||||
<Avatar
|
||||
imageSrc={!avatarMxc ? null : mx.mxcUrlToHttp(avatarMxc, 80, 80, 'crop')}
|
||||
text={username.slice(0, 1)}
|
||||
bgColor={colorMXID(userId)}
|
||||
size="large"
|
||||
/>
|
||||
<div className="profile-viewer__user__info">
|
||||
<Text variant="s1">{username}</Text>
|
||||
<Text variant="b2">{userId}</Text>
|
||||
</div>
|
||||
<div className="profile-viewer__user__role">
|
||||
<Text variant="b3">Role</Text>
|
||||
<Button iconSrc={ChevronBottomIC}>{getPowerLabel(member.powerLevel) || 'Member'}</Button>
|
||||
</div>
|
||||
</div>
|
||||
<SessionInfo userId={userId} />
|
||||
{ userId !== mx.getUserId() && (
|
||||
<ProfileFooter
|
||||
roomId={roomId}
|
||||
userId={userId}
|
||||
onRequestClose={() => setIsOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
className="profile-viewer__dialog"
|
||||
isOpen={isOpen}
|
||||
title={`${username} in ${room?.name ?? ''}`}
|
||||
onRequestClose={() => setIsOpen(false)}
|
||||
contentOptions={<IconButton src={CrossIC} onClick={() => setIsOpen(false)} tooltip="Close" />}
|
||||
>
|
||||
{isOpen && renderProfile()}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default ProfileViewer;
|
||||
89
src/app/organisms/profile-viewer/ProfileViewer.scss
Normal file
89
src/app/organisms/profile-viewer/ProfileViewer.scss
Normal file
@@ -0,0 +1,89 @@
|
||||
.profile-viewer__dialog {
|
||||
& .dialog__content__wrapper {
|
||||
position: relative;
|
||||
}
|
||||
& .dialog__content-container {
|
||||
padding: var(--sp-normal);
|
||||
padding-bottom: 89px;
|
||||
padding-right: var(--sp-extra-tight);
|
||||
[dir=rtl] & {
|
||||
padding-right: var(--sp-normal);
|
||||
padding-left: var(--sp-extra-tight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.profile-viewer {
|
||||
&__user {
|
||||
display: flex;
|
||||
padding-bottom: var(--sp-normal);
|
||||
border-bottom: 1px solid var(--bg-surface-border);
|
||||
|
||||
&__info {
|
||||
align-self: end;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
margin: 0 var(--sp-normal);
|
||||
|
||||
& .text-s1 {
|
||||
font-weight: 500;
|
||||
}
|
||||
& .text {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
}
|
||||
&__role {
|
||||
align-self: end;
|
||||
& > .text {
|
||||
margin-bottom: var(--sp-ultra-tight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
& .session-info {
|
||||
margin-top: var(--sp-normal);
|
||||
}
|
||||
|
||||
&__buttons {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
|
||||
width: 100%;
|
||||
padding: var(--sp-normal);
|
||||
background-color: var(--bg-surface);
|
||||
border-top: 1px solid var(--bg-surface-border);
|
||||
display: flex;
|
||||
|
||||
& > *:nth-child(2n) {
|
||||
margin: 0 var(--sp-normal)
|
||||
}
|
||||
& > *:last-child {
|
||||
margin-left: auto;
|
||||
[dir=rtl] & {
|
||||
margin-left: 0;
|
||||
margin-right: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.session-info {
|
||||
& .setting-tile__title .text {
|
||||
color: var(--tc-surface-high);
|
||||
}
|
||||
&__chips {
|
||||
padding-top: var(--sp-ultra-tight);
|
||||
& .chip {
|
||||
margin: {
|
||||
top: var(--sp-extra-tight);
|
||||
right: var(--sp-extra-tight);
|
||||
}
|
||||
[dir=rtl] & {
|
||||
margin: 0 0 var(--sp-extra-tight) var(--sp-extra-tight);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import React from 'react';
|
||||
|
||||
import ReadReceipts from '../read-receipts/ReadReceipts';
|
||||
import ProfileViewer from '../profile-viewer/ProfileViewer';
|
||||
|
||||
function Dialogs() {
|
||||
return (
|
||||
<>
|
||||
<ReadReceipts />
|
||||
<ProfileViewer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import PeopleSelector from '../../molecules/people-selector/PeopleSelector';
|
||||
import Dialog from '../../molecules/dialog/Dialog';
|
||||
|
||||
import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
|
||||
import { openProfileViewer } from '../../../client/action/navigation';
|
||||
|
||||
function ReadReceipts() {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
@@ -58,7 +59,10 @@ function ReadReceipts() {
|
||||
return (
|
||||
<PeopleSelector
|
||||
key={receipt.userId}
|
||||
onClick={() => alert('Viewing profile is yet to be implemented')}
|
||||
onClick={() => {
|
||||
setIsOpen(false);
|
||||
openProfileViewer(receipt.userId, roomId);
|
||||
}}
|
||||
avatarSrc={member?.getAvatarUrl(initMatrix.matrixClient.baseUrl, 24, 24, 'crop')}
|
||||
name={getUserDisplayName(receipt.userId)}
|
||||
color={colorMXID(receipt.userId)}
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, {
|
||||
useState, useEffect, useCallback, useRef,
|
||||
} from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './PeopleDrawer.scss';
|
||||
|
||||
import initMatrix from '../../../client/initMatrix';
|
||||
import { getUsernameOfRoomMember } from '../../../util/matrixUtil';
|
||||
import { getPowerLabel, getUsernameOfRoomMember } from '../../../util/matrixUtil';
|
||||
import colorMXID from '../../../util/colorMXID';
|
||||
import { openInviteUser } from '../../../client/action/navigation';
|
||||
import { openInviteUser, openProfileViewer } from '../../../client/action/navigation';
|
||||
import AsyncSearch from '../../../util/AsyncSearch';
|
||||
|
||||
import Text from '../../atoms/text/Text';
|
||||
import Header, { TitleWrapper } from '../../atoms/header/Header';
|
||||
import RawIcon from '../../atoms/system-icons/RawIcon';
|
||||
import IconButton from '../../atoms/button/IconButton';
|
||||
import Button from '../../atoms/button/Button';
|
||||
import ScrollView from '../../atoms/scroll/ScrollView';
|
||||
import Input from '../../atoms/input/Input';
|
||||
import SegmentedControl from '../../atoms/segmented-controls/SegmentedControls';
|
||||
import PeopleSelector from '../../molecules/people-selector/PeopleSelector';
|
||||
|
||||
import AddUserIC from '../../../../public/res/ic/outlined/add-user.svg';
|
||||
import SearchIC from '../../../../public/res/ic/outlined/search.svg';
|
||||
import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
|
||||
|
||||
function getPowerLabel(powerLevel) {
|
||||
if (powerLevel > 9000) return 'Goku';
|
||||
if (powerLevel > 100) return 'Founder';
|
||||
if (powerLevel === 100) return 'Admin';
|
||||
if (powerLevel >= 50) return 'Mod';
|
||||
return null;
|
||||
}
|
||||
function AtoZ(m1, m2) {
|
||||
const aName = m1.name;
|
||||
const bName = m2.name;
|
||||
@@ -44,31 +44,102 @@ function sortByPowerLevel(m1, m2) {
|
||||
if (pl1 < pl2) return 1;
|
||||
return 0;
|
||||
}
|
||||
function simplyfiMembers(members) {
|
||||
const mx = initMatrix.matrixClient;
|
||||
return members.map((member) => ({
|
||||
userId: member.userId,
|
||||
name: getUsernameOfRoomMember(member),
|
||||
username: member.userId.slice(1, member.userId.indexOf(':')),
|
||||
avatarSrc: member.getAvatarUrl(mx.baseUrl, 24, 24, 'crop'),
|
||||
peopleRole: getPowerLabel(member.powerLevel),
|
||||
powerLevel: members.powerLevel,
|
||||
}));
|
||||
}
|
||||
|
||||
const asyncSearch = new AsyncSearch();
|
||||
function PeopleDrawer({ roomId }) {
|
||||
const PER_PAGE_MEMBER = 50;
|
||||
const room = initMatrix.matrixClient.getRoom(roomId);
|
||||
const totalMemberList = room.getJoinedMembers().sort(AtoZ).sort(sortByPowerLevel);
|
||||
const [memberList, updateMemberList] = useState([]);
|
||||
const mx = initMatrix.matrixClient;
|
||||
const room = mx.getRoom(roomId);
|
||||
let isRoomChanged = false;
|
||||
|
||||
const [itemCount, setItemCount] = useState(PER_PAGE_MEMBER);
|
||||
const [membership, setMembership] = useState('join');
|
||||
const [memberList, setMemberList] = useState([]);
|
||||
const [searchedMembers, setSearchedMembers] = useState(null);
|
||||
const searchRef = useRef(null);
|
||||
|
||||
const getMembersWithMembership = useCallback(
|
||||
(mship) => room.getMembersWithMembership(mship),
|
||||
[roomId, membership],
|
||||
);
|
||||
|
||||
function loadMorePeople() {
|
||||
updateMemberList(totalMemberList.slice(0, memberList.length + PER_PAGE_MEMBER));
|
||||
setItemCount(itemCount + PER_PAGE_MEMBER);
|
||||
}
|
||||
|
||||
function handleSearchData(data) {
|
||||
// NOTICE: data is passed as object property
|
||||
// because react sucks at handling state update with array.
|
||||
setSearchedMembers({ data });
|
||||
setItemCount(PER_PAGE_MEMBER);
|
||||
}
|
||||
|
||||
function handleSearch(e) {
|
||||
const term = e.target.value;
|
||||
if (term === '' || term === undefined) {
|
||||
searchRef.current.value = '';
|
||||
searchRef.current.focus();
|
||||
setSearchedMembers(null);
|
||||
setItemCount(PER_PAGE_MEMBER);
|
||||
} else asyncSearch.search(term);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
updateMemberList(totalMemberList.slice(0, PER_PAGE_MEMBER));
|
||||
asyncSearch.setup(memberList, {
|
||||
keys: ['name', 'username', 'userId'],
|
||||
limit: PER_PAGE_MEMBER,
|
||||
});
|
||||
}, [memberList]);
|
||||
|
||||
useEffect(() => {
|
||||
let isGettingMembers = true;
|
||||
const updateMemberList = (event) => {
|
||||
if (isGettingMembers) return;
|
||||
console.log(event?.event?.room_id);
|
||||
if (event && event?.event?.room_id !== roomId) return;
|
||||
setMemberList(
|
||||
simplyfiMembers(
|
||||
getMembersWithMembership(membership)
|
||||
.sort(AtoZ).sort(sortByPowerLevel),
|
||||
),
|
||||
);
|
||||
};
|
||||
searchRef.current.value = '';
|
||||
updateMemberList();
|
||||
room.loadMembersIfNeeded().then(() => {
|
||||
isGettingMembers = false;
|
||||
if (isRoomChanged) return;
|
||||
const newTotalMemberList = room.getJoinedMembers().sort(AtoZ).sort(sortByPowerLevel);
|
||||
updateMemberList(newTotalMemberList.slice(0, PER_PAGE_MEMBER));
|
||||
updateMemberList();
|
||||
});
|
||||
|
||||
asyncSearch.on(asyncSearch.RESULT_SENT, handleSearchData);
|
||||
mx.on('RoomMember.membership', updateMemberList);
|
||||
return () => {
|
||||
isRoomChanged = true;
|
||||
setMemberList([]);
|
||||
setSearchedMembers(null);
|
||||
setItemCount(PER_PAGE_MEMBER);
|
||||
asyncSearch.removeListener(asyncSearch.RESULT_SENT, handleSearchData);
|
||||
mx.removeListener('RoomMember.membership', updateMemberList);
|
||||
};
|
||||
}, [roomId, membership]);
|
||||
|
||||
useEffect(() => {
|
||||
setMembership('join');
|
||||
}, [roomId]);
|
||||
|
||||
const mList = searchedMembers !== null ? searchedMembers.data : memberList.slice(0, itemCount);
|
||||
return (
|
||||
<div className="people-drawer">
|
||||
<Header>
|
||||
@@ -84,21 +155,53 @@ function PeopleDrawer({ roomId }) {
|
||||
<div className="people-drawer__scrollable">
|
||||
<ScrollView autoHide>
|
||||
<div className="people-drawer__content">
|
||||
<SegmentedControl
|
||||
selected={
|
||||
(() => {
|
||||
const getSegmentIndex = {
|
||||
join: 0,
|
||||
invite: 1,
|
||||
ban: 2,
|
||||
};
|
||||
return getSegmentIndex[membership];
|
||||
})()
|
||||
}
|
||||
segments={[{ text: 'Joined' }, { text: 'Invited' }, { text: 'Banned' }]}
|
||||
onSelect={(index) => {
|
||||
const selectSegment = [
|
||||
() => setMembership('join'),
|
||||
() => setMembership('invite'),
|
||||
() => setMembership('ban'),
|
||||
];
|
||||
selectSegment[index]?.();
|
||||
}}
|
||||
/>
|
||||
{
|
||||
memberList.map((member) => (
|
||||
mList.map((member) => (
|
||||
<PeopleSelector
|
||||
key={member.userId}
|
||||
onClick={() => alert('Viewing profile is yet to be implemented')}
|
||||
avatarSrc={member.getAvatarUrl(initMatrix.matrixClient.baseUrl, 24, 24, 'crop')}
|
||||
name={getUsernameOfRoomMember(member)}
|
||||
onClick={() => openProfileViewer(member.userId, roomId)}
|
||||
avatarSrc={member.avatarSrc}
|
||||
name={member.name}
|
||||
color={colorMXID(member.userId)}
|
||||
peopleRole={getPowerLabel(member.powerLevel)}
|
||||
peopleRole={member.peopleRole}
|
||||
/>
|
||||
))
|
||||
}
|
||||
{
|
||||
(searchedMembers?.data.length === 0 || memberList.length === 0)
|
||||
&& (
|
||||
<div className="people-drawer__noresult">
|
||||
<Text variant="b2">No result found!</Text>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<div className="people-drawer__load-more">
|
||||
{
|
||||
memberList.length !== totalMemberList.length && (
|
||||
mList.length !== 0
|
||||
&& memberList.length > itemCount
|
||||
&& searchedMembers === null
|
||||
&& (
|
||||
<Button onClick={loadMorePeople}>View more</Button>
|
||||
)
|
||||
}
|
||||
@@ -108,7 +211,12 @@ function PeopleDrawer({ roomId }) {
|
||||
</div>
|
||||
<div className="people-drawer__sticky">
|
||||
<form onSubmit={(e) => e.preventDefault()} className="people-search">
|
||||
<Input type="text" placeholder="Search" required />
|
||||
<RawIcon size="small" src={SearchIC} />
|
||||
<Input forwardRef={searchRef} type="text" onChange={handleSearch} placeholder="Search" required />
|
||||
{
|
||||
searchedMembers !== null
|
||||
&& <IconButton onClick={handleSearch} size="small" src={CrossIC} />
|
||||
}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -35,19 +35,48 @@
|
||||
@extend .people-drawer-flexItem;
|
||||
}
|
||||
|
||||
&__sticky {
|
||||
display: none;
|
||||
&__noresult {
|
||||
padding: var(--sp-extra-tight) var(--sp-normal);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
&__sticky {
|
||||
& .people-search {
|
||||
min-height: 48px;
|
||||
--search-input-height: 40px;
|
||||
min-height: var(--search-input-height);
|
||||
|
||||
margin: 0 var(--sp-normal);
|
||||
|
||||
position: relative;
|
||||
bottom: var(--sp-normal);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
& > .ic-raw,
|
||||
& > .ic-btn {
|
||||
position: absolute;
|
||||
z-index: 99;
|
||||
}
|
||||
& > .ic-raw {
|
||||
left: var(--sp-tight);
|
||||
[dir=rtl] & {
|
||||
right: var(--sp-tight);
|
||||
left: unset;
|
||||
}
|
||||
}
|
||||
& > .ic-btn {
|
||||
right: 2px;
|
||||
[dir=rtl] & {
|
||||
left: 2px;
|
||||
right: unset;
|
||||
}
|
||||
}
|
||||
& .input-container {
|
||||
flex: 1;
|
||||
}
|
||||
& .input {
|
||||
height: 48px;
|
||||
padding: 0 calc(var(--sp-loose) + var(--sp-normal));
|
||||
height: var(--search-input-height);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,7 +84,21 @@
|
||||
|
||||
.people-drawer__content {
|
||||
padding-top: var(--sp-extra-tight);
|
||||
padding-bottom: calc( var(--sp-extra-tight) + var(--sp-normal));
|
||||
padding-bottom: calc(2 * var(--sp-normal));
|
||||
|
||||
& .segmented-controls {
|
||||
display: flex;
|
||||
margin-bottom: var(--sp-extra-tight);
|
||||
margin-left: var(--sp-extra-tight);
|
||||
[dir=rtl] & {
|
||||
margin-left: unset;
|
||||
margin-right: var(--sp-extra-tight);
|
||||
}
|
||||
}
|
||||
& .segment-btn {
|
||||
flex: 1;
|
||||
padding: var(--sp-ultra-tight) 0;
|
||||
}
|
||||
}
|
||||
.people-drawer__load-more {
|
||||
padding: var(--sp-normal);
|
||||
|
||||
@@ -319,6 +319,7 @@ function RoomViewCmdBar({ roomId, roomTimeline, viewEvent }) {
|
||||
else if (searchTerm.match(/^[-]?(\()$/)) searchTerm = 'pleading_face';
|
||||
else if (searchTerm.match(/^[-]?(\$)$/)) searchTerm = 'money';
|
||||
else if (searchTerm.match(/^(<3)$/)) searchTerm = 'heart';
|
||||
else if (searchTerm.match(/^(c|ca|cat)$/)) searchTerm = '_cat';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,7 +344,7 @@ function RoomViewCmdBar({ roomId, roomTimeline, viewEvent }) {
|
||||
'>*': () => asyncSearch.setup(getRooms([...roomList.spaces]), { keys: ['name'], limit: 20 }),
|
||||
'>#': () => asyncSearch.setup(getRooms([...roomList.rooms]), { keys: ['name'], limit: 20 }),
|
||||
'>@': () => asyncSearch.setup(getRooms([...roomList.directs]), { keys: ['name'], limit: 20 }),
|
||||
':': () => asyncSearch.setup(emojis, { keys: ['shortcode'], limit: 20 }),
|
||||
':': () => asyncSearch.setup(emojis, { keys: ['shortcode'], isContain: true, limit: 20 }),
|
||||
'@': () => asyncSearch.setup(matrixClient.getRoom(roomId).getJoinedMembers().map((member) => ({
|
||||
name: member.name,
|
||||
userId: member.userId.slice(1),
|
||||
|
||||
@@ -11,7 +11,7 @@ import { redactEvent, sendReaction } from '../../../client/action/roomTimeline';
|
||||
import { getUsername, getUsernameOfRoomMember, doesRoomHaveUnread } from '../../../util/matrixUtil';
|
||||
import colorMXID from '../../../util/colorMXID';
|
||||
import { diffMinutes, isNotInSameDay, getEventCords } from '../../../util/common';
|
||||
import { openEmojiBoard, openReadReceipts } from '../../../client/action/navigation';
|
||||
import { openEmojiBoard, openProfileViewer, openReadReceipts } from '../../../client/action/navigation';
|
||||
|
||||
import Divider from '../../atoms/divider/Divider';
|
||||
import Avatar from '../../atoms/avatar/Avatar';
|
||||
@@ -353,12 +353,14 @@ function RoomViewContent({
|
||||
|
||||
const senderMXIDColor = colorMXID(mEvent.sender.userId);
|
||||
const userAvatar = isContentOnly ? null : (
|
||||
<Avatar
|
||||
imageSrc={mEvent.sender.getAvatarUrl(initMatrix.matrixClient.baseUrl, 36, 36, 'crop')}
|
||||
text={getUsernameOfRoomMember(mEvent.sender).slice(0, 1)}
|
||||
bgColor={senderMXIDColor}
|
||||
size="small"
|
||||
/>
|
||||
<button type="button" onClick={() => openProfileViewer(mEvent.sender.userId, roomId)}>
|
||||
<Avatar
|
||||
imageSrc={mEvent.sender.getAvatarUrl(initMatrix.matrixClient.baseUrl, 36, 36, 'crop')}
|
||||
text={getUsernameOfRoomMember(mEvent.sender).slice(0, 1)}
|
||||
bgColor={senderMXIDColor}
|
||||
size="small"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
const userHeader = isContentOnly ? null : (
|
||||
<MessageHeader
|
||||
|
||||
@@ -29,7 +29,7 @@ import MarkdownIC from '../../../../public/res/ic/outlined/markdown.svg';
|
||||
import FileIC from '../../../../public/res/ic/outlined/file.svg';
|
||||
import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
|
||||
|
||||
const CMD_REGEX = /(\/|>[#*@]|:|@)(\S*)$/;
|
||||
const CMD_REGEX = /(^\/|^>[#*@]|:|@)(\S*)$/;
|
||||
let isTyping = false;
|
||||
let isCmdActivated = false;
|
||||
let cmdCursorPos = null;
|
||||
@@ -313,6 +313,7 @@ function RoomViewInput({
|
||||
|
||||
function addEmoji(emoji) {
|
||||
textAreaRef.current.value += emoji.unicode;
|
||||
textAreaRef.current.focus();
|
||||
}
|
||||
|
||||
function handleUploadClick() {
|
||||
@@ -327,8 +328,7 @@ function RoomViewInput({
|
||||
if (file !== null) roomsInput.setAttachment(roomId, file);
|
||||
}
|
||||
|
||||
const myPowerlevel = roomTimeline.room.getMember(mx.getUserId()).powerLevel;
|
||||
const canISend = roomTimeline.room.currentState.hasSufficientPowerLevelFor('events_default', myPowerlevel);
|
||||
const canISend = roomTimeline.room.currentState.maySendMessage(mx.getUserId());
|
||||
|
||||
function renderInputs() {
|
||||
if (!canISend) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import PropTypes from 'prop-types';
|
||||
import './Settings.scss';
|
||||
|
||||
import initMatrix from '../../../client/initMatrix';
|
||||
import cons from '../../../client/state/cons';
|
||||
import settings from '../../../client/state/settings';
|
||||
import { toggleMarkdown } from '../../../client/action/settings';
|
||||
|
||||
@@ -104,13 +105,13 @@ function AboutSection() {
|
||||
<div>
|
||||
<Text variant="h2">
|
||||
Cinny
|
||||
<span className="text text-b3" style={{ margin: '0 var(--sp-extra-tight)' }}>v1.3.2</span>
|
||||
<span className="text text-b3" style={{ margin: '0 var(--sp-extra-tight)' }}>{`v${cons.version}`}</span>
|
||||
</Text>
|
||||
<Text>Yet another matrix client</Text>
|
||||
|
||||
<div className="set-about__btns">
|
||||
<Button onClick={() => window.open('https://github.com/ajbura/cinny')}>Source code</Button>
|
||||
<Button onClick={() => window.open('https://liberapay.com/ajbura/donate')}>Support</Button>
|
||||
<Button onClick={() => window.open('https://cinny.in/#sponsor')}>Support</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
BrowserRouter, Switch, Route, Redirect,
|
||||
BrowserRouter,
|
||||
} from 'react-router-dom';
|
||||
|
||||
import { isAuthenticated } from '../../client/state/auth';
|
||||
@@ -11,17 +11,7 @@ import Client from '../templates/client/Client';
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Switch>
|
||||
<Route exact path="/">
|
||||
{ isAuthenticated() ? <Client /> : <Redirect to="/login" />}
|
||||
</Route>
|
||||
<Route path="/login">
|
||||
{ isAuthenticated() ? <Redirect to="/" /> : <Auth type="login" />}
|
||||
</Route>
|
||||
<Route path="/register">
|
||||
{ isAuthenticated() ? <Redirect to="/" /> : <Auth type="register" />}
|
||||
</Route>
|
||||
</Switch>
|
||||
{ isAuthenticated() ? <Client /> : <Auth />}
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import React, { useState, useRef } from 'react';
|
||||
/* eslint-disable react/prop-types */
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import './Auth.scss';
|
||||
import ReCAPTCHA from 'react-google-recaptcha';
|
||||
import { Formik } from 'formik';
|
||||
|
||||
import { Link } from 'react-router-dom';
|
||||
import * as auth from '../../../client/action/auth';
|
||||
import cons from '../../../client/state/cons';
|
||||
import { Debounce, getUrlPrams } from '../../../util/common';
|
||||
import { getBaseUrl } from '../../../util/matrixUtil';
|
||||
|
||||
import Text from '../../atoms/text/Text';
|
||||
import Button from '../../atoms/button/Button';
|
||||
@@ -12,320 +16,556 @@ import IconButton from '../../atoms/button/IconButton';
|
||||
import Input from '../../atoms/input/Input';
|
||||
import Spinner from '../../atoms/spinner/Spinner';
|
||||
import ScrollView from '../../atoms/scroll/ScrollView';
|
||||
import Header, { TitleWrapper } from '../../atoms/header/Header';
|
||||
import Avatar from '../../atoms/avatar/Avatar';
|
||||
import ContextMenu, { MenuItem, MenuHeader } from '../../atoms/context-menu/ContextMenu';
|
||||
|
||||
import EyeIC from '../../../../public/res/ic/outlined/eye.svg';
|
||||
import ChevronBottomIC from '../../../../public/res/ic/outlined/chevron-bottom.svg';
|
||||
import CinnySvg from '../../../../public/res/svg/cinny.svg';
|
||||
import SSOButtons from '../../molecules/sso-buttons/SSOButtons';
|
||||
|
||||
// This regex validates historical usernames, which don't satisfy today's username requirements.
|
||||
// See https://matrix.org/docs/spec/appendices#id13 for more info.
|
||||
const LOCALPART_LOGIN_REGEX = /.*/;
|
||||
const LOCALPART_SIGNUP_REGEX = /^[a-z0-9_\-.=/]+$/;
|
||||
const BAD_LOCALPART_ERROR = 'Username must contain only a-z, 0-9, ., _, =, -, and /.';
|
||||
const BAD_LOCALPART_ERROR = 'Username can only contain characters a-z, 0-9, or \'=_-./\'';
|
||||
const USER_ID_TOO_LONG_ERROR = 'Your user ID, including the hostname, can\'t be more than 255 characters long.';
|
||||
|
||||
const PASSWORD_REGEX = /.+/;
|
||||
const PASSWORD_STRENGHT_REGEX = /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\d\s:])([^\s]){8,127}$/;
|
||||
const BAD_PASSWORD_ERROR = 'Password must contain at least 1 number, 1 uppercase letter, 1 lowercase letter, 1 non-alphanumeric character. Passwords can range from 8-127 characters with no whitespaces.';
|
||||
const BAD_PASSWORD_ERROR = 'Password must contain at least 1 lowercase, 1 uppercase, 1 number, 1 non-alphanumeric character, 8-127 characters with no space.';
|
||||
const CONFIRM_PASSWORD_ERROR = 'Passwords don\'t match.';
|
||||
|
||||
const EMAIL_REGEX = /([a-z0-9]+[_a-z0-9.-][a-z0-9]+)@([a-z0-9-]+(?:.[a-z0-9-]+).[a-z]{2,4})/;
|
||||
const EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
|
||||
const BAD_EMAIL_ERROR = 'Invalid email address';
|
||||
|
||||
function isValidInput(value, regex) {
|
||||
if (typeof regex === 'string') return regex === value;
|
||||
return regex.test(value);
|
||||
}
|
||||
function renderErrorMessage(error) {
|
||||
const $error = document.getElementById('auth_error');
|
||||
$error.textContent = error;
|
||||
$error.style.display = 'block';
|
||||
}
|
||||
function showBadInputError($input, error, stopAutoFocus) {
|
||||
renderErrorMessage(error);
|
||||
if (!stopAutoFocus) $input.focus();
|
||||
const myInput = $input;
|
||||
myInput.style.border = '1px solid var(--bg-danger)';
|
||||
myInput.style.boxShadow = 'none';
|
||||
document.getElementById('auth_submit-btn').disabled = true;
|
||||
}
|
||||
|
||||
function validateOnChange(targetInput, regex, error, stopAutoFocus) {
|
||||
if (!isValidInput(targetInput.value, regex) && targetInput.value) {
|
||||
showBadInputError(targetInput, error, stopAutoFocus);
|
||||
return false;
|
||||
}
|
||||
document.getElementById('auth_error').style.display = 'none';
|
||||
targetInput.style.removeProperty('border');
|
||||
targetInput.style.removeProperty('box-shadow');
|
||||
document.getElementById('auth_submit-btn').disabled = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a username into a standard format.
|
||||
*
|
||||
* Removes leading and trailing whitespaces and leading "@" symbols.
|
||||
* @param {string} rawUsername A raw-input username, which may include invalid characters.
|
||||
* @returns {string}
|
||||
*/
|
||||
function normalizeUsername(rawUsername) {
|
||||
const noLeadingAt = rawUsername.indexOf('@') === 0 ? rawUsername.substr(1) : rawUsername;
|
||||
return noLeadingAt.trim();
|
||||
}
|
||||
|
||||
function Auth({ type }) {
|
||||
const [process, changeProcess] = useState(null);
|
||||
const usernameRef = useRef(null);
|
||||
const homeserverRef = useRef(null);
|
||||
const passwordRef = useRef(null);
|
||||
const confirmPasswordRef = useRef(null);
|
||||
const emailRef = useRef(null);
|
||||
let searchingHs = null;
|
||||
function Homeserver({ onChange }) {
|
||||
const [hs, setHs] = useState(null);
|
||||
const [debounce] = useState(new Debounce());
|
||||
const [process, setProcess] = useState({ isLoading: true, message: 'Loading homeserver list...' });
|
||||
const hsRef = useRef();
|
||||
|
||||
function register(recaptchaValue, terms, verified) {
|
||||
auth.register(
|
||||
usernameRef.current.value,
|
||||
homeserverRef.current.value,
|
||||
passwordRef.current.value,
|
||||
emailRef.current.value,
|
||||
recaptchaValue,
|
||||
terms,
|
||||
verified,
|
||||
).then((res) => {
|
||||
document.getElementById('auth_submit-btn').disabled = false;
|
||||
if (res.type === 'recaptcha') {
|
||||
changeProcess({ type: res.type, sitekey: res.public_key });
|
||||
return;
|
||||
}
|
||||
if (res.type === 'terms') {
|
||||
changeProcess({ type: res.type, en: res.en });
|
||||
}
|
||||
if (res.type === 'email') {
|
||||
changeProcess({ type: res.type });
|
||||
}
|
||||
if (res.type === 'done') {
|
||||
window.location.replace('/');
|
||||
}
|
||||
}).catch((error) => {
|
||||
changeProcess(null);
|
||||
renderErrorMessage(error);
|
||||
document.getElementById('auth_submit-btn').disabled = false;
|
||||
});
|
||||
if (terms) {
|
||||
changeProcess({ type: 'loading', message: 'Sending email verification link...' });
|
||||
} else changeProcess({ type: 'loading', message: 'Registration in progress...' });
|
||||
}
|
||||
const setupHsConfig = async (servername) => {
|
||||
setProcess({ isLoading: true, message: 'Looking for homeserver...' });
|
||||
let baseUrl = null;
|
||||
try {
|
||||
baseUrl = await getBaseUrl(servername);
|
||||
} catch (e) {
|
||||
baseUrl = e.message;
|
||||
}
|
||||
if (searchingHs !== servername) return;
|
||||
setProcess({ isLoading: true, message: `Connecting to ${baseUrl}...` });
|
||||
const tempClient = auth.createTemporaryClient(baseUrl);
|
||||
|
||||
function handleLogin(e) {
|
||||
e.preventDefault();
|
||||
document.getElementById('auth_submit-btn').disabled = true;
|
||||
document.getElementById('auth_error').style.display = 'none';
|
||||
Promise.allSettled([tempClient.loginFlows(), tempClient.register()])
|
||||
.then((values) => {
|
||||
const loginFlow = values[0].status === 'fulfilled' ? values[0]?.value : undefined;
|
||||
const registerFlow = values[1].status === 'rejected' ? values[1]?.reason?.data : undefined;
|
||||
if (loginFlow === undefined || registerFlow === undefined) throw new Error();
|
||||
|
||||
/** @type {string} */
|
||||
const rawUsername = usernameRef.current.value;
|
||||
/** @type {string} */
|
||||
const normalizedUsername = normalizeUsername(rawUsername);
|
||||
|
||||
auth.login(normalizedUsername, homeserverRef.current.value, passwordRef.current.value)
|
||||
.then(() => {
|
||||
document.getElementById('auth_submit-btn').disabled = false;
|
||||
window.location.replace('/');
|
||||
})
|
||||
.catch((error) => {
|
||||
changeProcess(null);
|
||||
renderErrorMessage(error);
|
||||
document.getElementById('auth_submit-btn').disabled = false;
|
||||
if (searchingHs !== servername) return;
|
||||
onChange({ baseUrl, login: loginFlow, register: registerFlow });
|
||||
setProcess({ isLoading: false });
|
||||
}).catch(() => {
|
||||
if (searchingHs !== servername) return;
|
||||
onChange(null);
|
||||
setProcess({ isLoading: false, error: 'Unable to connect. Please check your input.' });
|
||||
});
|
||||
changeProcess({ type: 'loading', message: 'Login in progress...' });
|
||||
}
|
||||
};
|
||||
|
||||
function handleRegister(e) {
|
||||
e.preventDefault();
|
||||
document.getElementById('auth_submit-btn').disabled = true;
|
||||
document.getElementById('auth_error').style.display = 'none';
|
||||
useEffect(() => {
|
||||
onChange(null);
|
||||
if (hs === null || hs?.selected.trim() === '') return;
|
||||
searchingHs = hs.selected;
|
||||
setupHsConfig(hs.selected);
|
||||
}, [hs]);
|
||||
|
||||
if (!isValidInput(usernameRef.current.value, LOCALPART_SIGNUP_REGEX)) {
|
||||
showBadInputError(usernameRef.current, BAD_LOCALPART_ERROR);
|
||||
return;
|
||||
useEffect(async () => {
|
||||
const link = window.location.href;
|
||||
const configFileUrl = `${link}${link[link.length - 1] === '/' ? '' : '/'}config.json`;
|
||||
try {
|
||||
const result = await (await fetch(configFileUrl, { method: 'GET' })).json();
|
||||
const selectedHs = result?.defaultHomeserver;
|
||||
const hsList = result?.homeserverList;
|
||||
if (!hsList?.length > 0 || selectedHs < 0 || selectedHs >= hsList?.length) {
|
||||
throw new Error();
|
||||
}
|
||||
setHs({ selected: hsList[selectedHs], list: hsList });
|
||||
} catch {
|
||||
setHs({ selected: 'matrix.org', list: ['matrix.org'] });
|
||||
}
|
||||
if (!isValidInput(passwordRef.current.value, PASSWORD_STRENGHT_REGEX)) {
|
||||
showBadInputError(passwordRef.current, BAD_PASSWORD_ERROR);
|
||||
return;
|
||||
}
|
||||
if (passwordRef.current.value !== confirmPasswordRef.current.value) {
|
||||
showBadInputError(confirmPasswordRef.current, CONFIRM_PASSWORD_ERROR);
|
||||
return;
|
||||
}
|
||||
if (!isValidInput(emailRef.current.value, EMAIL_REGEX)) {
|
||||
showBadInputError(emailRef.current, BAD_EMAIL_ERROR);
|
||||
return;
|
||||
}
|
||||
if (`@${usernameRef.current.value}:${homeserverRef.current.value}`.length > 255) {
|
||||
showBadInputError(usernameRef.current, USER_ID_TOO_LONG_ERROR);
|
||||
return;
|
||||
}
|
||||
register();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleHsInput = (e) => {
|
||||
const { value } = e.target;
|
||||
setProcess({ isLoading: false });
|
||||
debounce._(async () => {
|
||||
setHs({ selected: value, list: hs.list });
|
||||
}, 700)();
|
||||
};
|
||||
|
||||
const handleAuth = (type === 'login') ? handleLogin : handleRegister;
|
||||
return (
|
||||
<>
|
||||
{process?.type === 'loading' && <LoadingScreen message={process.message} />}
|
||||
{process?.type === 'recaptcha' && <Recaptcha message="Please check the box below to proceed." sitekey={process.sitekey} onChange={(v) => { if (typeof v === 'string') register(v); }} />}
|
||||
{process?.type === 'terms' && <Terms url={process.en.url} onSubmit={register} />}
|
||||
{process?.type === 'email' && (
|
||||
<ProcessWrapper>
|
||||
<div style={{ margin: 'var(--sp-normal)', maxWidth: '450px' }}>
|
||||
<Text variant="h2">Verify email</Text>
|
||||
<div style={{ margin: 'var(--sp-normal) 0' }}>
|
||||
<Text variant="b1">
|
||||
Please check your email
|
||||
{' '}
|
||||
<b>{`(${emailRef.current.value})`}</b>
|
||||
{' '}
|
||||
and validate before continuing further.
|
||||
</Text>
|
||||
</div>
|
||||
<Button variant="primary" onClick={() => register(undefined, undefined, true)}>Continue</Button>
|
||||
</div>
|
||||
</ProcessWrapper>
|
||||
)}
|
||||
<StaticWrapper>
|
||||
<div className="auth-form__wrapper flex-v--center">
|
||||
<form onSubmit={handleAuth} className="auth-form">
|
||||
<Text variant="h2">{ type === 'login' ? 'Login' : 'Register' }</Text>
|
||||
<div className="username__wrapper">
|
||||
<Input
|
||||
forwardRef={usernameRef}
|
||||
onChange={(e) => (type === 'login'
|
||||
? validateOnChange(e.target, LOCALPART_LOGIN_REGEX, BAD_LOCALPART_ERROR)
|
||||
: validateOnChange(e.target, LOCALPART_SIGNUP_REGEX, BAD_LOCALPART_ERROR))}
|
||||
id="auth_username"
|
||||
label="Username"
|
||||
required
|
||||
/>
|
||||
<Input
|
||||
forwardRef={homeserverRef}
|
||||
id="auth_homeserver"
|
||||
placeholder="Homeserver"
|
||||
value="matrix.org"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="password__wrapper">
|
||||
<Input
|
||||
forwardRef={passwordRef}
|
||||
onChange={(e) => {
|
||||
const isValidPass = validateOnChange(e.target, ((type === 'login') ? PASSWORD_REGEX : PASSWORD_STRENGHT_REGEX), BAD_PASSWORD_ERROR);
|
||||
if (type === 'register' && isValidPass) {
|
||||
validateOnChange(
|
||||
confirmPasswordRef.current, passwordRef.current.value,
|
||||
CONFIRM_PASSWORD_ERROR, true,
|
||||
);
|
||||
}
|
||||
}}
|
||||
id="auth_password"
|
||||
type="password"
|
||||
label="Password"
|
||||
required
|
||||
/>
|
||||
<IconButton
|
||||
onClick={() => {
|
||||
if (passwordRef.current.type === 'password') {
|
||||
passwordRef.current.type = 'text';
|
||||
} else passwordRef.current.type = 'password';
|
||||
}}
|
||||
size="extra-small"
|
||||
src={EyeIC}
|
||||
/>
|
||||
</div>
|
||||
{type === 'register' && (
|
||||
<>
|
||||
<div className="password__wrapper">
|
||||
<Input
|
||||
forwardRef={confirmPasswordRef}
|
||||
onChange={(e) => {
|
||||
validateOnChange(e.target, passwordRef.current.value, CONFIRM_PASSWORD_ERROR);
|
||||
}}
|
||||
id="auth_confirmPassword"
|
||||
type="password"
|
||||
label="Confirm password"
|
||||
required
|
||||
/>
|
||||
<IconButton
|
||||
<div className="homeserver-form">
|
||||
<Input name="homeserver" onChange={handleHsInput} value={hs?.selected} forwardRef={hsRef} label="Homeserver" />
|
||||
<ContextMenu
|
||||
placement="right"
|
||||
content={(hideMenu) => (
|
||||
<>
|
||||
<MenuHeader>Homeserver list</MenuHeader>
|
||||
{
|
||||
hs?.list.map((hsName) => (
|
||||
<MenuItem
|
||||
key={hsName}
|
||||
onClick={() => {
|
||||
if (confirmPasswordRef.current.type === 'password') {
|
||||
confirmPasswordRef.current.type = 'text';
|
||||
} else confirmPasswordRef.current.type = 'password';
|
||||
hideMenu();
|
||||
hsRef.current.value = hsName;
|
||||
setHs({ selected: hsName, list: hs.list });
|
||||
}}
|
||||
size="extra-small"
|
||||
src={EyeIC}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
forwardRef={emailRef}
|
||||
onChange={(e) => validateOnChange(e.target, EMAIL_REGEX, BAD_EMAIL_ERROR)}
|
||||
id="auth_email"
|
||||
type="email"
|
||||
label="Email"
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<div className="submit-btn__wrapper flex--end">
|
||||
<Text id="auth_error" className="error-message" variant="b3">Error</Text>
|
||||
<Button
|
||||
id="auth_submit-btn"
|
||||
variant="primary"
|
||||
type="submit"
|
||||
>
|
||||
{type === 'login' ? 'Login' : 'Register' }
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
>
|
||||
{hsName}
|
||||
</MenuItem>
|
||||
))
|
||||
}
|
||||
</>
|
||||
)}
|
||||
render={(toggleMenu) => <IconButton onClick={toggleMenu} src={ChevronBottomIC} />}
|
||||
/>
|
||||
</div>
|
||||
{process.error !== undefined && <Text className="homeserver-form__error" variant="b3">{process.error}</Text>}
|
||||
{process.isLoading && (
|
||||
<div className="homeserver-form__status flex--center">
|
||||
<Spinner size="small" />
|
||||
<Text variant="b2">{process.message}</Text>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Homeserver.propTypes = {
|
||||
onChange: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
<div className="flex--center">
|
||||
<Text variant="b2">
|
||||
{`${(type === 'login' ? 'Don\'t have' : 'Already have')} an account?`}
|
||||
<Link to={type === 'login' ? '/register' : '/login'}>
|
||||
{ type === 'login' ? ' Register' : ' Login' }
|
||||
</Link>
|
||||
</Text>
|
||||
</div>
|
||||
</StaticWrapper>
|
||||
function Login({ loginFlow, baseUrl }) {
|
||||
const [typeIndex, setTypeIndex] = useState(0);
|
||||
const loginTypes = ['Username', 'Email'];
|
||||
const isPassword = loginFlow?.filter((flow) => flow.type === 'm.login.password')[0];
|
||||
const ssoProviders = loginFlow?.filter((flow) => flow.type.match(/^m.login.(sso|cas)$/))[0];
|
||||
|
||||
const initialValues = {
|
||||
username: '', password: '', email: '', other: '',
|
||||
};
|
||||
|
||||
const validator = (values) => {
|
||||
const errors = {};
|
||||
if (typeIndex === 0 && values.username.length > 0 && values.username.indexOf(':') > -1) {
|
||||
errors.username = 'Username must contain local-part only';
|
||||
}
|
||||
if (typeIndex === 1 && values.email.length > 0 && !isValidInput(values.email, EMAIL_REGEX)) {
|
||||
errors.email = BAD_EMAIL_ERROR;
|
||||
}
|
||||
return errors;
|
||||
};
|
||||
const submitter = (values, actions) => auth.login(
|
||||
baseUrl,
|
||||
typeIndex === 0 ? normalizeUsername(values.username) : undefined,
|
||||
typeIndex === 1 ? values.email : undefined,
|
||||
values.password,
|
||||
).then(() => {
|
||||
actions.setSubmitting(true);
|
||||
window.location.reload();
|
||||
}).catch((error) => {
|
||||
let msg = error.message;
|
||||
if (msg === 'Unknown message') msg = 'Please check your credentials';
|
||||
actions.setErrors({
|
||||
password: msg === 'Invalid password' ? msg : undefined,
|
||||
other: msg !== 'Invalid password' ? msg : undefined,
|
||||
});
|
||||
actions.setSubmitting(false);
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="auth-form__heading">
|
||||
<Text variant="h2">Login</Text>
|
||||
{isPassword && (
|
||||
<ContextMenu
|
||||
placement="right"
|
||||
content={(hideMenu) => (
|
||||
loginTypes.map((type, index) => (
|
||||
<MenuItem
|
||||
key={type}
|
||||
onClick={() => {
|
||||
hideMenu();
|
||||
setTypeIndex(index);
|
||||
}}
|
||||
>
|
||||
{type}
|
||||
</MenuItem>
|
||||
))
|
||||
)}
|
||||
render={(toggleMenu) => (
|
||||
<Button onClick={toggleMenu} iconSrc={ChevronBottomIC}>
|
||||
{loginTypes[typeIndex]}
|
||||
</Button>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{isPassword && (
|
||||
<Formik
|
||||
initialValues={initialValues}
|
||||
onSubmit={submitter}
|
||||
validate={validator}
|
||||
>
|
||||
{({
|
||||
values, errors, handleChange, handleSubmit, isSubmitting,
|
||||
}) => (
|
||||
<>
|
||||
{isSubmitting && <LoadingScreen message="Login in progress..." />}
|
||||
<form className="auth-form" onSubmit={handleSubmit}>
|
||||
{typeIndex === 0 && <Input values={values.username} name="username" onChange={handleChange} label="Username" type="username" required />}
|
||||
{errors.username && <Text className="auth-form__error" variant="b3">{errors.username}</Text>}
|
||||
{typeIndex === 1 && <Input values={values.email} name="email" onChange={handleChange} label="Email" type="email" required />}
|
||||
{errors.email && <Text className="auth-form__error" variant="b3">{errors.email}</Text>}
|
||||
<Input values={values.password} name="password" onChange={handleChange} label="Password" type="password" required />
|
||||
{errors.password && <Text className="auth-form__error" variant="b3">{errors.password}</Text>}
|
||||
{errors.other && <Text className="auth-form__error" variant="b3">{errors.other}</Text>}
|
||||
<div className="auth-form__btns">
|
||||
<Button variant="primary" type="submit" disabled={isSubmitting}>Login</Button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</Formik>
|
||||
)}
|
||||
{ssoProviders && isPassword && <Text className="sso__divider">OR</Text>}
|
||||
{ssoProviders && (
|
||||
<SSOButtons
|
||||
type={ssoProviders.type.match(/^m.login.(sso|cas)$/)[1]}
|
||||
identityProviders={ssoProviders.identity_providers}
|
||||
baseUrl={baseUrl}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Login.propTypes = {
|
||||
loginFlow: PropTypes.arrayOf(
|
||||
PropTypes.shape({}),
|
||||
).isRequired,
|
||||
baseUrl: PropTypes.string.isRequired,
|
||||
};
|
||||
|
||||
let sid;
|
||||
let clientSecret;
|
||||
function Register({ registerInfo, loginFlow, baseUrl }) {
|
||||
const [process, setProcess] = useState({});
|
||||
const formRef = useRef();
|
||||
|
||||
const ssoProviders = loginFlow?.filter((flow) => flow.type.match(/^m.login.(sso|cas)$/))[0];
|
||||
const isDisabled = registerInfo.errcode !== undefined;
|
||||
const { flows, params, session } = registerInfo;
|
||||
|
||||
let isEmail = false;
|
||||
let isEmailRequired = true;
|
||||
let isRecaptcha = false;
|
||||
let isTerms = false;
|
||||
let isDummy = false;
|
||||
|
||||
flows?.forEach((flow) => {
|
||||
if (isEmailRequired && flow.stages.indexOf('m.login.email.identity') === -1) isEmailRequired = false;
|
||||
if (!isEmail) isEmail = flow.stages.indexOf('m.login.email.identity') > -1;
|
||||
if (!isRecaptcha) isRecaptcha = flow.stages.indexOf('m.login.recaptcha') > -1;
|
||||
if (!isTerms) isTerms = flow.stages.indexOf('m.login.terms') > -1;
|
||||
if (!isDummy) isDummy = flow.stages.indexOf('m.login.dummy') > -1;
|
||||
});
|
||||
|
||||
const initialValues = {
|
||||
username: '', password: '', confirmPassword: '', email: '', other: '',
|
||||
};
|
||||
|
||||
const validator = (values) => {
|
||||
const errors = {};
|
||||
if (values.username.list > 255) errors.username = USER_ID_TOO_LONG_ERROR;
|
||||
if (values.username.length > 0 && !isValidInput(values.username, LOCALPART_SIGNUP_REGEX)) {
|
||||
errors.username = BAD_LOCALPART_ERROR;
|
||||
}
|
||||
if (values.password.length > 0 && !isValidInput(values.password, PASSWORD_STRENGHT_REGEX)) {
|
||||
errors.password = BAD_PASSWORD_ERROR;
|
||||
}
|
||||
if (values.confirmPassword.length > 0
|
||||
&& !isValidInput(values.confirmPassword, values.password)) {
|
||||
errors.confirmPassword = CONFIRM_PASSWORD_ERROR;
|
||||
}
|
||||
if (values.email.length > 0 && !isValidInput(values.email, EMAIL_REGEX)) {
|
||||
errors.email = BAD_EMAIL_ERROR;
|
||||
}
|
||||
return errors;
|
||||
};
|
||||
const submitter = (values, actions) => {
|
||||
const tempClient = auth.createTemporaryClient(baseUrl);
|
||||
clientSecret = tempClient.generateClientSecret();
|
||||
return tempClient.isUsernameAvailable(values.username)
|
||||
.then(async (isAvail) => {
|
||||
if (!isAvail) {
|
||||
actions.setErrors({ username: 'Username is already taken' });
|
||||
actions.setSubmitting(false);
|
||||
}
|
||||
if (isEmail && values.email.length > 0) {
|
||||
const result = await auth.verifyEmail(baseUrl, values.email, clientSecret, 1);
|
||||
if (result.errcode) {
|
||||
if (result.errcode === 'M_THREEPID_IN_USE') actions.setErrors({ email: result.error });
|
||||
else actions.setErrors({ others: result.error || result.message });
|
||||
actions.setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
sid = result.sid;
|
||||
}
|
||||
setProcess({ type: 'processing', message: 'Registration in progress....' });
|
||||
actions.setSubmitting(false);
|
||||
}).catch((err) => {
|
||||
const msg = err.message || err.error;
|
||||
if (['M_USER_IN_USE', 'M_INVALID_USERNAME', 'M_EXCLUSIVE'].indexOf(err.errcode) > 0) {
|
||||
actions.setErrors({ username: err.errCode === 'M_USER_IN_USE' ? 'Username is already taken' : msg });
|
||||
} else if (msg) actions.setErrors({ other: msg });
|
||||
|
||||
actions.setSubmitting(false);
|
||||
});
|
||||
};
|
||||
|
||||
const refreshWindow = () => window.location.reload();
|
||||
|
||||
const getInputs = () => {
|
||||
const f = formRef.current;
|
||||
return [f.username.value, f.password.value, f?.email?.value];
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (process.type !== 'processing') return;
|
||||
const asyncProcess = async () => {
|
||||
const [username, password, email] = getInputs();
|
||||
const d = await auth.completeRegisterStage(baseUrl, username, password, { session });
|
||||
|
||||
if (isRecaptcha && !d.completed.includes('m.login.recaptcha')) {
|
||||
const sitekey = params['m.login.recaptcha'].public_key;
|
||||
setProcess({ type: 'm.login.recaptcha', sitekey });
|
||||
return;
|
||||
}
|
||||
if (isTerms && !d.completed.includes('m.login.terms')) {
|
||||
const pp = params['m.login.terms'].policies.privacy_policy;
|
||||
const url = pp?.en.url || pp[Object.keys(pp)[0]].url;
|
||||
setProcess({ type: 'm.login.terms', url });
|
||||
return;
|
||||
}
|
||||
if (isEmail && email.length > 0) {
|
||||
setProcess({ type: 'm.login.email.identity', email });
|
||||
return;
|
||||
}
|
||||
if (isDummy) {
|
||||
const data = await auth.completeRegisterStage(baseUrl, username, password, {
|
||||
type: 'm.login.dummy',
|
||||
session,
|
||||
});
|
||||
if (data.done) refreshWindow();
|
||||
}
|
||||
};
|
||||
asyncProcess();
|
||||
}, [process]);
|
||||
|
||||
const handleRecaptcha = async (value) => {
|
||||
if (typeof value !== 'string') return;
|
||||
const [username, password] = getInputs();
|
||||
const d = await auth.completeRegisterStage(baseUrl, username, password, {
|
||||
type: 'm.login.recaptcha',
|
||||
response: value,
|
||||
session,
|
||||
});
|
||||
if (d.done) refreshWindow();
|
||||
else setProcess({ type: 'processing', message: 'Registration in progress...' });
|
||||
};
|
||||
const handleTerms = async () => {
|
||||
const [username, password] = getInputs();
|
||||
const d = await auth.completeRegisterStage(baseUrl, username, password, {
|
||||
type: 'm.login.terms',
|
||||
session,
|
||||
});
|
||||
if (d.done) refreshWindow();
|
||||
else setProcess({ type: 'processing', message: 'Registration in progress...' });
|
||||
};
|
||||
const handleEmailVerify = async () => {
|
||||
const [username, password] = getInputs();
|
||||
const d = await auth.completeRegisterStage(baseUrl, username, password, {
|
||||
type: 'm.login.email.identity',
|
||||
threepidCreds: { sid, client_secret: clientSecret },
|
||||
threepid_creds: { sid, client_secret: clientSecret },
|
||||
session,
|
||||
});
|
||||
if (d.done) refreshWindow();
|
||||
else setProcess({ type: 'processing', message: 'Registration in progress...' });
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{process.type === 'processing' && <LoadingScreen message={process.message} />}
|
||||
{process.type === 'm.login.recaptcha' && <Recaptcha message="Please check the box below to proceed." sitekey={process.sitekey} onChange={handleRecaptcha} />}
|
||||
{process.type === 'm.login.terms' && <Terms url={process.url} onSubmit={handleTerms} />}
|
||||
{process.type === 'm.login.email.identity' && <EmailVerify email={process.email} onContinue={handleEmailVerify} />}
|
||||
<div className="auth-form__heading">
|
||||
{!isDisabled && <Text variant="h2">Register</Text>}
|
||||
{isDisabled && <Text className="auth-form__error">{registerInfo.error}</Text>}
|
||||
</div>
|
||||
{!isDisabled && (
|
||||
<Formik
|
||||
initialValues={initialValues}
|
||||
onSubmit={submitter}
|
||||
validate={validator}
|
||||
>
|
||||
{({
|
||||
values, errors, handleChange, handleSubmit, isSubmitting,
|
||||
}) => (
|
||||
<>
|
||||
{process.type === undefined && isSubmitting && <LoadingScreen message="Registration in progress..." />}
|
||||
<form className="auth-form" ref={formRef} onSubmit={handleSubmit}>
|
||||
<Input values={values.username} name="username" onChange={handleChange} label="Username" type="username" required />
|
||||
{errors.username && <Text className="auth-form__error" variant="b3">{errors.username}</Text>}
|
||||
<Input values={values.password} name="password" onChange={handleChange} label="Password" type="password" required />
|
||||
{errors.password && <Text className="auth-form__error" variant="b3">{errors.password}</Text>}
|
||||
<Input values={values.confirmPassword} name="confirmPassword" onChange={handleChange} label="Confirm password" type="password" required />
|
||||
{errors.confirmPassword && <Text className="auth-form__error" variant="b3">{errors.confirmPassword}</Text>}
|
||||
{isEmail && <Input values={values.email} name="email" onChange={handleChange} label={`Email${isEmailRequired ? '' : ' (optional)'}`} type="email" required={isEmailRequired} />}
|
||||
{errors.email && <Text className="auth-form__error" variant="b3">{errors.email}</Text>}
|
||||
{errors.other && <Text className="auth-form__error" variant="b3">{errors.other}</Text>}
|
||||
<div className="auth-form__btns">
|
||||
<Button variant="primary" type="submit" disabled={isSubmitting}>Register</Button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</Formik>
|
||||
)}
|
||||
{isDisabled && ssoProviders && (
|
||||
<SSOButtons
|
||||
type={ssoProviders.type.match(/^m.login.(sso|cas)$/)[1]}
|
||||
identityProviders={ssoProviders.identity_providers}
|
||||
baseUrl={baseUrl}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Register.propTypes = {
|
||||
registerInfo: PropTypes.shape({}).isRequired,
|
||||
loginFlow: PropTypes.arrayOf(
|
||||
PropTypes.shape({}),
|
||||
).isRequired,
|
||||
baseUrl: PropTypes.string.isRequired,
|
||||
};
|
||||
|
||||
function AuthCard() {
|
||||
const [hsConfig, setHsConfig] = useState(null);
|
||||
const [type, setType] = useState('login');
|
||||
|
||||
const handleHsChange = (info) => {
|
||||
console.log(info);
|
||||
setHsConfig(info);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Homeserver onChange={handleHsChange} />
|
||||
{ hsConfig !== null && (
|
||||
type === 'login'
|
||||
? <Login loginFlow={hsConfig.login.flows} baseUrl={hsConfig.baseUrl} />
|
||||
: (
|
||||
<Register
|
||||
registerInfo={hsConfig.register}
|
||||
loginFlow={hsConfig.login.flows}
|
||||
baseUrl={hsConfig.baseUrl}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
{ hsConfig !== null && (
|
||||
<Text variant="b2" className="auth-card__switch flex--center">
|
||||
{`${(type === 'login' ? 'Don\'t have' : 'Already have')} an account?`}
|
||||
<button
|
||||
type="button"
|
||||
style={{ color: 'var(--tc-link)', cursor: 'pointer', margin: '0 var(--sp-ultra-tight)' }}
|
||||
onClick={() => setType((type === 'login') ? 'register' : 'login')}
|
||||
>
|
||||
{ type === 'login' ? ' Register' : ' Login' }
|
||||
</button>
|
||||
</Text>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Auth.propTypes = {
|
||||
type: PropTypes.string.isRequired,
|
||||
};
|
||||
function Auth() {
|
||||
const [loginToken, setLoginToken] = useState(getUrlPrams('loginToken'));
|
||||
|
||||
useEffect(async () => {
|
||||
if (!loginToken) return;
|
||||
if (localStorage.getItem(cons.secretKey.BASE_URL) === undefined) {
|
||||
setLoginToken(null);
|
||||
return;
|
||||
}
|
||||
const baseUrl = localStorage.getItem(cons.secretKey.BASE_URL);
|
||||
try {
|
||||
await auth.loginWithToken(baseUrl, loginToken);
|
||||
|
||||
const { href } = window.location;
|
||||
window.location.replace(href.slice(0, href.indexOf('?')));
|
||||
} catch {
|
||||
setLoginToken(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
function StaticWrapper({ children }) {
|
||||
return (
|
||||
<ScrollView invisible>
|
||||
<div className="auth__wrapper flex--center">
|
||||
<div className="auth-card">
|
||||
<div className="auth-card__interactive flex-v">
|
||||
<div className="app-ident flex">
|
||||
<img className="app-ident__logo noselect" src={CinnySvg} alt="Cinny logo" />
|
||||
<div className="app-ident__text flex-v--center">
|
||||
<Text variant="h2">Cinny</Text>
|
||||
<Text variant="b2">Yet another matrix client</Text>
|
||||
<div className="auth__base">
|
||||
<div className="auth__wrapper">
|
||||
{loginToken && <LoadingScreen message="Redirecting..." />}
|
||||
{!loginToken && (
|
||||
<div className="auth-card flex-v">
|
||||
<Header>
|
||||
<Avatar size="extra-small" imageSrc={CinnySvg} />
|
||||
<TitleWrapper>
|
||||
<Text variant="h2">Cinny</Text>
|
||||
</TitleWrapper>
|
||||
</Header>
|
||||
<div className="auth-card__content">
|
||||
<AuthCard />
|
||||
</div>
|
||||
</div>
|
||||
{ children }
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="auth-footer">
|
||||
<Text variant="b2">
|
||||
<a href="https://cinny.in" target="_blank" rel="noreferrer">About</a>
|
||||
</Text>
|
||||
<Text variant="b2">
|
||||
<a href="https://github.com/ajbura/cinny/releases" target="_blank" rel="noreferrer">{`v${cons.version}`}</a>
|
||||
</Text>
|
||||
<Text variant="b2">
|
||||
<a href="https://twitter.com/cinnyapp" target="_blank" rel="noreferrer">Twitter</a>
|
||||
</Text>
|
||||
<Text variant="b2">
|
||||
<a href="https://matrix.org" target="_blank" rel="noreferrer">Powered by Matrix</a>
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
StaticWrapper.propTypes = {
|
||||
children: PropTypes.node.isRequired,
|
||||
};
|
||||
|
||||
function LoadingScreen({ message }) {
|
||||
return (
|
||||
<ProcessWrapper>
|
||||
@@ -359,7 +599,7 @@ Recaptcha.propTypes = {
|
||||
function Terms({ url, onSubmit }) {
|
||||
return (
|
||||
<ProcessWrapper>
|
||||
<form onSubmit={() => onSubmit(undefined, true)}>
|
||||
<form onSubmit={(e) => { e.preventDefault(); onSubmit(); }}>
|
||||
<div style={{ margin: 'var(--sp-normal)', maxWidth: '450px' }}>
|
||||
<Text variant="h2">Agree with terms</Text>
|
||||
<div style={{ marginBottom: 'var(--sp-normal)' }} />
|
||||
@@ -382,6 +622,27 @@ Terms.propTypes = {
|
||||
onSubmit: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
function EmailVerify({ email, onContinue }) {
|
||||
return (
|
||||
<ProcessWrapper>
|
||||
<div style={{ margin: 'var(--sp-normal)', maxWidth: '450px' }}>
|
||||
<Text variant="h2">Verify email</Text>
|
||||
<div style={{ margin: 'var(--sp-normal) 0' }}>
|
||||
<Text variant="b1">
|
||||
{'Please check your email '}
|
||||
<b>{`(${email})`}</b>
|
||||
{' and validate before continuing further.'}
|
||||
</Text>
|
||||
</div>
|
||||
<Button variant="primary" onClick={onContinue}>Continue</Button>
|
||||
</div>
|
||||
</ProcessWrapper>
|
||||
);
|
||||
}
|
||||
EmailVerify.propTypes = {
|
||||
email: PropTypes.string.isRequired,
|
||||
};
|
||||
|
||||
function ProcessWrapper({ children }) {
|
||||
return (
|
||||
<div className="process-wrapper">
|
||||
|
||||
@@ -1,156 +1,144 @@
|
||||
.auth__wrapper {
|
||||
.auth__base {
|
||||
--pattern-size: 48px;
|
||||
min-height: 100vh;
|
||||
padding: var(--sp-loose);
|
||||
background-color: var(--bg-surface-low);
|
||||
|
||||
background-image: url("https://images.unsplash.com/photo-1562619371-b67725b6fde2?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80");
|
||||
background-size: cover;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
background-image: radial-gradient(rgba(0, 0, 0, 6%) 2px, rgba(0, 0, 0, 0%) 2px);
|
||||
background-size: var(--pattern-size) var(--pattern-size);
|
||||
|
||||
.auth-card {
|
||||
width: 462px;
|
||||
min-height: 644px;
|
||||
background-color: var(--bg-surface-low);
|
||||
border-radius: var(--bo-radius);
|
||||
box-shadow: var(--bs-popup);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-flow: row nowrap;
|
||||
|
||||
&__interactive{
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.auth__wrapper {
|
||||
flex: 1;
|
||||
padding: var(--sp-loose);
|
||||
padding-bottom: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.auth-footer {
|
||||
padding: var(--sp-normal) 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
&__interactive {
|
||||
padding: calc(var(--sp-normal) + var(--sp-extra-loose));
|
||||
padding-bottom: var(--sp-extra-loose);
|
||||
background-color: var(--bg-surface);
|
||||
}
|
||||
& > *:nth-child(2n) {
|
||||
margin: 0 var(--sp-loose);
|
||||
}
|
||||
& a {
|
||||
color: var(--tc-surface-normal);
|
||||
&:hover { text-decoration: underline; }
|
||||
}
|
||||
}
|
||||
.auth-card {
|
||||
width: 462px;
|
||||
background-color: var(--bg-surface);
|
||||
border-radius: var(--bo-radius);
|
||||
box-shadow: var(--bs-popup);
|
||||
overflow: hidden;
|
||||
|
||||
&__content {
|
||||
padding: var(--sp-extra-loose) calc(var(--sp-normal) + var(--sp-extra-loose));
|
||||
}
|
||||
&__switch {
|
||||
margin-top: var(--sp-loose) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.app-ident {
|
||||
margin-bottom: var(--sp-extra-loose);
|
||||
|
||||
&__logo {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
.homeserver-form,
|
||||
.auth-form__heading {
|
||||
& .context-menu .btn-surface .ic-raw {
|
||||
width: 0;
|
||||
}
|
||||
&__text {
|
||||
margin-left: calc(var(--sp-loose) + var(--sp-ultra-tight));
|
||||
}
|
||||
|
||||
.text-s1 {
|
||||
margin-top: var(--sp-tight);
|
||||
color: var(--tc-surface-normal);
|
||||
.homeserver-form {
|
||||
display: flex;
|
||||
margin-bottom: var(--sp-extra-tight);
|
||||
align-items: flex-end;
|
||||
& > .input-container {
|
||||
flex: 1;
|
||||
& .input {
|
||||
border-right: unset;
|
||||
border-radius: var(--bo-radius) 0 0 var(--bo-radius);
|
||||
background-color: var(--bg-surface);
|
||||
}
|
||||
}
|
||||
& .ic-btn {
|
||||
height: 46px;
|
||||
border: 1px solid var(--bg-surface-border);
|
||||
border-radius: 0 var(--bo-radius) var(--bo-radius) 0;
|
||||
}
|
||||
[dir=rtl] & {
|
||||
& .input {
|
||||
border-radius: 0 var(--bo-radius) var(--bo-radius) 0;
|
||||
border-radius: 1px;
|
||||
border-left: unset;
|
||||
}
|
||||
.ic-btn {
|
||||
border-radius: var(--bo-radius) 0 0 var(--bo-radius);
|
||||
}
|
||||
}
|
||||
|
||||
[dir=rtl] & {
|
||||
margin-left: 0;
|
||||
margin-right: calc(var(--sp-loose) + var(--sp-ultra-tight));
|
||||
&__status {
|
||||
margin-top: var(--sp-normal);
|
||||
& .donut-spinner {
|
||||
min-width: 28px;
|
||||
}
|
||||
& .text {
|
||||
margin: 0 var(--sp-tight);
|
||||
}
|
||||
}
|
||||
&__error {
|
||||
margin-bottom: var(--sp-normal) !important;
|
||||
color: var(--tc-danger-normal) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.auth-form {
|
||||
|
||||
& > .text {
|
||||
margin-bottom: var(--sp-loose);
|
||||
margin-top: var(--sp-loose);
|
||||
}
|
||||
& > .input-container {
|
||||
margin-top: var(--sp-tight);
|
||||
margin: var(--sp-tight) 0 var(--sp-ultra-tight);
|
||||
}
|
||||
|
||||
&__heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-top: calc(var(--sp-extra-loose) + var(--sp-tight));
|
||||
}
|
||||
|
||||
.submit-btn__wrapper {
|
||||
margin-top: var(--sp-extra-loose);
|
||||
margin-bottom: var(--sp-loose);
|
||||
align-items: flex-start;
|
||||
|
||||
& > .error-message {
|
||||
display: none;
|
||||
flex: 1;
|
||||
color: var(--tc-danger-normal);
|
||||
margin-right: var(--sp-normal);
|
||||
word-break: break;
|
||||
|
||||
[dir=rtl] & {
|
||||
margin: {
|
||||
right: 0;
|
||||
left: var(--sp-normal);
|
||||
}
|
||||
}
|
||||
}
|
||||
&__btns {
|
||||
padding-top: var(--sp-loose);
|
||||
margin-bottom: var(--sp-extra-loose);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
&__wrapper {
|
||||
height: 100%;
|
||||
&__error {
|
||||
color: var(--tc-danger-normal) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.username__wrapper {
|
||||
.sso__divider {
|
||||
margin-bottom: var(--sp-tight);
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
align-items: center;
|
||||
|
||||
& > :first-child {
|
||||
&::before,
|
||||
&::after {
|
||||
flex: 1;
|
||||
|
||||
.input {
|
||||
border-radius: var(--bo-radius) 0 0 var(--bo-radius);
|
||||
|
||||
[dir=rtl] & {
|
||||
border-radius: 0 var(--bo-radius) var(--bo-radius) 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
& > :last-child {
|
||||
width: 110px;
|
||||
|
||||
.input {
|
||||
border-left-width: 0;
|
||||
background-color: var(--bg-surface);
|
||||
border-radius: 0 var(--bo-radius) var(--bo-radius) 0;
|
||||
|
||||
[dir=rtl] & {
|
||||
border-left-width: 1px;
|
||||
border-right-width: 0;
|
||||
border-radius: var(--bo-radius) 0 0 var(--bo-radius);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.password__wrapper {
|
||||
margin-top: var(--sp-tight);
|
||||
position: relative;
|
||||
|
||||
& .ic-btn {
|
||||
position: absolute;
|
||||
right: 6px;
|
||||
bottom: 6px;
|
||||
border-radius: calc(var(--bo-radius) / 2);
|
||||
[dir=rtl] & {
|
||||
left: 6px;
|
||||
right: unset;
|
||||
}
|
||||
content: '';
|
||||
margin: var(--sp-tight);
|
||||
border-bottom: 1px solid var(--bg-surface-border);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 462px) {
|
||||
.auth__wrapper {
|
||||
padding: 0;
|
||||
background-image: none;
|
||||
background-color: var(--bg-surface);
|
||||
|
||||
.auth-card {
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
|
||||
&__interactive {
|
||||
padding: var(--sp-extra-loose);
|
||||
}
|
||||
padding: var(--sp-tight);
|
||||
}
|
||||
.auth-card {
|
||||
&__content {
|
||||
padding: var(--sp-loose) var(--sp-normal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,14 +9,31 @@ import Windows from '../../organisms/pw/Windows';
|
||||
import Dialogs from '../../organisms/pw/Dialogs';
|
||||
import EmojiBoardOpener from '../../organisms/emoji-board/EmojiBoardOpener';
|
||||
import RoomOptions from '../../organisms/room-optons/RoomOptions';
|
||||
import logout from '../../../client/action/logout';
|
||||
|
||||
import initMatrix from '../../../client/initMatrix';
|
||||
|
||||
function Client() {
|
||||
const [isLoading, changeLoading] = useState(true);
|
||||
const [loadingMsg, setLoadingMsg] = useState('Heating up');
|
||||
|
||||
useEffect(() => {
|
||||
let counter = 0;
|
||||
const iId = setInterval(() => {
|
||||
const msgList = [
|
||||
'Sometimes it takes a while...',
|
||||
'Looks like you have a lot of stuff to heat up!',
|
||||
];
|
||||
if (counter === msgList.length - 1) {
|
||||
setLoadingMsg(msgList[msgList.length - 1]);
|
||||
clearInterval(iId);
|
||||
return;
|
||||
}
|
||||
setLoadingMsg(msgList[counter]);
|
||||
counter += 1;
|
||||
}, 9000);
|
||||
initMatrix.once('init_loading_finished', () => {
|
||||
clearInterval(iId);
|
||||
changeLoading(false);
|
||||
});
|
||||
initMatrix.init();
|
||||
@@ -25,8 +42,11 @@ function Client() {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="loading-display">
|
||||
<button className="loading__logout" onClick={logout} type="button">
|
||||
<Text variant="b3">Logout</Text>
|
||||
</button>
|
||||
<Spinner />
|
||||
<Text className="loading__message" variant="b2">Heating up</Text>
|
||||
<Text className="loading__message" variant="b2">{loadingMsg}</Text>
|
||||
|
||||
<div className="loading__appname">
|
||||
<Text variant="h2">Cinny</Text>
|
||||
|
||||
@@ -27,8 +27,19 @@
|
||||
}
|
||||
.loading__message {
|
||||
margin-top: var(--sp-normal);
|
||||
max-width: 350px;
|
||||
text-align: center;
|
||||
}
|
||||
.loading__appname {
|
||||
position: absolute;
|
||||
bottom: var(--sp-normal);
|
||||
}
|
||||
.loading__logout {
|
||||
position: absolute;
|
||||
bottom: var(--sp-extra-tight);
|
||||
right: var(--sp-extra-tight);
|
||||
cursor: pointer;
|
||||
.text {
|
||||
color: var(--tc-link);
|
||||
}
|
||||
}
|
||||
@@ -1,152 +1,101 @@
|
||||
import * as sdk from 'matrix-js-sdk';
|
||||
import cons from '../state/cons';
|
||||
import { getBaseUrl } from '../../util/matrixUtil';
|
||||
|
||||
async function login(username, homeserver, password) {
|
||||
let baseUrl = null;
|
||||
try {
|
||||
baseUrl = await getBaseUrl(homeserver);
|
||||
} catch (e) {
|
||||
baseUrl = `https://${homeserver}`;
|
||||
}
|
||||
function updateLocalStore(accessToken, deviceId, userId, baseUrl) {
|
||||
localStorage.setItem(cons.secretKey.ACCESS_TOKEN, accessToken);
|
||||
localStorage.setItem(cons.secretKey.DEVICE_ID, deviceId);
|
||||
localStorage.setItem(cons.secretKey.USER_ID, userId);
|
||||
localStorage.setItem(cons.secretKey.BASE_URL, baseUrl);
|
||||
}
|
||||
|
||||
if (typeof baseUrl === 'undefined') throw new Error('Homeserver not found');
|
||||
function createTemporaryClient(baseUrl) {
|
||||
return sdk.createClient({ baseUrl });
|
||||
}
|
||||
|
||||
const client = sdk.createClient({ baseUrl });
|
||||
async function startSsoLogin(baseUrl, type, idpId) {
|
||||
const client = createTemporaryClient(baseUrl);
|
||||
localStorage.setItem(cons.secretKey.BASE_URL, client.baseUrl);
|
||||
window.location.href = client.getSsoLoginUrl(window.location.href, type, idpId);
|
||||
}
|
||||
|
||||
const response = await client.login('m.login.password', {
|
||||
identifier: {
|
||||
type: 'm.id.user',
|
||||
user: username,
|
||||
},
|
||||
async function login(baseUrl, username, email, password) {
|
||||
const identifier = {};
|
||||
if (username) {
|
||||
identifier.type = 'm.id.user';
|
||||
identifier.user = username;
|
||||
} else if (email) {
|
||||
identifier.type = 'm.id.thirdparty';
|
||||
identifier.medium = 'email';
|
||||
identifier.address = email;
|
||||
} else throw new Error('Bad Input');
|
||||
|
||||
const client = createTemporaryClient(baseUrl);
|
||||
const res = await client.login('m.login.password', {
|
||||
identifier,
|
||||
password,
|
||||
initial_device_display_name: cons.DEVICE_DISPLAY_NAME,
|
||||
});
|
||||
|
||||
localStorage.setItem(cons.secretKey.ACCESS_TOKEN, response.access_token);
|
||||
localStorage.setItem(cons.secretKey.DEVICE_ID, response.device_id);
|
||||
localStorage.setItem(cons.secretKey.USER_ID, response.user_id);
|
||||
localStorage.setItem(cons.secretKey.BASE_URL, response?.well_known?.['m.homeserver']?.base_url || baseUrl);
|
||||
const myBaseUrl = res?.well_known?.['m.homeserver']?.base_url || client.baseUrl;
|
||||
updateLocalStore(res.access_token, res.device_id, res.user_id, myBaseUrl);
|
||||
}
|
||||
|
||||
async function getAdditionalInfo(baseUrl, content) {
|
||||
try {
|
||||
const res = await fetch(`${baseUrl}/_matrix/client/r0/register`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(content),
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const data = await res.json();
|
||||
return data;
|
||||
} catch (e) {
|
||||
throw new Error(e);
|
||||
}
|
||||
}
|
||||
async function verifyEmail(baseUrl, content) {
|
||||
try {
|
||||
const res = await fetch(`${baseUrl}/_matrix/client/r0/register/email/requestToken`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(content),
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const data = await res.json();
|
||||
return data;
|
||||
} catch (e) {
|
||||
throw new Error(e);
|
||||
}
|
||||
}
|
||||
async function loginWithToken(baseUrl, token) {
|
||||
const client = createTemporaryClient(baseUrl);
|
||||
|
||||
let session = null;
|
||||
let clientSecret = null;
|
||||
let sid = null;
|
||||
async function register(username, homeserver, password, email, recaptchaValue, terms, verified) {
|
||||
const baseUrl = await getBaseUrl(homeserver);
|
||||
|
||||
if (typeof baseUrl === 'undefined') throw new Error('Homeserver not found');
|
||||
|
||||
const client = sdk.createClient({ baseUrl });
|
||||
|
||||
const isAvailable = await client.isUsernameAvailable(username);
|
||||
if (!isAvailable) throw new Error('Username not available');
|
||||
|
||||
if (typeof recaptchaValue === 'string') {
|
||||
await getAdditionalInfo(baseUrl, {
|
||||
auth: {
|
||||
type: 'm.login.recaptcha',
|
||||
session,
|
||||
response: recaptchaValue,
|
||||
},
|
||||
});
|
||||
} else if (terms === true) {
|
||||
await getAdditionalInfo(baseUrl, {
|
||||
auth: {
|
||||
type: 'm.login.terms',
|
||||
session,
|
||||
},
|
||||
});
|
||||
} else if (verified !== true) {
|
||||
session = null;
|
||||
clientSecret = client.generateClientSecret();
|
||||
const verifyData = await verifyEmail(baseUrl, {
|
||||
email,
|
||||
client_secret: clientSecret,
|
||||
send_attempt: 1,
|
||||
});
|
||||
if (typeof verifyData.error === 'string') {
|
||||
throw new Error(verifyData.error);
|
||||
}
|
||||
sid = verifyData.sid;
|
||||
}
|
||||
|
||||
const additionalInfo = await getAdditionalInfo(baseUrl, {
|
||||
auth: { session: (session !== null) ? session : undefined },
|
||||
const res = await client.login('m.login.token', {
|
||||
token,
|
||||
initial_device_display_name: cons.DEVICE_DISPLAY_NAME,
|
||||
});
|
||||
session = additionalInfo.session;
|
||||
if (typeof additionalInfo.completed === 'undefined' || additionalInfo.completed.length === 0) {
|
||||
return ({
|
||||
type: 'recaptcha',
|
||||
public_key: additionalInfo.params['m.login.recaptcha'].public_key,
|
||||
});
|
||||
}
|
||||
if (additionalInfo.completed.find((process) => process === 'm.login.recaptcha') === 'm.login.recaptcha'
|
||||
&& !additionalInfo.completed.find((process) => process === 'm.login.terms')) {
|
||||
return ({
|
||||
type: 'terms',
|
||||
en: additionalInfo.params['m.login.terms'].policies.privacy_policy.en,
|
||||
});
|
||||
}
|
||||
if (verified || additionalInfo.completed.find((process) => process === 'm.login.terms') === 'm.login.terms') {
|
||||
const tpc = {
|
||||
client_secret: clientSecret,
|
||||
sid,
|
||||
};
|
||||
const verifyData = await getAdditionalInfo(baseUrl, {
|
||||
auth: {
|
||||
session,
|
||||
type: 'm.login.email.identity',
|
||||
threepidCreds: tpc,
|
||||
threepid_creds: tpc,
|
||||
},
|
||||
username,
|
||||
password,
|
||||
});
|
||||
if (verifyData.errcode === 'M_UNAUTHORIZED') {
|
||||
return { type: 'email' };
|
||||
}
|
||||
|
||||
localStorage.setItem(cons.secretKey.ACCESS_TOKEN, verifyData.access_token);
|
||||
localStorage.setItem(cons.secretKey.DEVICE_ID, verifyData.device_id);
|
||||
localStorage.setItem(cons.secretKey.USER_ID, verifyData.user_id);
|
||||
localStorage.setItem(cons.secretKey.BASE_URL, baseUrl);
|
||||
return { type: 'done' };
|
||||
}
|
||||
return {};
|
||||
const myBaseUrl = res?.well_known?.['m.homeserver']?.base_url || client.baseUrl;
|
||||
updateLocalStore(res.access_token, res.device_id, res.user_id, myBaseUrl);
|
||||
}
|
||||
|
||||
export { login, register };
|
||||
// eslint-disable-next-line camelcase
|
||||
async function verifyEmail(baseUrl, email, client_secret, send_attempt, next_link) {
|
||||
const res = await fetch(`${baseUrl}/_matrix/client/r0/register/email/requestToken`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
email, client_secret, send_attempt, next_link,
|
||||
}),
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const data = await res.json();
|
||||
return data;
|
||||
}
|
||||
|
||||
async function completeRegisterStage(
|
||||
baseUrl, username, password, auth,
|
||||
) {
|
||||
const tempClient = createTemporaryClient(baseUrl);
|
||||
|
||||
try {
|
||||
const result = await tempClient.registerRequest({
|
||||
username, password, auth,
|
||||
});
|
||||
const data = { completed: result.completed || [] };
|
||||
if (result.access_token) {
|
||||
data.done = true;
|
||||
updateLocalStore(result.access_token, result.device_id, result.user_id, baseUrl);
|
||||
}
|
||||
return data;
|
||||
} catch (e) {
|
||||
const result = e.data;
|
||||
const data = { completed: result.completed || [] };
|
||||
if (result.access_token) {
|
||||
data.done = true;
|
||||
updateLocalStore(result.access_token, result.device_id, result.user_id, baseUrl);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
createTemporaryClient, login, verifyEmail,
|
||||
loginWithToken, startSsoLogin,
|
||||
completeRegisterStage,
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import initMatrix from '../initMatrix';
|
||||
|
||||
function logout() {
|
||||
const mx = initMatrix.matrixClient;
|
||||
mx.stopClient();
|
||||
mx.logout().then(() => {
|
||||
mx.clearStores();
|
||||
window.localStorage.clear();
|
||||
|
||||
@@ -55,6 +55,14 @@ function openInviteUser(roomId, searchTerm) {
|
||||
});
|
||||
}
|
||||
|
||||
function openProfileViewer(userId, roomId) {
|
||||
appDispatcher.dispatch({
|
||||
type: cons.actions.navigation.OPEN_PROFILE_VIEWER,
|
||||
userId,
|
||||
roomId,
|
||||
});
|
||||
}
|
||||
|
||||
function openSettings() {
|
||||
appDispatcher.dispatch({
|
||||
type: cons.actions.navigation.OPEN_SETTINGS,
|
||||
@@ -94,6 +102,7 @@ export {
|
||||
openPublicRooms,
|
||||
openCreateRoom,
|
||||
openInviteUser,
|
||||
openProfileViewer,
|
||||
openSettings,
|
||||
openEmojiBoard,
|
||||
openReadReceipts,
|
||||
|
||||
@@ -132,9 +132,11 @@ function leave(roomId) {
|
||||
* @param {boolean} [opts.isEncrypted=false] Makes room encrypted
|
||||
* @param {boolean} [opts.isDirect=false] Makes room as direct message
|
||||
* @param {string[]} [opts.invite=[]] An array of userId's to invite
|
||||
* @param{number} [opts.powerLevel=100] My power level
|
||||
*/
|
||||
async function create(opts) {
|
||||
const mx = initMatrix.matrixClient;
|
||||
const customPowerLevels = [101];
|
||||
const options = {
|
||||
name: opts.name,
|
||||
topic: opts.topic,
|
||||
@@ -143,6 +145,10 @@ async function create(opts) {
|
||||
is_direct: opts.isDirect === true,
|
||||
invite: opts.invite || [],
|
||||
initial_state: [],
|
||||
preset: opts.isDirect === true ? 'trusted_private_chat' : undefined,
|
||||
power_level_content_override: customPowerLevels.indexOf(opts.powerLevel) === -1 ? undefined : {
|
||||
users: { [initMatrix.matrixClient.getUserId()]: opts.powerLevel },
|
||||
},
|
||||
};
|
||||
|
||||
if (opts.isPublic !== true && opts.isEncrypted === true) {
|
||||
@@ -182,12 +188,15 @@ async function create(opts) {
|
||||
async function invite(roomId, userId) {
|
||||
const mx = initMatrix.matrixClient;
|
||||
|
||||
try {
|
||||
const result = await mx.invite(roomId, userId);
|
||||
return result;
|
||||
} catch (e) {
|
||||
throw new Error(e);
|
||||
}
|
||||
const result = await mx.invite(roomId, userId);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function kick(roomId, userId) {
|
||||
const mx = initMatrix.matrixClient;
|
||||
|
||||
const result = await mx.kick(roomId, userId);
|
||||
return result;
|
||||
}
|
||||
|
||||
function createSpaceShortcut(roomId) {
|
||||
@@ -206,6 +215,6 @@ function deleteSpaceShortcut(roomId) {
|
||||
|
||||
export {
|
||||
join, leave,
|
||||
create, invite,
|
||||
create, invite, kick,
|
||||
createSpaceShortcut, deleteSpaceShortcut,
|
||||
};
|
||||
|
||||
@@ -77,12 +77,28 @@ class Notifications extends EventEmitter {
|
||||
return this.roomIdToNoti.has(roomId);
|
||||
}
|
||||
|
||||
_getAllParentIds(roomId) {
|
||||
let allParentIds = this.roomList.roomIdToParents.get(roomId);
|
||||
if (allParentIds === undefined) return new Set();
|
||||
const parentIds = [...allParentIds];
|
||||
|
||||
parentIds.forEach((pId) => {
|
||||
allParentIds = new Set(
|
||||
[...allParentIds, ...this._getAllParentIds(pId)],
|
||||
);
|
||||
});
|
||||
|
||||
return allParentIds;
|
||||
}
|
||||
|
||||
_setNoti(roomId, total, highlight, childId) {
|
||||
const prevTotal = this.roomIdToNoti.get(roomId)?.total ?? null;
|
||||
const noti = this.getNoti(roomId);
|
||||
|
||||
noti.total += total;
|
||||
noti.highlight += highlight;
|
||||
if (!childId || this._remainingParentIds?.has(roomId)) {
|
||||
noti.total += total;
|
||||
noti.highlight += highlight;
|
||||
}
|
||||
if (childId) {
|
||||
if (noti.from === null) noti.from = new Set();
|
||||
noti.from.add(childId);
|
||||
@@ -91,9 +107,16 @@ class Notifications extends EventEmitter {
|
||||
this.roomIdToNoti.set(roomId, noti);
|
||||
this.emit(cons.events.notifications.NOTI_CHANGED, roomId, noti.total, prevTotal);
|
||||
|
||||
if (!childId) this._remainingParentIds = this._getAllParentIds(roomId);
|
||||
else this._remainingParentIds.delete(roomId);
|
||||
|
||||
const parentIds = this.roomList.roomIdToParents.get(roomId);
|
||||
if (typeof parentIds === 'undefined') return;
|
||||
if (typeof parentIds === 'undefined') {
|
||||
if (!childId) this._remainingParentIds = undefined;
|
||||
return;
|
||||
}
|
||||
[...parentIds].forEach((parentId) => this._setNoti(parentId, total, highlight, roomId));
|
||||
if (!childId) this._remainingParentIds = undefined;
|
||||
}
|
||||
|
||||
_deleteNoti(roomId, total, highlight, childId) {
|
||||
@@ -103,8 +126,12 @@ class Notifications extends EventEmitter {
|
||||
const prevTotal = noti.total;
|
||||
noti.total -= total;
|
||||
noti.highlight -= highlight;
|
||||
if (noti.total < 0) {
|
||||
noti.total = 0;
|
||||
noti.highlight = 0;
|
||||
}
|
||||
if (childId && noti.from !== null) {
|
||||
noti.from.delete(childId);
|
||||
if (!this.hasNoti(childId)) noti.from.delete(childId);
|
||||
}
|
||||
if (noti.from === null || noti.from.size === 0) {
|
||||
this.roomIdToNoti.delete(roomId);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const cons = {
|
||||
version: '1.5.0',
|
||||
secretKey: {
|
||||
ACCESS_TOKEN: 'cinny_access_token',
|
||||
DEVICE_ID: 'cinny_device_id',
|
||||
@@ -27,6 +28,7 @@ const cons = {
|
||||
OPEN_PUBLIC_ROOMS: 'OPEN_PUBLIC_ROOMS',
|
||||
OPEN_CREATE_ROOM: 'OPEN_CREATE_ROOM',
|
||||
OPEN_INVITE_USER: 'OPEN_INVITE_USER',
|
||||
OPEN_PROFILE_VIEWER: 'OPEN_PROFILE_VIEWER',
|
||||
OPEN_SETTINGS: 'OPEN_SETTINGS',
|
||||
OPEN_EMOJIBOARD: 'OPEN_EMOJIBOARD',
|
||||
OPEN_READRECEIPTS: 'OPEN_READRECEIPTS',
|
||||
@@ -57,6 +59,7 @@ const cons = {
|
||||
CREATE_ROOM_OPENED: 'CREATE_ROOM_OPENED',
|
||||
INVITE_USER_OPENED: 'INVITE_USER_OPENED',
|
||||
SETTINGS_OPENED: 'SETTINGS_OPENED',
|
||||
PROFILE_VIEWER_OPENED: 'PROFILE_VIEWER_OPENED',
|
||||
EMOJIBOARD_OPENED: 'EMOJIBOARD_OPENED',
|
||||
READRECEIPTS_OPENED: 'READRECEIPTS_OPENED',
|
||||
ROOMOPTIONS_OPENED: 'ROOMOPTIONS_OPENED',
|
||||
|
||||
@@ -69,6 +69,9 @@ class Navigation extends EventEmitter {
|
||||
[cons.actions.navigation.OPEN_INVITE_USER]: () => {
|
||||
this.emit(cons.events.navigation.INVITE_USER_OPENED, action.roomId, action.searchTerm);
|
||||
},
|
||||
[cons.actions.navigation.OPEN_PROFILE_VIEWER]: () => {
|
||||
this.emit(cons.events.navigation.PROFILE_VIEWER_OPENED, action.userId, action.roomId);
|
||||
},
|
||||
[cons.actions.navigation.OPEN_SETTINGS]: () => {
|
||||
this.emit(cons.events.navigation.SETTINGS_OPENED);
|
||||
},
|
||||
|
||||
@@ -290,6 +290,11 @@ button {
|
||||
overflow: visible;
|
||||
-webkit-appearance: button;
|
||||
}
|
||||
textarea, input[type="text"] {
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
appearance: none;
|
||||
}
|
||||
textarea {
|
||||
color: inherit;
|
||||
word-spacing: inherit;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable max-classes-per-file */
|
||||
export function bytesToSize(bytes) {
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
||||
if (bytes === 0) return 'n/a';
|
||||
@@ -33,3 +34,53 @@ export function abbreviateNumber(number) {
|
||||
if (number > 99) return '99+';
|
||||
return number;
|
||||
}
|
||||
|
||||
export class Debounce {
|
||||
constructor() {
|
||||
this.timeoutId = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {function} func - callback function
|
||||
* @param {number} wait - wait in milliseconds to call func
|
||||
* @returns {func} debounceCallback - to pass arguments to func callback
|
||||
*/
|
||||
_(func, wait) {
|
||||
const that = this;
|
||||
return function debounceCallback(...args) {
|
||||
clearTimeout(that.timeoutId);
|
||||
that.timeoutId = setTimeout(() => {
|
||||
func.apply(this, args);
|
||||
that.timeoutId = null;
|
||||
}, wait);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export class Throttle {
|
||||
constructor() {
|
||||
this.timeoutId = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {function} func - callback function
|
||||
* @param {number} wait - wait in milliseconds to call func
|
||||
* @returns {function} throttleCallback - to pass arguments to func callback
|
||||
*/
|
||||
_(func, wait) {
|
||||
const that = this;
|
||||
return function throttleCallback(...args) {
|
||||
if (that.timeoutId !== null) return;
|
||||
that.timeoutId = setTimeout(() => {
|
||||
func.apply(this, args);
|
||||
that.timeoutId = null;
|
||||
}, wait);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function getUrlPrams(paramName) {
|
||||
const queryString = window.location.search;
|
||||
const urlParams = new URLSearchParams(queryString);
|
||||
return urlParams.get(paramName);
|
||||
}
|
||||
|
||||
@@ -2,15 +2,18 @@ import initMatrix from '../client/initMatrix';
|
||||
|
||||
const WELL_KNOWN_URI = '/.well-known/matrix/client';
|
||||
|
||||
async function getBaseUrl(homeserver) {
|
||||
const serverDiscoveryUrl = `https://${homeserver}${WELL_KNOWN_URI}`;
|
||||
async function getBaseUrl(servername) {
|
||||
let protocol = 'https://';
|
||||
if (servername.match(/^https?:\/\//) !== null) protocol = '';
|
||||
const serverDiscoveryUrl = `${protocol}${servername}${WELL_KNOWN_URI}`;
|
||||
try {
|
||||
const result = await fetch(serverDiscoveryUrl, { method: 'GET' });
|
||||
const data = await result.json();
|
||||
const result = await (await fetch(serverDiscoveryUrl, { method: 'GET' })).json();
|
||||
|
||||
return data?.['m.homeserver']?.base_url;
|
||||
const baseUrl = result?.['m.homeserver']?.base_url;
|
||||
if (baseUrl === undefined) throw new Error();
|
||||
return baseUrl;
|
||||
} catch (e) {
|
||||
throw new Error('Homeserver not found');
|
||||
throw new Error(`${protocol}${servername}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +72,15 @@ function doesRoomHaveUnread(room) {
|
||||
return true;
|
||||
}
|
||||
|
||||
function getPowerLabel(powerLevel) {
|
||||
if (powerLevel > 9000) return 'Goku';
|
||||
if (powerLevel > 100) return 'Founder';
|
||||
if (powerLevel === 100) return 'Admin';
|
||||
if (powerLevel >= 50) return 'Mod';
|
||||
return null;
|
||||
}
|
||||
|
||||
export {
|
||||
getBaseUrl, getUsername, getUsernameOfRoomMember,
|
||||
isRoomAliasAvailable, doesRoomHaveUnread,
|
||||
isRoomAliasAvailable, doesRoomHaveUnread, getPowerLabel,
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
|
||||
const webpack = require('webpack');
|
||||
const CopyPlugin = require("copy-webpack-plugin");
|
||||
|
||||
module.exports = {
|
||||
entry: {
|
||||
@@ -38,15 +39,13 @@ module.exports = {
|
||||
use: ['html-loader'],
|
||||
},
|
||||
{
|
||||
test: /\.(svg|png|jpe?g|gif|otf|ttf)$/,
|
||||
use: {
|
||||
loader: 'file-loader',
|
||||
options: {
|
||||
name: '[name].[hash].[ext]',
|
||||
outputPath: 'assets',
|
||||
},
|
||||
},
|
||||
test: /\.(png|jpe?g|gif|otf|ttf)$/,
|
||||
type: 'asset/resource',
|
||||
},
|
||||
{
|
||||
test: /\.svg$/,
|
||||
type: 'asset/inline',
|
||||
}
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
@@ -70,5 +69,12 @@ module.exports = {
|
||||
new webpack.DefinePlugin({
|
||||
'process.env': JSON.stringify(process.env),
|
||||
}),
|
||||
new CopyPlugin({
|
||||
patterns: [
|
||||
{ from: 'olm.wasm' },
|
||||
{ from: '_redirects' },
|
||||
{ from: 'config.json' },
|
||||
],
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -4,7 +4,6 @@ const { merge } = require('webpack-merge');
|
||||
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
|
||||
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
|
||||
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
|
||||
const CopyPlugin = require("copy-webpack-plugin");
|
||||
|
||||
module.exports = merge(common, {
|
||||
mode: 'production',
|
||||
@@ -36,11 +35,5 @@ module.exports = merge(common, {
|
||||
new MiniCssExtractPlugin({
|
||||
filename: '[name].[contenthash].bundle.css',
|
||||
}),
|
||||
new CopyPlugin({
|
||||
patterns: [
|
||||
{ from: 'olm.wasm' },
|
||||
{ from: '_redirects' },
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user