Compare commits

...

73 Commits

Author SHA1 Message Date
Ajay Bura
2c9e32b6c4 Readded package-lock.json
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-07 18:17:44 +05:30
Ajay Bura
fc470d0622 Minor changes to registration msg
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-07 17:44:09 +05:30
Ajay Bura
a3270041e3 Bumped dependencies and v1.5.0
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-07 15:46:36 +05:30
Ajay Bura
956068d0d6 Depd sorted
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-07 10:19:23 +05:30
Samuel Dionne-Riel
3776e32364 Fix commands activating anywhere in the input (#156)
* Fix commands activating anywhere in the input

Writing `The command to leave a channel is /leave` might have had "fun"
consequences for users.

Fixes #155

* Fix go-to commands activating anywhere in the input

While less obtrusive than `/` commands activating anywhere, it seems
logical to only activate completion of those when at the beginning of
the input.
2021-11-07 10:02:50 +05:30
Ajay Bura
fb5a54dd17 Re: fix alignment on hsInput in safari
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-06 19:12:45 +05:30
Ajay Bura
916d564f82 fix alignment on hsInput in safari
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-06 18:25:56 +05:30
Ajay Bura
364def188a Removed some servers and fixed shadow on input in safari
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-06 18:09:29 +05:30
Ajay Bura
d1228a085b Updated dependencies
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-06 17:56:50 +05:30
Ajay Bura
6c5a29fb48 Updated dependencies and build instructions
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-06 16:26:18 +05:30
Ajay Bura
a83aecaa69 Full UIAA implement (#93), #32, #146, #64, #102
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-06 15:15:35 +05:30
Ajay Bura
3d885ec262 Added debounce, throttle, getUrlParams
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-11-06 15:12:36 +05:30
Ajay Bura
6fdace07c8 Automatic update people list
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-29 18:11:02 +05:30
Ajay Bura
8711658e75 Feature: invite/disinvite from profile viewer
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-29 17:13:33 +05:30
Ajay Bura
e25dc46863 Add option to select role on roomCreation
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-29 14:59:16 +05:30
Ajay Bura
f53f54af7f Refactor 2194cb65a2
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-29 13:20:27 +05:30
Ajay Bura
763aa8865b Bumped dependencies
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-28 18:39:34 +05:30
Ajay Bura
2194cb65a2 Hide pinned space notification from home icon
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-28 15:30:16 +05:30
Ajay Bura
60435d505f Fix duplicate notification count
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-28 15:08:26 +05:30
Ajay Bura
af983c76b8 Fix SOO button sorting
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-28 13:42:57 +05:30
Zalax
ef161bbb31 Improve SSO display on login page (#150)
sort SSO providers by alphabetical order, and reset provider list on homeserver change (to avoid having them if the homeserver is invalid)
2021-10-27 19:09:35 +05:30
daemonspring
ac364e5ab7 Fixed links splitting across line mid-word (#151)
`break-all` meant that links would split mid-word e.g. I observed `email` become `e\nmail`. `break-word` avoids this but also ensures long links still break before overflowing the line length.
2021-10-27 19:01:45 +05:30
Ajay Bura
2e2b1c6f18 Added variety of msg on loading app
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-27 19:00:31 +05:30
Ajay Bura
1fa1496d7f Added logout in loading screen
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-27 17:08:26 +05:30
Ajay Bura
8fb9365eaa Enhanced invite list UX
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-27 16:48:31 +05:30
Ajay Bura
92ab8331d0 Fix overscroll behavior
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-27 16:06:07 +05:30
Ajay Bura
603d373cee Fix notification minus count
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-27 16:03:41 +05:30
Ajay Bura
aca2c3a9dd v1.4.0: SSO login and profile viewer
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-25 17:53:25 +05:30
Ajay Bura
f544dab3e0 Fix reaction selector doesn't focus msg input (#62)
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-25 17:28:14 +05:30
Ajay Bura
c489940f8b Fix message menu placement on large screen (#113)
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-25 17:19:11 +05:30
Ajay Bura
dc7ddeaa9b Fix wildcard matching in emojisearch (#121)
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-25 16:46:23 +05:30
Ajay Bura
9b5f42cda9 Fix profile picture inconsistency (#104, #147)
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-25 14:25:06 +05:30
Ajay Bura
4022e4969d UI improvement in SSO
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-24 17:33:56 +05:30
Ajay Bura
ed62d06b5e SegmentedControl bug fixed
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-23 15:41:16 +05:30
Ajay Bura
f11e4f6626 Add option to filter PeopleDrawer
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-23 15:27:54 +05:30
Ajay Bura
59eec5241a Enhanced people search UX
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-22 20:02:01 +05:30
Ajay Bura
d287486165 Added button reset type.
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-22 17:13:57 +05:30
Ajay Bura
f70270a0b3 Fixed inconsistent search in emojiboard.
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-22 17:02:42 +05:30
Ajay Bura
36380fe5fd Add search in People drawer
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-21 17:50:49 +05:30
Ajay Bura
dc7fca4f4c SSO login bug fixed
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-19 20:23:15 +05:30
Ajay Bura
977759145e Fix redirect on SSO login (#142), #27, #94
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-19 19:38:09 +05:30
James Julich
76c3660cb2 Address 301 redirect issue and Safari regex issue. (#143)
* Address 301 redirect issue and Safari regex issue.

* Restored login redirect

as this doesn't not fix the sso redirect #143.

Co-authored-by: Ajay Bura <32841439+ajbura@users.noreply.github.com>
2021-10-19 18:09:30 +05:30
Gero Gerke
fa10a67811 Implement Profile Viewer (#130)
* Implement Profile Viewer

Fixes #111

* Make user avatar in chat clickable

* design progress

* Refactored code

* progress

* Updated chip comp

Signed-off-by: Ajay Bura <ajbura@gmail.com>

* Refactored ProfileViewer comp

Signed-off-by: Ajay Bura <ajbura@gmail.com>

* Added msg functionality in ProfileViewer

Signed-off-by: Ajay Bura <ajbura@gmail.com>

* Added Ignore functionality in ProfileViewer

Signed-off-by: Ajay Bura <ajbura@gmail.com>

* Fixed Ignore btn bug

Signed-off-by: Ajay Bura <ajbura@gmail.com>

* Refectored ProfileViewer comp

Signed-off-by: Ajay Bura <ajbura@gmail.com>

Co-authored-by: Ajay Bura <ajbura@gmail.com>
2021-10-18 20:55:52 +05:30
Ajay Bura
8d95fd0ca0 Update pull-request.yml 2021-10-14 10:42:07 +05:30
Ajay Bura
332e95701e Update pull-request.yml 2021-10-14 10:34:04 +05:30
Ajay Bura
124b24ab76 Fixed deploy on PR 2021-10-14 10:28:31 +05:30
Ajay Bura
6ccd1e43bc Update pull-request.yml 2021-10-12 15:00:09 +05:30
Ajay Bura
5c09d04912 added action for pull request previews 2021-10-11 15:22:15 +05:30
jamesjulich
119325c3a2 Add support for SSO login. 2021-10-11 11:21:44 +05:30
kfiven
462a559bd3 Fix unable to send msg in DM from IRC users (#135) 2021-10-11 11:19:32 +05:30
Ajay Bura
1bd58a0103 Fix make both user admin on DM create
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-11 11:16:16 +05:30
Ajay Bura
6c97d08027 Updated support link
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-06 13:48:30 +05:30
Ajay Bura
0ebda9d224 v1.3.2
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-06 12:42:48 +05:30
Ajay Bura
808fc8dc0d Fix Password don't match on register page
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-06 12:35:51 +05:30
Ajay Bura
aefed73f5a Revert dark theme color changes
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-04 11:01:27 +05:30
Ajay Bura
ea47750ea4 Made ContextMenu animation little fast (#114)
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-04 11:00:18 +05:30
Ajay Bura
0f02bfd2c3 Merge pull request #128 from Empty2k12/fix/no-public-rooms
Improve message when there are no public rooms on a server
2021-10-03 10:00:23 +05:30
Ajay Bura
8e5a5baf52 Better error handling when server room list is private
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-10-03 09:53:54 +05:30
Krishan
3deb8eb488 Merge pull request #125 from Empty2k12/fix/powerlevel-sending
Disallow sending messages to rooms with insufficient powerlevel
2021-09-30 21:00:00 +05:30
kfiven
1dd7f0371d Changed p to Text component 2021-09-30 20:56:39 +05:30
Gero Gerke
7d032bb684 Improve message when there are no public rooms on a server 2021-09-30 17:24:28 +02:00
Gero Gerke
ecc4a40eea Disallow sending to rooms with insufficient powerlevel
Fixes #123
2021-09-30 16:17:01 +02:00
Ajay Bura
83c6914a50 Merge pull request #117 from ajbura/master
v1.3.1: Bug fixes
2021-09-26 18:59:53 +05:30
Ajay Bura
0f06d88e18 v1.3.1
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-09-26 18:51:22 +05:30
Ajay Bura
ea5f7b65f3 Fixed #115: High CPU usages while idling
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-09-26 18:47:37 +05:30
Ajay Bura
9ce95da8f4 Fixed #103: Crash when space nesting has a loop
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-09-25 20:18:06 +05:30
Ajay Bura
abd1fd3efb fixed dark theme color
Signed-off-by: Ajay Bura <ajbura@gmail.com>
2021-09-25 18:18:58 +05:30
Ajay Bura
90ab8dac27 Merge pull request #116 from jamesjulich/chip
Added chip component.
2021-09-23 16:43:40 +05:30
Ajay Bura
c96d556094 Updated Chip.scss property ordering 2021-09-23 16:40:52 +05:30
jamesjulich
26f68a890e Added chip component. 2021-09-20 11:02:15 -05:00
Ajay Bura
cd5b7b17f6 Added more options to run locally 2021-09-15 17:17:31 +05:30
Ajay Bura
14cfa69060 Merge pull request #100 from mkljczk/fix-typo
Fix typo
2021-09-14 14:56:27 +05:30
marcin mikołajczak
d6d1b0eeef Fix typo
Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
2021-09-14 09:30:37 +02:00
66 changed files with 22730 additions and 6113 deletions

30
.github/workflows/pull-request.yml vendored Normal file
View 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 }}

2
.gitignore vendored
View File

@@ -2,3 +2,5 @@ experiment
dist dist
node_modules node_modules
devAssets devAssets
.DS_Store

View File

@@ -14,6 +14,11 @@ Cinny is a [Matrix](https://matrix.org) client focusing primarily on simple, ele
## Building and Running ## Building and Running
### Running pre-compiled
A tarball of pre-compiled version of the app is provided with each [release](https://github.com/ajbura/cinny/releases).
You can serve the application with a webserver of your choosing by simply copying `dist/` directory to the webroot.
### Building from source ### Building from source
Execute the following commands to compile the app from its source code: Execute the following commands to compile the app from its source code:
@@ -44,6 +49,12 @@ docker run -p 8080:80 cinny:latest
This will forward your `localhost` port 8080 to the container's port 80. You can visit the app in your browser by This will forward your `localhost` port 8080 to the container's port 80. You can visit the app in your browser by
navigating to `http://localhost:8080`. 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 ## License
Copyright (c) 2021 Ajay Bura (ajbura) and other contributors Copyright (c) 2021 Ajay Bura (ajbura) and other contributors

12
config.json Normal file
View File

@@ -0,0 +1,12 @@
{
"defaultHomeserver": 5,
"homeserverList": [
"boba.best",
"converser.eu",
"envs.net",
"halogen.city",
"kde.org",
"matrix.org",
"mozilla.modular.im"
]
}

26262
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "cinny", "name": "cinny",
"version": "1.3.0", "version": "1.5.0",
"description": "Yet another matrix client", "description": "Yet another matrix client",
"main": "index.js", "main": "index.js",
"engines": { "engines": {
@@ -22,8 +22,10 @@
"dateformat": "^4.5.1", "dateformat": "^4.5.1",
"emojibase-data": "^6.2.0", "emojibase-data": "^6.2.0",
"flux": "^4.0.1", "flux": "^4.0.1",
"formik": "^2.2.9",
"html-react-parser": "^1.2.7", "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", "matrix-js-sdk": "^12.4.1",
"micromark": "^3.0.3", "micromark": "^3.0.3",
"micromark-extension-gfm": "^1.0.0", "micromark-extension-gfm": "^1.0.0",
@@ -71,9 +73,9 @@
"stream-browserify": "^3.0.0", "stream-browserify": "^3.0.0",
"style-loader": "^2.0.0", "style-loader": "^2.0.0",
"util": "^0.12.4", "util": "^0.12.4",
"webpack": "^5.28.0", "webpack": "^5.62.1",
"webpack-cli": "^4.5.0", "webpack-cli": "^4.9.1",
"webpack-dev-server": "^3.11.2", "webpack-dev-server": "^4.4.0",
"webpack-merge": "^5.7.3" "webpack-merge": "^5.7.3"
} }
} }

View 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

View File

@@ -24,7 +24,6 @@
height: var(--av-extra-small); height: var(--av-extra-small);
} }
img { img {
width: 100%; width: 100%;
height: 100%; height: 100%;

View File

@@ -13,7 +13,6 @@
&--alert { &--alert {
background-color: var(--bg-positive); background-color: var(--bg-positive);
& .text { color: white }
} }
&:empty { &:empty {

View File

@@ -6,18 +6,20 @@ import Text from '../text/Text';
import RawIcon from '../system-icons/RawIcon'; import RawIcon from '../system-icons/RawIcon';
import { blurOnBubbling } from './script'; import { blurOnBubbling } from './script';
function Button({ const Button = React.forwardRef(({
id, className, variant, iconSrc, id, className, variant, iconSrc,
type, onClick, children, disabled, type, onClick, children, disabled,
}) { }, ref) => {
const iconClass = (iconSrc === null) ? '' : `btn-${variant}--icon`; const iconClass = (iconSrc === null) ? '' : `btn-${variant}--icon`;
return ( return (
<button <button
ref={ref}
id={id === '' ? undefined : id} id={id === '' ? undefined : id}
className={`${className ? `${className} ` : ''}btn-${variant} ${iconClass} noselect`} className={`${className ? `${className} ` : ''}btn-${variant} ${iconClass} noselect`}
onMouseUp={(e) => blurOnBubbling(e, `.btn-${variant}`)} onMouseUp={(e) => blurOnBubbling(e, `.btn-${variant}`)}
onClick={onClick} onClick={onClick}
type={type === 'button' ? 'button' : 'submit'} // eslint-disable-next-line react/button-has-type
type={type}
disabled={disabled} disabled={disabled}
> >
{iconSrc !== null && <RawIcon size="small" src={iconSrc} />} {iconSrc !== null && <RawIcon size="small" src={iconSrc} />}
@@ -25,7 +27,7 @@ function Button({
{typeof children !== 'string' && children } {typeof children !== 'string' && children }
</button> </button>
); );
} });
Button.defaultProps = { Button.defaultProps = {
id: '', id: '',
@@ -42,7 +44,7 @@ Button.propTypes = {
className: PropTypes.string, className: PropTypes.string,
variant: PropTypes.oneOf(['surface', 'primary', 'positive', 'caution', 'danger']), variant: PropTypes.oneOf(['surface', 'primary', 'positive', 'caution', 'danger']),
iconSrc: PropTypes.string, iconSrc: PropTypes.string,
type: PropTypes.oneOf(['button', 'submit']), type: PropTypes.oneOf(['button', 'submit', 'reset']),
onClick: PropTypes.func, onClick: PropTypes.func,
children: PropTypes.node.isRequired, children: PropTypes.node.isRequired,
disabled: PropTypes.bool, disabled: PropTypes.bool,

View File

@@ -17,7 +17,8 @@ const IconButton = React.forwardRef(({
className={`ic-btn ic-btn-${variant}`} className={`ic-btn ic-btn-${variant}`}
onMouseUp={(e) => blurOnBubbling(e, `.ic-btn-${variant}`)} onMouseUp={(e) => blurOnBubbling(e, `.ic-btn-${variant}`)}
onClick={onClick} onClick={onClick}
type={type === 'button' ? 'button' : 'submit'} // eslint-disable-next-line react/button-has-type
type={type}
> >
<RawIcon size={size} src={src} /> <RawIcon size={size} src={src} />
</button> </button>
@@ -45,7 +46,7 @@ IconButton.defaultProps = {
IconButton.propTypes = { IconButton.propTypes = {
variant: PropTypes.oneOf(['surface', 'positive', 'caution', 'danger']), variant: PropTypes.oneOf(['surface', 'positive', 'caution', 'danger']),
size: PropTypes.oneOf(['normal', 'small', 'extra-small']), size: PropTypes.oneOf(['normal', 'small', 'extra-small']),
type: PropTypes.oneOf(['button', 'submit']), type: PropTypes.oneOf(['button', 'submit', 'reset']),
tooltip: PropTypes.string, tooltip: PropTypes.string,
tooltipPlacement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']), tooltipPlacement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
src: PropTypes.string.isRequired, src: PropTypes.string.isRequired,

View File

@@ -0,0 +1,37 @@
import React from 'react';
import PropTypes from 'prop-types';
import './Chip.scss';
import Text from '../text/Text';
import RawIcon from '../system-icons/RawIcon';
function Chip({
iconSrc, iconColor, text, children,
onClick,
}) {
return (
<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}
</button>
);
}
Chip.propTypes = {
iconSrc: PropTypes.string,
iconColor: PropTypes.string,
text: PropTypes.string,
children: PropTypes.element,
onClick: PropTypes.func,
};
Chip.defaultProps = {
iconSrc: null,
iconColor: null,
text: null,
children: null,
onClick: null,
};
export default Chip;

View File

@@ -0,0 +1,33 @@
.chip {
padding: var(--sp-ultra-tight) var(--sp-extra-tight);
display: inline-flex;
flex-direction: row;
align-items: center;
background: var(--bg-surface-low);
border-radius: var(--bo-radius);
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 {
width: 16px;
height: 16px;
margin-right: var(--sp-ultra-tight);
[dir=rtl] & {
margin-right: 0;
margin-left: var(--sp-ultra-tight);
}
}
}

View File

@@ -31,6 +31,7 @@ function ContextMenu({
interactive interactive
arrow={false} arrow={false}
maxWidth={maxWidth} maxWidth={maxWidth}
duration={200}
> >
{render(isVisible ? hideMenu : showMenu)} {render(isVisible ? hideMenu : showMenu)}
</Tippy> </Tippy>

View File

@@ -5,7 +5,7 @@ import './Input.scss';
import TextareaAutosize from 'react-autosize-textarea'; import TextareaAutosize from 'react-autosize-textarea';
function Input({ function Input({
id, label, value, placeholder, id, label, name, value, placeholder,
required, type, onChange, forwardRef, required, type, onChange, forwardRef,
resizable, minHeight, onResize, state, resizable, minHeight, onResize, state,
onKeyDown, onKeyDown,
@@ -17,6 +17,7 @@ function Input({
? ( ? (
<TextareaAutosize <TextareaAutosize
style={{ minHeight: `${minHeight}px` }} style={{ minHeight: `${minHeight}px` }}
name={name}
id={id} id={id}
className={`input input--resizable${state !== 'normal' ? ` input--${state}` : ''}`} className={`input input--resizable${state !== 'normal' ? ` input--${state}` : ''}`}
ref={forwardRef} ref={forwardRef}
@@ -33,6 +34,7 @@ function Input({
<input <input
ref={forwardRef} ref={forwardRef}
id={id} id={id}
name={name}
className={`input ${state !== 'normal' ? ` input--${state}` : ''}`} className={`input ${state !== 'normal' ? ` input--${state}` : ''}`}
type={type} type={type}
placeholder={placeholder} placeholder={placeholder}
@@ -49,6 +51,7 @@ function Input({
Input.defaultProps = { Input.defaultProps = {
id: null, id: null,
name: '',
label: '', label: '',
value: '', value: '',
placeholder: '', placeholder: '',
@@ -65,6 +68,7 @@ Input.defaultProps = {
Input.propTypes = { Input.propTypes = {
id: PropTypes.string, id: PropTypes.string,
name: PropTypes.string,
label: PropTypes.string, label: PropTypes.string,
value: PropTypes.string, value: PropTypes.string,
placeholder: PropTypes.string, placeholder: PropTypes.string,

View File

@@ -2,6 +2,7 @@
display: block; display: block;
width: 100%; width: 100%;
min-width: 0px; min-width: 0px;
margin: 0;
padding: var(--sp-tight) var(--sp-normal); padding: var(--sp-tight) var(--sp-normal);
background-color: var(--bg-surface-low); background-color: var(--bg-surface-low);
color: var(--tc-surface-normal); color: var(--tc-surface-normal);

View File

@@ -32,6 +32,7 @@
@mixin scroll { @mixin scroll {
overflow: hidden; overflow: hidden;
overscroll-behavior: none;
@extend .firefox-scrollbar; @extend .firefox-scrollbar;
@extend .webkit-scrollbar; @extend .webkit-scrollbar;
@extend .webkit-scrollbar-track; @extend .webkit-scrollbar-track;

View File

@@ -1,4 +1,4 @@
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import './SegmentedControls.scss'; import './SegmentedControls.scss';
@@ -17,6 +17,10 @@ function SegmentedControls({
onSelect(segmentIndex); onSelect(segmentIndex);
} }
useEffect(() => {
setSelect(selected);
}, [selected]);
return ( return (
<div className="segmented-controls"> <div className="segmented-controls">
{ {

View File

@@ -11,6 +11,10 @@
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
} }
& a {
line-height: 0;
}
} }
.file-container { .file-container {

View File

@@ -2,7 +2,7 @@ import React, { useRef } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import './Message.scss'; import './Message.scss';
import Linkify from 'linkifyjs/react'; import Linkify from 'linkify-react';
import ReactMarkdown from 'react-markdown'; import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm'; import gfm from 'remark-gfm';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';

View File

@@ -22,11 +22,12 @@
&__avatar-container { &__avatar-container {
padding-top: 6px; padding-top: 6px;
}
&__avatar-container{
margin-right: var(--sp-tight); margin-right: var(--sp-tight);
& button {
cursor: pointer;
}
[dir=rtl] & { [dir=rtl] & {
margin: { margin: {
left: var(--sp-tight); left: var(--sp-tight);
@@ -159,7 +160,7 @@
} }
& a { & a {
word-break: break-all; word-break: break-word;
} }
&-edited { &-edited {
color: var(--tc-surface-low); color: var(--tc-surface-low);
@@ -261,6 +262,16 @@
right: unset; right: unset;
} }
} }
@media (min-width: 1620px) {
.message__options {
right: unset;
left: 770px;
[dir=rtl] {
left: unset;
right: 770px
}
}
}
// markdown formating // markdown formating
.message__content { .message__content {

View File

@@ -2,8 +2,6 @@ import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import './TimelineChange.scss'; import './TimelineChange.scss';
// import Linkify from 'linkifyjs/react';
import Text from '../../atoms/text/Text'; import Text from '../../atoms/text/Text';
import RawIcon from '../../atoms/system-icons/RawIcon'; import RawIcon from '../../atoms/system-icons/RawIcon';

View File

@@ -2,7 +2,7 @@ import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import './RoomIntro.scss'; import './RoomIntro.scss';
import Linkify from 'linkifyjs/react'; import Linkify from 'linkify-react';
import colorMXID from '../../../util/colorMXID'; import colorMXID from '../../../util/colorMXID';
import Text from '../../atoms/text/Text'; import Text from '../../atoms/text/Text';
@@ -28,7 +28,7 @@ function RoomIntro({
} }
RoomIntro.defaultProps = { RoomIntro.defaultProps = {
avatarSrc: false, avatarSrc: null,
time: null, time: null,
}; };

View File

@@ -70,7 +70,7 @@
@extend .room-selector-flexItem; @extend .room-selector-flexItem;
margin: 0 var(--sp-extra-tight); margin: 0 var(--sp-extra-tight);
color: var(--tc-surface-normal); color: var(--tc-surface-normal-low);
overflow: hidden; overflow: hidden;
white-space: nowrap; white-space: nowrap;
text-overflow: ellipsis; text-overflow: ellipsis;

View File

@@ -2,7 +2,7 @@ import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import './RoomTile.scss'; import './RoomTile.scss';
import Linkify from 'linkifyjs/react'; import Linkify from 'linkify-react';
import colorMXID from '../../../util/colorMXID'; import colorMXID from '../../../util/colorMXID';
import Text from '../../atoms/text/Text'; import Text from '../../atoms/text/Text';

View 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;

View 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);
}
}
}

View File

@@ -5,6 +5,7 @@ import './CreateRoom.scss';
import initMatrix from '../../../client/initMatrix'; import initMatrix from '../../../client/initMatrix';
import { isRoomAliasAvailable } from '../../../util/matrixUtil'; import { isRoomAliasAvailable } from '../../../util/matrixUtil';
import * as roomActions from '../../../client/action/room'; import * as roomActions from '../../../client/action/room';
import { selectRoom } from '../../../client/action/navigation';
import Text from '../../atoms/text/Text'; import Text from '../../atoms/text/Text';
import Button from '../../atoms/button/Button'; import Button from '../../atoms/button/Button';
@@ -12,6 +13,7 @@ import Toggle from '../../atoms/button/Toggle';
import IconButton from '../../atoms/button/IconButton'; import IconButton from '../../atoms/button/IconButton';
import Input from '../../atoms/input/Input'; import Input from '../../atoms/input/Input';
import Spinner from '../../atoms/spinner/Spinner'; import Spinner from '../../atoms/spinner/Spinner';
import SegmentControl from '../../atoms/segmented-controls/SegmentedControls';
import PopupWindow from '../../molecules/popup-window/PopupWindow'; import PopupWindow from '../../molecules/popup-window/PopupWindow';
import SettingTile from '../../molecules/setting-tile/SettingTile'; import SettingTile from '../../molecules/setting-tile/SettingTile';
@@ -28,6 +30,7 @@ function CreateRoom({ isOpen, onRequestClose }) {
const [titleValue, updateTitleValue] = useState(undefined); const [titleValue, updateTitleValue] = useState(undefined);
const [topicValue, updateTopicValue] = useState(undefined); const [topicValue, updateTopicValue] = useState(undefined);
const [addressValue, updateAddressValue] = useState(undefined); const [addressValue, updateAddressValue] = useState(undefined);
const [roleIndex, setRoleIndex] = useState(0);
const addressRef = useRef(null); const addressRef = useRef(null);
const topicRef = useRef(null); const topicRef = useRef(null);
@@ -45,6 +48,7 @@ function CreateRoom({ isOpen, onRequestClose }) {
updateTitleValue(undefined); updateTitleValue(undefined);
updateTopicValue(undefined); updateTopicValue(undefined);
updateAddressValue(undefined); updateAddressValue(undefined);
setRoleIndex(0);
} }
async function createRoom() { async function createRoom() {
@@ -60,12 +64,15 @@ function CreateRoom({ isOpen, onRequestClose }) {
if (roomAlias.trim() === '') roomAlias = undefined; if (roomAlias.trim() === '') roomAlias = undefined;
} }
const powerLevel = roleIndex === 1 ? 101 : undefined;
try { try {
await roomActions.create({ const result = await roomActions.create({
name, topic, isPublic, roomAlias, isEncrypted, name, topic, isPublic, roomAlias, isEncrypted, powerLevel,
}); });
resetForm(); resetForm();
selectRoom(result.room_id);
onRequestClose(); onRequestClose();
} catch (e) { } catch (e) {
if (e.message === 'M_UNKNOWN: Invalid characters in room alias') { if (e.message === 'M_UNKNOWN: Invalid characters in room alias') {
@@ -139,6 +146,19 @@ function CreateRoom({ isOpen, onRequestClose }) {
content={<Text variant="b3">You cant disable this later. Bridges & most bots wont work yet.</Text>} content={<Text variant="b3">You cant disable this later. Bridges & most bots wont 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)" /> <Input value={topicValue} onChange={handleTopicChange} forwardRef={topicRef} minHeight={174} resizable label="Topic (optional)" />
<div className="create-room__name-wrapper"> <div className="create-room__name-wrapper">
<Input value={titleValue} onChange={handleTitleChange} forwardRef={nameRef} label="Room name" required /> <Input value={titleValue} onChange={handleTitleChange} forwardRef={nameRef} label="Room name" required />

View File

@@ -9,6 +9,13 @@
} }
} }
& .segment-btn {
padding: var(--sp-ultra-tight) 0;
&__base {
padding: 0 var(--sp-tight);
}
}
&__address { &__address {
display: flex; display: flex;
&__label { &__label {

View File

@@ -80,17 +80,17 @@ EmojiGroup.propTypes = {
}; };
const asyncSearch = new AsyncSearch(); const asyncSearch = new AsyncSearch();
asyncSearch.setup(emojis, { keys: ['shortcode'], limit: 30 }); asyncSearch.setup(emojis, { keys: ['shortcode'], isContain: true, limit: 40 });
function SearchedEmoji() { function SearchedEmoji() {
const [searchedEmojis, setSearchedEmojis] = useState(null); const [searchedEmojis, setSearchedEmojis] = useState(null);
function handleSearchEmoji(resultEmojis, term) { function handleSearchEmoji(resultEmojis, term) {
if (term === '' || resultEmojis.length === 0) { if (term === '' || resultEmojis.length === 0) {
if (term === '') setSearchedEmojis(null); if (term === '') setSearchedEmojis(null);
else setSearchedEmojis([]); else setSearchedEmojis({ emojis: [] });
return; return;
} }
setSearchedEmojis(resultEmojis); setSearchedEmojis({ emojis: resultEmojis });
} }
useEffect(() => { useEffect(() => {
@@ -102,7 +102,7 @@ function SearchedEmoji() {
if (searchedEmojis === null) return false; 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 }) { function EmojiBoard({ onSelect }) {

View File

@@ -5,6 +5,7 @@ import './InviteList.scss';
import initMatrix from '../../../client/initMatrix'; import initMatrix from '../../../client/initMatrix';
import cons from '../../../client/state/cons'; import cons from '../../../client/state/cons';
import * as roomActions from '../../../client/action/room'; import * as roomActions from '../../../client/action/room';
import { selectRoom, selectSpace } from '../../../client/action/navigation';
import Text from '../../atoms/text/Text'; import Text from '../../atoms/text/Text';
import Button from '../../atoms/button/Button'; import Button from '../../atoms/button/Button';
@@ -29,13 +30,18 @@ function InviteList({ isOpen, onRequestClose }) {
roomActions.leave(roomId, isDM); roomActions.leave(roomId, isDM);
} }
function updateInviteList(roomId) { function updateInviteList(roomId) {
if (procInvite.has(roomId)) { if (procInvite.has(roomId)) procInvite.delete(roomId);
procInvite.delete(roomId);
changeProcInvite(new Set(Array.from(procInvite))); changeProcInvite(new Set(Array.from(procInvite)));
} else changeProcInvite(new Set(Array.from(procInvite)));
const rl = initMatrix.roomList; 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(); if (totalInvites === 0) onRequestClose();
} }

View File

@@ -24,6 +24,28 @@ import PowerIC from '../../../../public/res/ic/outlined/power.svg';
function ProfileAvatarMenu() { function ProfileAvatarMenu() {
const mx = initMatrix.matrixClient; 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 ( return (
<ContextMenu <ContextMenu
@@ -45,10 +67,10 @@ function ProfileAvatarMenu() {
render={(toggleMenu) => ( render={(toggleMenu) => (
<SidebarAvatar <SidebarAvatar
onClick={toggleMenu} onClick={toggleMenu}
tooltip={mx.getUser(mx.getUserId()).displayName} tooltip={profile.displayName}
imageSrc={mx.getUser(mx.getUserId()).avatarUrl !== null ? mx.mxcUrlToHttp(mx.getUser(mx.getUserId()).avatarUrl, 42, 42, 'crop') : null} imageSrc={profile.avatarUrl !== null ? mx.mxcUrlToHttp(profile.avatarUrl, 42, 42, 'crop') : null}
bgColor={colorMXID(mx.getUserId())} 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; let noti = null;
orphans.forEach((roomId) => { orphans.forEach((roomId) => {
if (roomList.spaceShortcut.has(roomId)) return;
if (!notifications.hasNoti(roomId)) return; if (!notifications.hasNoti(roomId)) return;
if (noti === null) noti = { total: 0, highlight: 0 }; if (noti === null) noti = { total: 0, highlight: 0 };
const childNoti = notifications.getNoti(roomId); const childNoti = notifications.getNoti(roomId);

View File

@@ -1,4 +1,4 @@
import React, { useState, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import initMatrix from '../../../client/initMatrix'; import initMatrix from '../../../client/initMatrix';
@@ -17,11 +17,17 @@ function ProfileEditor({
const mx = initMatrix.matrixClient; const mx = initMatrix.matrixClient;
const displayNameRef = useRef(null); const displayNameRef = useRef(null);
const bgColor = colorMXID(userId); 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); const [disabled, setDisabled] = useState(true);
let username = mx.getUser(mx.getUserId()).displayName; 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 // Sets avatar URL and updates the avatar component in profile editor to reflect new upload
function handleAvatarUpload(url) { function handleAvatarUpload(url) {
if (url === null) { if (url === null) {

View 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;

View 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);
}
}
}
}

View File

@@ -139,14 +139,20 @@ function PublicRooms({ isOpen, searchTerm, onRequestClose }) {
updateIsViewMore(false); updateIsViewMore(false);
if (totalRooms.length === 0) { if (totalRooms.length === 0) {
updateSearchQuery({ updateSearchQuery({
error: `No result found for "${inputRoomName}" on ${inputHs}`, error: inputRoomName === ''
? `No public rooms on ${inputHs}`
: `No result found for "${inputRoomName}" on ${inputHs}`,
alias: isInputAlias ? inputRoomName : null, alias: isInputAlias ? inputRoomName : null,
}); });
} }
} catch (e) { } catch (e) {
updatePublicRooms([]); updatePublicRooms([]);
let err = 'Something went wrong!';
if (e?.httpStatus >= 400 && e?.httpStatus < 500) {
err = e.message;
}
updateSearchQuery({ updateSearchQuery({
error: 'Something went wrong!', error: err,
alias: isInputAlias ? inputRoomName : null, alias: isInputAlias ? inputRoomName : null,
}); });
updateIsSearching(false); updateIsSearching(false);

View File

@@ -1,11 +1,13 @@
import React from 'react'; import React from 'react';
import ReadReceipts from '../read-receipts/ReadReceipts'; import ReadReceipts from '../read-receipts/ReadReceipts';
import ProfileViewer from '../profile-viewer/ProfileViewer';
function Dialogs() { function Dialogs() {
return ( return (
<> <>
<ReadReceipts /> <ReadReceipts />
<ProfileViewer />
</> </>
); );
} }

View File

@@ -11,6 +11,7 @@ import PeopleSelector from '../../molecules/people-selector/PeopleSelector';
import Dialog from '../../molecules/dialog/Dialog'; import Dialog from '../../molecules/dialog/Dialog';
import CrossIC from '../../../../public/res/ic/outlined/cross.svg'; import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
import { openProfileViewer } from '../../../client/action/navigation';
function ReadReceipts() { function ReadReceipts() {
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
@@ -58,7 +59,10 @@ function ReadReceipts() {
return ( return (
<PeopleSelector <PeopleSelector
key={receipt.userId} 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')} avatarSrc={member?.getAvatarUrl(initMatrix.matrixClient.baseUrl, 24, 24, 'crop')}
name={getUserDisplayName(receipt.userId)} name={getUserDisplayName(receipt.userId)}
color={colorMXID(receipt.userId)} color={colorMXID(receipt.userId)}

View File

@@ -1,29 +1,29 @@
import React, { useState, useEffect } from 'react'; import React, {
useState, useEffect, useCallback, useRef,
} from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import './PeopleDrawer.scss'; import './PeopleDrawer.scss';
import initMatrix from '../../../client/initMatrix'; import initMatrix from '../../../client/initMatrix';
import { getUsernameOfRoomMember } from '../../../util/matrixUtil'; import { getPowerLabel, getUsernameOfRoomMember } from '../../../util/matrixUtil';
import colorMXID from '../../../util/colorMXID'; 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 Text from '../../atoms/text/Text';
import Header, { TitleWrapper } from '../../atoms/header/Header'; import Header, { TitleWrapper } from '../../atoms/header/Header';
import RawIcon from '../../atoms/system-icons/RawIcon';
import IconButton from '../../atoms/button/IconButton'; import IconButton from '../../atoms/button/IconButton';
import Button from '../../atoms/button/Button'; import Button from '../../atoms/button/Button';
import ScrollView from '../../atoms/scroll/ScrollView'; import ScrollView from '../../atoms/scroll/ScrollView';
import Input from '../../atoms/input/Input'; import Input from '../../atoms/input/Input';
import SegmentedControl from '../../atoms/segmented-controls/SegmentedControls';
import PeopleSelector from '../../molecules/people-selector/PeopleSelector'; import PeopleSelector from '../../molecules/people-selector/PeopleSelector';
import AddUserIC from '../../../../public/res/ic/outlined/add-user.svg'; 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) { function AtoZ(m1, m2) {
const aName = m1.name; const aName = m1.name;
const bName = m2.name; const bName = m2.name;
@@ -44,31 +44,102 @@ function sortByPowerLevel(m1, m2) {
if (pl1 < pl2) return 1; if (pl1 < pl2) return 1;
return 0; 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 }) { function PeopleDrawer({ roomId }) {
const PER_PAGE_MEMBER = 50; const PER_PAGE_MEMBER = 50;
const room = initMatrix.matrixClient.getRoom(roomId); const mx = initMatrix.matrixClient;
const totalMemberList = room.getJoinedMembers().sort(AtoZ).sort(sortByPowerLevel); const room = mx.getRoom(roomId);
const [memberList, updateMemberList] = useState([]);
let isRoomChanged = false; 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() { 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(() => { 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(() => { room.loadMembersIfNeeded().then(() => {
isGettingMembers = false;
if (isRoomChanged) return; if (isRoomChanged) return;
const newTotalMemberList = room.getJoinedMembers().sort(AtoZ).sort(sortByPowerLevel); updateMemberList();
updateMemberList(newTotalMemberList.slice(0, PER_PAGE_MEMBER));
}); });
asyncSearch.on(asyncSearch.RESULT_SENT, handleSearchData);
mx.on('RoomMember.membership', updateMemberList);
return () => { return () => {
isRoomChanged = true; 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]); }, [roomId]);
const mList = searchedMembers !== null ? searchedMembers.data : memberList.slice(0, itemCount);
return ( return (
<div className="people-drawer"> <div className="people-drawer">
<Header> <Header>
@@ -84,21 +155,53 @@ function PeopleDrawer({ roomId }) {
<div className="people-drawer__scrollable"> <div className="people-drawer__scrollable">
<ScrollView autoHide> <ScrollView autoHide>
<div className="people-drawer__content"> <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 <PeopleSelector
key={member.userId} key={member.userId}
onClick={() => alert('Viewing profile is yet to be implemented')} onClick={() => openProfileViewer(member.userId, roomId)}
avatarSrc={member.getAvatarUrl(initMatrix.matrixClient.baseUrl, 24, 24, 'crop')} avatarSrc={member.avatarSrc}
name={getUsernameOfRoomMember(member)} name={member.name}
color={colorMXID(member.userId)} 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"> <div className="people-drawer__load-more">
{ {
memberList.length !== totalMemberList.length && ( mList.length !== 0
&& memberList.length > itemCount
&& searchedMembers === null
&& (
<Button onClick={loadMorePeople}>View more</Button> <Button onClick={loadMorePeople}>View more</Button>
) )
} }
@@ -108,7 +211,12 @@ function PeopleDrawer({ roomId }) {
</div> </div>
<div className="people-drawer__sticky"> <div className="people-drawer__sticky">
<form onSubmit={(e) => e.preventDefault()} className="people-search"> <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> </form>
</div> </div>
</div> </div>

View File

@@ -35,19 +35,48 @@
@extend .people-drawer-flexItem; @extend .people-drawer-flexItem;
} }
&__sticky { &__noresult {
display: none; padding: var(--sp-extra-tight) var(--sp-normal);
text-align: center;
}
&__sticky {
& .people-search { & .people-search {
min-height: 48px; --search-input-height: 40px;
min-height: var(--search-input-height);
margin: 0 var(--sp-normal); margin: 0 var(--sp-normal);
position: relative; position: relative;
bottom: var(--sp-normal); 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 { & .input {
height: 48px; padding: 0 calc(var(--sp-loose) + var(--sp-normal));
height: var(--search-input-height);
} }
} }
} }
@@ -55,7 +84,21 @@
.people-drawer__content { .people-drawer__content {
padding-top: var(--sp-extra-tight); 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 { .people-drawer__load-more {
padding: var(--sp-normal); padding: var(--sp-normal);

View File

@@ -319,6 +319,7 @@ function RoomViewCmdBar({ roomId, roomTimeline, viewEvent }) {
else if (searchTerm.match(/^[-]?(\()$/)) searchTerm = 'pleading_face'; else if (searchTerm.match(/^[-]?(\()$/)) searchTerm = 'pleading_face';
else if (searchTerm.match(/^[-]?(\$)$/)) searchTerm = 'money'; else if (searchTerm.match(/^[-]?(\$)$/)) searchTerm = 'money';
else if (searchTerm.match(/^(<3)$/)) searchTerm = 'heart'; 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.spaces]), { keys: ['name'], limit: 20 }),
'>#': () => asyncSearch.setup(getRooms([...roomList.rooms]), { keys: ['name'], limit: 20 }), '>#': () => asyncSearch.setup(getRooms([...roomList.rooms]), { keys: ['name'], limit: 20 }),
'>@': () => asyncSearch.setup(getRooms([...roomList.directs]), { 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) => ({ '@': () => asyncSearch.setup(matrixClient.getRoom(roomId).getJoinedMembers().map((member) => ({
name: member.name, name: member.name,
userId: member.userId.slice(1), userId: member.userId.slice(1),

View File

@@ -11,7 +11,7 @@ import { redactEvent, sendReaction } from '../../../client/action/roomTimeline';
import { getUsername, getUsernameOfRoomMember, doesRoomHaveUnread } from '../../../util/matrixUtil'; import { getUsername, getUsernameOfRoomMember, doesRoomHaveUnread } from '../../../util/matrixUtil';
import colorMXID from '../../../util/colorMXID'; import colorMXID from '../../../util/colorMXID';
import { diffMinutes, isNotInSameDay, getEventCords } from '../../../util/common'; 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 Divider from '../../atoms/divider/Divider';
import Avatar from '../../atoms/avatar/Avatar'; import Avatar from '../../atoms/avatar/Avatar';
@@ -353,12 +353,14 @@ function RoomViewContent({
const senderMXIDColor = colorMXID(mEvent.sender.userId); const senderMXIDColor = colorMXID(mEvent.sender.userId);
const userAvatar = isContentOnly ? null : ( const userAvatar = isContentOnly ? null : (
<button type="button" onClick={() => openProfileViewer(mEvent.sender.userId, roomId)}>
<Avatar <Avatar
imageSrc={mEvent.sender.getAvatarUrl(initMatrix.matrixClient.baseUrl, 36, 36, 'crop')} imageSrc={mEvent.sender.getAvatarUrl(initMatrix.matrixClient.baseUrl, 36, 36, 'crop')}
text={getUsernameOfRoomMember(mEvent.sender).slice(0, 1)} text={getUsernameOfRoomMember(mEvent.sender).slice(0, 1)}
bgColor={senderMXIDColor} bgColor={senderMXIDColor}
size="small" size="small"
/> />
</button>
); );
const userHeader = isContentOnly ? null : ( const userHeader = isContentOnly ? null : (
<MessageHeader <MessageHeader

View File

@@ -54,7 +54,7 @@ function RoomViewFloating({
return ( return (
<> <>
<div className={`room-view__typing${isSomeoneTyping(typingMembers) ? ' room-view__typing--open' : ''}`}> <div className={`room-view__typing${isSomeoneTyping(typingMembers) ? ' room-view__typing--open' : ''}`}>
<div className="bouncingLoader"><div /></div> <div className="bouncing-loader"><div /></div>
<Text variant="b2">{getTypingMessage(typingMembers)}</Text> <Text variant="b2">{getTypingMessage(typingMembers)}</Text>
</div> </div>
<div className={`room-view__STB${reachedBottom ? '' : ' room-view__STB--open'}`}> <div className={`room-view__STB${reachedBottom ? '' : ' room-view__STB--open'}`}>

View File

@@ -9,10 +9,6 @@
color: var(--tc-surface-high); color: var(--tc-surface-high);
} }
&--open {
transform: translateY(-99%);
}
& .text { & .text {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
@@ -22,37 +18,48 @@
text-overflow: ellipsis; text-overflow: ellipsis;
margin: 0 var(--sp-tight); margin: 0 var(--sp-tight);
} }
&--open {
transform: translateY(-99%);
& .bouncing-loader {
& > *,
&::after,
&::before {
animation: bouncing-loader 0.6s infinite alternate;
}
}
}
} }
.bouncingLoader { .bouncing-loader {
transform: translateY(2px); transform: translateY(2px);
margin: 0 calc(var(--sp-ultra-tight) / 2); margin: 0 calc(var(--sp-ultra-tight) / 2);
} }
.bouncingLoader > div, .bouncing-loader > div,
.bouncingLoader:before, .bouncing-loader::before,
.bouncingLoader:after { .bouncing-loader::after {
display: inline-block; display: inline-block;
width: 8px; width: 8px;
height: 8px; height: 8px;
background: var(--tc-surface-high); background: var(--tc-surface-high);
border-radius: 50%; border-radius: 50%;
animation: bouncing-loader 0.6s infinite alternate;
} }
.bouncingLoader:before,
.bouncingLoader:after { .bouncing-loader::before,
.bouncing-loader::after {
content: ""; content: "";
} }
.bouncingLoader > div { .bouncing-loader > div {
margin: 0 4px; margin: 0 4px;
} }
.bouncingLoader > div { .bouncing-loader > div {
animation-delay: 0.2s; animation-delay: 0.2s;
} }
.bouncingLoader:after { .bouncing-loader::after {
animation-delay: 0.4s; animation-delay: 0.4s;
} }

View File

@@ -29,7 +29,7 @@ import MarkdownIC from '../../../../public/res/ic/outlined/markdown.svg';
import FileIC from '../../../../public/res/ic/outlined/file.svg'; import FileIC from '../../../../public/res/ic/outlined/file.svg';
import CrossIC from '../../../../public/res/ic/outlined/cross.svg'; import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
const CMD_REGEX = /(\/|>[#*@]|:|@)(\S*)$/; const CMD_REGEX = /(^\/|^>[#*@]|:|@)(\S*)$/;
let isTyping = false; let isTyping = false;
let isCmdActivated = false; let isCmdActivated = false;
let cmdCursorPos = null; let cmdCursorPos = null;
@@ -313,6 +313,7 @@ function RoomViewInput({
function addEmoji(emoji) { function addEmoji(emoji) {
textAreaRef.current.value += emoji.unicode; textAreaRef.current.value += emoji.unicode;
textAreaRef.current.focus();
} }
function handleUploadClick() { function handleUploadClick() {
@@ -327,7 +328,14 @@ function RoomViewInput({
if (file !== null) roomsInput.setAttachment(roomId, file); if (file !== null) roomsInput.setAttachment(roomId, file);
} }
const canISend = roomTimeline.room.currentState.maySendMessage(mx.getUserId());
function renderInputs() { function renderInputs() {
if (!canISend) {
return (
<Text className="room-input__disallowed">You do not have permission to post to this room</Text>
);
}
return ( return (
<> <>
<div className={`room-input__option-container${attachment === null ? '' : ' room-attachment__option'}`}> <div className={`room-input__option-container${attachment === null ? '' : ' room-attachment__option'}`}>

View File

@@ -3,6 +3,11 @@
display: flex; display: flex;
min-height: 48px; min-height: 48px;
&__disallowed {
flex: 1;
text-align: center;
}
&__space { &__space {
min-width: 0; min-width: 0;
align-self: center; align-self: center;

View File

@@ -3,6 +3,7 @@ import PropTypes from 'prop-types';
import './Settings.scss'; import './Settings.scss';
import initMatrix from '../../../client/initMatrix'; import initMatrix from '../../../client/initMatrix';
import cons from '../../../client/state/cons';
import settings from '../../../client/state/settings'; import settings from '../../../client/state/settings';
import { toggleMarkdown } from '../../../client/action/settings'; import { toggleMarkdown } from '../../../client/action/settings';
@@ -104,13 +105,13 @@ function AboutSection() {
<div> <div>
<Text variant="h2"> <Text variant="h2">
Cinny Cinny
<span className="text text-b3" style={{ margin: '0 var(--sp-extra-tight)' }}>v1.3.0</span> <span className="text text-b3" style={{ margin: '0 var(--sp-extra-tight)' }}>{`v${cons.version}`}</span>
</Text> </Text>
<Text>Yet another matrix client</Text> <Text>Yet another matrix client</Text>
<div className="set-about__btns"> <div className="set-about__btns">
<Button onClick={() => window.open('https://github.com/ajbura/cinny')}>Source code</Button> <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> </div>
</div> </div>

View File

@@ -1,9 +1,9 @@
import React from 'react'; import React from 'react';
import { import {
BrowserRouter, Switch, Route, Redirect, BrowserRouter,
} from 'react-router-dom'; } from 'react-router-dom';
import { isAuthanticated } from '../../client/state/auth'; import { isAuthenticated } from '../../client/state/auth';
import Auth from '../templates/auth/Auth'; import Auth from '../templates/auth/Auth';
import Client from '../templates/client/Client'; import Client from '../templates/client/Client';
@@ -11,17 +11,7 @@ import Client from '../templates/client/Client';
function App() { function App() {
return ( return (
<BrowserRouter> <BrowserRouter>
<Switch> { isAuthenticated() ? <Client /> : <Auth />}
<Route exact path="/">
{ isAuthanticated() ? <Client /> : <Redirect to="/login" />}
</Route>
<Route path="/login">
{ isAuthanticated() ? <Redirect to="/" /> : <Auth type="login" />}
</Route>
<Route path="/register">
{ isAuthanticated() ? <Redirect to="/" /> : <Auth type="register" />}
</Route>
</Switch>
</BrowserRouter> </BrowserRouter>
); );
} }

View File

@@ -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 PropTypes from 'prop-types';
import './Auth.scss'; import './Auth.scss';
import ReCAPTCHA from 'react-google-recaptcha'; import ReCAPTCHA from 'react-google-recaptcha';
import { Formik } from 'formik';
import { Link } from 'react-router-dom';
import * as auth from '../../../client/action/auth'; 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 Text from '../../atoms/text/Text';
import Button from '../../atoms/button/Button'; import Button from '../../atoms/button/Button';
@@ -12,308 +16,556 @@ import IconButton from '../../atoms/button/IconButton';
import Input from '../../atoms/input/Input'; import Input from '../../atoms/input/Input';
import Spinner from '../../atoms/spinner/Spinner'; import Spinner from '../../atoms/spinner/Spinner';
import ScrollView from '../../atoms/scroll/ScrollView'; 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 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 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 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 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 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'; const BAD_EMAIL_ERROR = 'Invalid email address';
function isValidInput(value, regex) { function isValidInput(value, regex) {
if (typeof regex === 'string') return regex === value;
return regex.test(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) {
renderErrorMessage(error);
$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(e, regex, error) {
if (!isValidInput(e.target.value, regex) && e.target.value) {
showBadInputError(e.target, error);
return;
}
document.getElementById('auth_error').style.display = 'none';
e.target.style.removeProperty('border');
e.target.style.removeProperty('box-shadow');
document.getElementById('auth_submit-btn').disabled = false;
}
/**
* 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) { function normalizeUsername(rawUsername) {
const noLeadingAt = rawUsername.indexOf('@') === 0 ? rawUsername.substr(1) : rawUsername; const noLeadingAt = rawUsername.indexOf('@') === 0 ? rawUsername.substr(1) : rawUsername;
return noLeadingAt.trim(); return noLeadingAt.trim();
} }
function Auth({ type }) { let searchingHs = null;
const [process, changeProcess] = useState(null); function Homeserver({ onChange }) {
const usernameRef = useRef(null); const [hs, setHs] = useState(null);
const homeserverRef = useRef(null); const [debounce] = useState(new Debounce());
const passwordRef = useRef(null); const [process, setProcess] = useState({ isLoading: true, message: 'Loading homeserver list...' });
const confirmPasswordRef = useRef(null); const hsRef = useRef();
const emailRef = useRef(null);
function register(recaptchaValue, terms, verified) { const setupHsConfig = async (servername) => {
auth.register( setProcess({ isLoading: true, message: 'Looking for homeserver...' });
usernameRef.current.value, let baseUrl = null;
homeserverRef.current.value, try {
passwordRef.current.value, baseUrl = await getBaseUrl(servername);
emailRef.current.value, } catch (e) {
recaptchaValue, baseUrl = e.message;
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') { if (searchingHs !== servername) return;
changeProcess({ type: res.type, en: res.en }); setProcess({ isLoading: true, message: `Connecting to ${baseUrl}...` });
} const tempClient = auth.createTemporaryClient(baseUrl);
if (res.type === 'email') {
changeProcess({ type: res.type }); Promise.allSettled([tempClient.loginFlows(), tempClient.register()])
} .then((values) => {
if (res.type === 'done') { const loginFlow = values[0].status === 'fulfilled' ? values[0]?.value : undefined;
window.location.replace('/'); const registerFlow = values[1].status === 'rejected' ? values[1]?.reason?.data : undefined;
} if (loginFlow === undefined || registerFlow === undefined) throw new Error();
}).catch((error) => {
changeProcess(null); if (searchingHs !== servername) return;
renderErrorMessage(error); onChange({ baseUrl, login: loginFlow, register: registerFlow });
document.getElementById('auth_submit-btn').disabled = false; setProcess({ isLoading: false });
}).catch(() => {
if (searchingHs !== servername) return;
onChange(null);
setProcess({ isLoading: false, error: 'Unable to connect. Please check your input.' });
}); });
if (terms) { };
changeProcess({ type: 'loading', message: 'Sending email verification link...' });
} else changeProcess({ type: 'loading', message: 'Registration in progress...' });
}
function handleLogin(e) { useEffect(() => {
e.preventDefault(); onChange(null);
document.getElementById('auth_submit-btn').disabled = true; if (hs === null || hs?.selected.trim() === '') return;
document.getElementById('auth_error').style.display = 'none'; searchingHs = hs.selected;
setupHsConfig(hs.selected);
}, [hs]);
/** @type {string} */ useEffect(async () => {
const rawUsername = usernameRef.current.value; const link = window.location.href;
/** @type {string} */ const configFileUrl = `${link}${link[link.length - 1] === '/' ? '' : '/'}config.json`;
const normalizedUsername = normalizeUsername(rawUsername); 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'] });
}
}, []);
auth.login(normalizedUsername, homeserverRef.current.value, passwordRef.current.value) const handleHsInput = (e) => {
.then(() => { const { value } = e.target;
document.getElementById('auth_submit-btn').disabled = false; setProcess({ isLoading: false });
window.location.replace('/'); debounce._(async () => {
}) setHs({ selected: value, list: hs.list });
.catch((error) => { }, 700)();
changeProcess(null); };
renderErrorMessage(error);
document.getElementById('auth_submit-btn').disabled = false;
});
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';
if (!isValidInput(usernameRef.current.value, LOCALPART_SIGNUP_REGEX)) {
showBadInputError(usernameRef.current, BAD_LOCALPART_ERROR);
return;
}
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 handleAuth = (type === 'login') ? handleLogin : handleRegister;
return ( return (
<> <>
{process?.type === 'loading' && <LoadingScreen message={process.message} />} <div className="homeserver-form">
{process?.type === 'recaptcha' && <Recaptcha message="Please check the box below to proceed." sitekey={process.sitekey} onChange={(v) => { if (typeof v === 'string') register(v); }} />} <Input name="homeserver" onChange={handleHsInput} value={hs?.selected} forwardRef={hsRef} label="Homeserver" />
{process?.type === 'terms' && <Terms url={process.en.url} onSubmit={register} />} <ContextMenu
{process?.type === 'email' && ( placement="right"
<ProcessWrapper> content={(hideMenu) => (
<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, LOCALPART_LOGIN_REGEX, BAD_LOCALPART_ERROR)
: validateOnChange(e, 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) => validateOnChange(e, ((type === 'login') ? PASSWORD_REGEX : PASSWORD_STRENGHT_REGEX), BAD_PASSWORD_ERROR)}
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"> <MenuHeader>Homeserver list</MenuHeader>
<Input {
forwardRef={confirmPasswordRef} hs?.list.map((hsName) => (
onChange={(e) => validateOnChange(e, new RegExp(`^(${passwordRef.current.value})$`), CONFIRM_PASSWORD_ERROR)} <MenuItem
id="auth_confirmPassword" key={hsName}
type="password"
label="Confirm password"
required
/>
<IconButton
onClick={() => { onClick={() => {
if (confirmPasswordRef.current.type === 'password') { hideMenu();
confirmPasswordRef.current.type = 'text'; hsRef.current.value = hsName;
} else confirmPasswordRef.current.type = 'password'; setHs({ selected: hsName, list: hs.list });
}} }}
size="extra-small" >
src={EyeIC} {hsName}
/> </MenuItem>
</div> ))
<Input }
forwardRef={emailRef}
onChange={(e) => validateOnChange(e, EMAIL_REGEX, BAD_EMAIL_ERROR)}
id="auth_email"
type="email"
label="Email"
required
/>
</> </>
)} )}
<div className="submit-btn__wrapper flex--end"> render={(toggleMenu) => <IconButton onClick={toggleMenu} src={ChevronBottomIC} />}
<Text id="auth_error" className="error-message" variant="b3">Error</Text> />
<Button </div>
id="auth_submit-btn" {process.error !== undefined && <Text className="homeserver-form__error" variant="b3">{process.error}</Text>}
variant="primary" {process.isLoading && (
type="submit" <div className="homeserver-form__status flex--center">
<Spinner size="small" />
<Text variant="b2">{process.message}</Text>
</div>
)}
</>
);
}
Homeserver.propTypes = {
onChange: PropTypes.func.isRequired,
};
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 === 'login' ? 'Login' : 'Register' } {type}
</MenuItem>
))
)}
render={(toggleMenu) => (
<Button onClick={toggleMenu} iconSrc={ChevronBottomIC}>
{loginTypes[typeIndex]}
</Button> </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> </div>
</form> </form>
</div> </>
)}
</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,
};
<div className="flex--center"> let sid;
<Text variant="b2"> let clientSecret;
{`${(type === 'login' ? 'Don\'t have' : 'Already have')} an account?`} function Register({ registerInfo, loginFlow, baseUrl }) {
<Link to={type === 'login' ? '/register' : '/login'}> const [process, setProcess] = useState({});
{ type === 'login' ? ' Register' : ' Login' } const formRef = useRef();
</Link>
</Text> 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> </div>
</StaticWrapper> {!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 = { function Auth() {
type: PropTypes.string.isRequired, 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 ( return (
<ScrollView invisible> <ScrollView invisible>
<div className="auth__wrapper flex--center"> <div className="auth__base">
<div className="auth-card"> <div className="auth__wrapper">
<div className="auth-card__interactive flex-v"> {loginToken && <LoadingScreen message="Redirecting..." />}
<div className="app-ident flex"> {!loginToken && (
<img className="app-ident__logo noselect" src={CinnySvg} alt="Cinny logo" /> <div className="auth-card flex-v">
<div className="app-ident__text flex-v--center"> <Header>
<Avatar size="extra-small" imageSrc={CinnySvg} />
<TitleWrapper>
<Text variant="h2">Cinny</Text> <Text variant="h2">Cinny</Text>
<Text variant="b2">Yet another matrix client</Text> </TitleWrapper>
</Header>
<div className="auth-card__content">
<AuthCard />
</div> </div>
</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>
</div> </div>
</ScrollView> </ScrollView>
); );
} }
StaticWrapper.propTypes = {
children: PropTypes.node.isRequired,
};
function LoadingScreen({ message }) { function LoadingScreen({ message }) {
return ( return (
<ProcessWrapper> <ProcessWrapper>
@@ -347,7 +599,7 @@ Recaptcha.propTypes = {
function Terms({ url, onSubmit }) { function Terms({ url, onSubmit }) {
return ( return (
<ProcessWrapper> <ProcessWrapper>
<form onSubmit={() => onSubmit(undefined, true)}> <form onSubmit={(e) => { e.preventDefault(); onSubmit(); }}>
<div style={{ margin: 'var(--sp-normal)', maxWidth: '450px' }}> <div style={{ margin: 'var(--sp-normal)', maxWidth: '450px' }}>
<Text variant="h2">Agree with terms</Text> <Text variant="h2">Agree with terms</Text>
<div style={{ marginBottom: 'var(--sp-normal)' }} /> <div style={{ marginBottom: 'var(--sp-normal)' }} />
@@ -370,6 +622,27 @@ Terms.propTypes = {
onSubmit: PropTypes.func.isRequired, 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 }) { function ProcessWrapper({ children }) {
return ( return (
<div className="process-wrapper"> <div className="process-wrapper">

View File

@@ -1,156 +1,144 @@
.auth__wrapper { .auth__base {
--pattern-size: 48px;
min-height: 100vh; min-height: 100vh;
background-color: var(--bg-surface-low);
background-image: radial-gradient(rgba(0, 0, 0, 6%) 2px, rgba(0, 0, 0, 0%) 2px);
background-size: var(--pattern-size) var(--pattern-size);
display: flex;
flex-direction: column;
}
.auth__wrapper {
flex: 1;
padding: var(--sp-loose); padding: var(--sp-loose);
background-color: var(--bg-surface-low); 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;
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"); & > *:nth-child(2n) {
background-size: cover; margin: 0 var(--sp-loose);
background-repeat: no-repeat; }
background-position: center; & a {
color: var(--tc-surface-normal);
.auth-card { &:hover { text-decoration: underline; }
}
}
.auth-card {
width: 462px; width: 462px;
min-height: 644px; background-color: var(--bg-surface);
background-color: var(--bg-surface-low);
border-radius: var(--bo-radius); border-radius: var(--bo-radius);
box-shadow: var(--bs-popup); box-shadow: var(--bs-popup);
overflow: hidden; overflow: hidden;
display: flex;
flex-flow: row nowrap;
&__interactive{ &__content {
flex: 1; padding: var(--sp-extra-loose) calc(var(--sp-normal) + var(--sp-extra-loose));
min-width: 0;
} }
&__switch {
&__interactive { margin-top: var(--sp-loose) !important;
padding: calc(var(--sp-normal) + var(--sp-extra-loose));
padding-bottom: var(--sp-extra-loose);
background-color: var(--bg-surface);
}
} }
} }
.app-ident { .homeserver-form,
margin-bottom: var(--sp-extra-loose); .auth-form__heading {
& .context-menu .btn-surface .ic-raw {
&__logo { width: 0;
width: 60px;
height: 60px;
} }
&__text { }
margin-left: calc(var(--sp-loose) + var(--sp-ultra-tight));
.text-s1 { .homeserver-form {
margin-top: var(--sp-tight); display: flex;
color: var(--tc-surface-normal); 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] & { [dir=rtl] & {
margin-left: 0; & .input {
margin-right: calc(var(--sp-loose) + var(--sp-ultra-tight)); 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);
}
}
&__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 { .auth-form {
& > .text {
margin-bottom: var(--sp-loose);
margin-top: var(--sp-loose);
}
& > .input-container { & > .input-container {
margin-top: var(--sp-tight); margin: var(--sp-tight) 0 var(--sp-ultra-tight);
} }
.submit-btn__wrapper { &__heading {
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);
}
}
}
}
&__wrapper {
height: 100%;
}
}
.username__wrapper {
display: flex; display: flex;
align-items: flex-end; justify-content: space-between;
margin-top: calc(var(--sp-extra-loose) + var(--sp-tight));
& > :first-child {
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 { &__btns {
border-left-width: 0; padding-top: var(--sp-loose);
background-color: var(--bg-surface); margin-bottom: var(--sp-extra-loose);
border-radius: 0 var(--bo-radius) var(--bo-radius) 0; display: flex;
justify-content: flex-end;
}
[dir=rtl] & { &__error {
border-left-width: 1px; color: var(--tc-danger-normal) !important;
border-right-width: 0;
border-radius: var(--bo-radius) 0 0 var(--bo-radius);
}
}
} }
} }
.sso__divider {
margin-bottom: var(--sp-tight);
display: flex;
align-items: center;
.password__wrapper { &::before,
margin-top: var(--sp-tight); &::after {
position: relative; flex: 1;
content: '';
& .ic-btn { margin: var(--sp-tight);
position: absolute; border-bottom: 1px solid var(--bg-surface-border);
right: 6px;
bottom: 6px;
border-radius: calc(var(--bo-radius) / 2);
[dir=rtl] & {
left: 6px;
right: unset;
}
} }
} }
@media (max-width: 462px) { @media (max-width: 462px) {
.auth__wrapper { .auth__wrapper {
padding: 0; padding: var(--sp-tight);
background-image: none;
background-color: var(--bg-surface);
.auth-card {
border-radius: 0;
box-shadow: none;
&__interactive {
padding: var(--sp-extra-loose);
} }
.auth-card {
&__content {
padding: var(--sp-loose) var(--sp-normal);
} }
} }
} }

View File

@@ -9,14 +9,31 @@ import Windows from '../../organisms/pw/Windows';
import Dialogs from '../../organisms/pw/Dialogs'; import Dialogs from '../../organisms/pw/Dialogs';
import EmojiBoardOpener from '../../organisms/emoji-board/EmojiBoardOpener'; import EmojiBoardOpener from '../../organisms/emoji-board/EmojiBoardOpener';
import RoomOptions from '../../organisms/room-optons/RoomOptions'; import RoomOptions from '../../organisms/room-optons/RoomOptions';
import logout from '../../../client/action/logout';
import initMatrix from '../../../client/initMatrix'; import initMatrix from '../../../client/initMatrix';
function Client() { function Client() {
const [isLoading, changeLoading] = useState(true); const [isLoading, changeLoading] = useState(true);
const [loadingMsg, setLoadingMsg] = useState('Heating up');
useEffect(() => { 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', () => { initMatrix.once('init_loading_finished', () => {
clearInterval(iId);
changeLoading(false); changeLoading(false);
}); });
initMatrix.init(); initMatrix.init();
@@ -25,8 +42,11 @@ function Client() {
if (isLoading) { if (isLoading) {
return ( return (
<div className="loading-display"> <div className="loading-display">
<button className="loading__logout" onClick={logout} type="button">
<Text variant="b3">Logout</Text>
</button>
<Spinner /> <Spinner />
<Text className="loading__message" variant="b2">Heating up</Text> <Text className="loading__message" variant="b2">{loadingMsg}</Text>
<div className="loading__appname"> <div className="loading__appname">
<Text variant="h2">Cinny</Text> <Text variant="h2">Cinny</Text>

View File

@@ -27,8 +27,19 @@
} }
.loading__message { .loading__message {
margin-top: var(--sp-normal); margin-top: var(--sp-normal);
max-width: 350px;
text-align: center;
} }
.loading__appname { .loading__appname {
position: absolute; position: absolute;
bottom: var(--sp-normal); 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);
}
}

View File

@@ -1,55 +1,64 @@
import * as sdk from 'matrix-js-sdk'; import * as sdk from 'matrix-js-sdk';
import cons from '../state/cons'; import cons from '../state/cons';
import { getBaseUrl } from '../../util/matrixUtil';
async function login(username, homeserver, password) { function updateLocalStore(accessToken, deviceId, userId, baseUrl) {
let baseUrl = null; localStorage.setItem(cons.secretKey.ACCESS_TOKEN, accessToken);
try { localStorage.setItem(cons.secretKey.DEVICE_ID, deviceId);
baseUrl = await getBaseUrl(homeserver); localStorage.setItem(cons.secretKey.USER_ID, userId);
} catch (e) { localStorage.setItem(cons.secretKey.BASE_URL, baseUrl);
baseUrl = `https://${homeserver}`; }
}
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', { async function login(baseUrl, username, email, password) {
identifier: { const identifier = {};
type: 'm.id.user', if (username) {
user: 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, password,
initial_device_display_name: cons.DEVICE_DISPLAY_NAME, initial_device_display_name: cons.DEVICE_DISPLAY_NAME,
}); });
localStorage.setItem(cons.secretKey.ACCESS_TOKEN, response.access_token); const myBaseUrl = res?.well_known?.['m.homeserver']?.base_url || client.baseUrl;
localStorage.setItem(cons.secretKey.DEVICE_ID, response.device_id); updateLocalStore(res.access_token, res.device_id, res.user_id, myBaseUrl);
localStorage.setItem(cons.secretKey.USER_ID, response.user_id);
localStorage.setItem(cons.secretKey.BASE_URL, response?.well_known?.['m.homeserver']?.base_url || baseUrl);
} }
async function getAdditionalInfo(baseUrl, content) { async function loginWithToken(baseUrl, token) {
try { const client = createTemporaryClient(baseUrl);
const res = await fetch(`${baseUrl}/_matrix/client/r0/register`, {
method: 'POST', const res = await client.login('m.login.token', {
body: JSON.stringify(content), token,
headers: { initial_device_display_name: cons.DEVICE_DISPLAY_NAME,
'Content-Type': 'application/json; charset=utf-8',
},
credentials: 'same-origin',
}); });
const data = await res.json();
return data; const myBaseUrl = res?.well_known?.['m.homeserver']?.base_url || client.baseUrl;
} catch (e) { updateLocalStore(res.access_token, res.device_id, res.user_id, myBaseUrl);
throw new Error(e);
}
} }
async function verifyEmail(baseUrl, content) {
try { // 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`, { const res = await fetch(`${baseUrl}/_matrix/client/r0/register/email/requestToken`, {
method: 'POST', method: 'POST',
body: JSON.stringify(content), body: JSON.stringify({
email, client_secret, send_attempt, next_link,
}),
headers: { headers: {
'Content-Type': 'application/json; charset=utf-8', 'Content-Type': 'application/json; charset=utf-8',
}, },
@@ -57,96 +66,36 @@ async function verifyEmail(baseUrl, content) {
}); });
const data = await res.json(); const data = await res.json();
return data; 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) { } catch (e) {
throw new Error(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;
} }
} }
let session = null; export {
let clientSecret = null; createTemporaryClient, login, verifyEmail,
let sid = null; loginWithToken, startSsoLogin,
async function register(username, homeserver, password, email, recaptchaValue, terms, verified) { completeRegisterStage,
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 },
});
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 {};
}
export { login, register };

View File

@@ -2,6 +2,7 @@ import initMatrix from '../initMatrix';
function logout() { function logout() {
const mx = initMatrix.matrixClient; const mx = initMatrix.matrixClient;
mx.stopClient();
mx.logout().then(() => { mx.logout().then(() => {
mx.clearStores(); mx.clearStores();
window.localStorage.clear(); window.localStorage.clear();

View File

@@ -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() { function openSettings() {
appDispatcher.dispatch({ appDispatcher.dispatch({
type: cons.actions.navigation.OPEN_SETTINGS, type: cons.actions.navigation.OPEN_SETTINGS,
@@ -94,6 +102,7 @@ export {
openPublicRooms, openPublicRooms,
openCreateRoom, openCreateRoom,
openInviteUser, openInviteUser,
openProfileViewer,
openSettings, openSettings,
openEmojiBoard, openEmojiBoard,
openReadReceipts, openReadReceipts,

View File

@@ -132,9 +132,11 @@ function leave(roomId) {
* @param {boolean} [opts.isEncrypted=false] Makes room encrypted * @param {boolean} [opts.isEncrypted=false] Makes room encrypted
* @param {boolean} [opts.isDirect=false] Makes room as direct message * @param {boolean} [opts.isDirect=false] Makes room as direct message
* @param {string[]} [opts.invite=[]] An array of userId's to invite * @param {string[]} [opts.invite=[]] An array of userId's to invite
* @param{number} [opts.powerLevel=100] My power level
*/ */
async function create(opts) { async function create(opts) {
const mx = initMatrix.matrixClient; const mx = initMatrix.matrixClient;
const customPowerLevels = [101];
const options = { const options = {
name: opts.name, name: opts.name,
topic: opts.topic, topic: opts.topic,
@@ -143,6 +145,10 @@ async function create(opts) {
is_direct: opts.isDirect === true, is_direct: opts.isDirect === true,
invite: opts.invite || [], invite: opts.invite || [],
initial_state: [], 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) { if (opts.isPublic !== true && opts.isEncrypted === true) {
@@ -182,12 +188,15 @@ async function create(opts) {
async function invite(roomId, userId) { async function invite(roomId, userId) {
const mx = initMatrix.matrixClient; const mx = initMatrix.matrixClient;
try {
const result = await mx.invite(roomId, userId); const result = await mx.invite(roomId, userId);
return result; return result;
} catch (e) { }
throw new Error(e);
} async function kick(roomId, userId) {
const mx = initMatrix.matrixClient;
const result = await mx.kick(roomId, userId);
return result;
} }
function createSpaceShortcut(roomId) { function createSpaceShortcut(roomId) {
@@ -206,6 +215,6 @@ function deleteSpaceShortcut(roomId) {
export { export {
join, leave, join, leave,
create, invite, create, invite, kick,
createSpaceShortcut, deleteSpaceShortcut, createSpaceShortcut, deleteSpaceShortcut,
}; };

View File

@@ -77,12 +77,28 @@ class Notifications extends EventEmitter {
return this.roomIdToNoti.has(roomId); 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) { _setNoti(roomId, total, highlight, childId) {
const prevTotal = this.roomIdToNoti.get(roomId)?.total ?? null; const prevTotal = this.roomIdToNoti.get(roomId)?.total ?? null;
const noti = this.getNoti(roomId); const noti = this.getNoti(roomId);
if (!childId || this._remainingParentIds?.has(roomId)) {
noti.total += total; noti.total += total;
noti.highlight += highlight; noti.highlight += highlight;
}
if (childId) { if (childId) {
if (noti.from === null) noti.from = new Set(); if (noti.from === null) noti.from = new Set();
noti.from.add(childId); noti.from.add(childId);
@@ -91,9 +107,16 @@ class Notifications extends EventEmitter {
this.roomIdToNoti.set(roomId, noti); this.roomIdToNoti.set(roomId, noti);
this.emit(cons.events.notifications.NOTI_CHANGED, roomId, noti.total, prevTotal); 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); 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)); [...parentIds].forEach((parentId) => this._setNoti(parentId, total, highlight, roomId));
if (!childId) this._remainingParentIds = undefined;
} }
_deleteNoti(roomId, total, highlight, childId) { _deleteNoti(roomId, total, highlight, childId) {
@@ -103,8 +126,12 @@ class Notifications extends EventEmitter {
const prevTotal = noti.total; const prevTotal = noti.total;
noti.total -= total; noti.total -= total;
noti.highlight -= highlight; noti.highlight -= highlight;
if (noti.total < 0) {
noti.total = 0;
noti.highlight = 0;
}
if (childId && noti.from !== null) { 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) { if (noti.from === null || noti.from.size === 0) {
this.roomIdToNoti.delete(roomId); this.roomIdToNoti.delete(roomId);

View File

@@ -76,10 +76,23 @@ class RoomList extends EventEmitter {
if (parents.size === 0) this.roomIdToParents.delete(roomId); if (parents.size === 0) this.roomIdToParents.delete(roomId);
} }
getParentSpaces(roomId) {
let parentIds = this.roomIdToParents.get(roomId);
if (parentIds) {
[...parentIds].forEach((parentId) => {
parentIds = new Set([...parentIds, ...this.getParentSpaces(parentId)]);
});
}
return parentIds || new Set();
}
addToSpaces(roomId) { addToSpaces(roomId) {
this.spaces.add(roomId); this.spaces.add(roomId);
const allParentSpaces = this.getParentSpaces(roomId);
const spaceChildren = this.getSpaceChildren(roomId); const spaceChildren = this.getSpaceChildren(roomId);
spaceChildren?.forEach((childRoomId) => { spaceChildren?.forEach((childRoomId) => {
if (allParentSpaces.has(childRoomId)) return;
this.addToRoomIdToParents(childRoomId, roomId); this.addToRoomIdToParents(childRoomId, roomId);
}); });
} }
@@ -268,6 +281,8 @@ class RoomList extends EventEmitter {
if (mEvent.getType() === 'm.space.child') { if (mEvent.getType() === 'm.space.child') {
const { event } = mEvent; const { event } = mEvent;
if (isMEventSpaceChild(mEvent)) { if (isMEventSpaceChild(mEvent)) {
const allParentSpaces = this.getParentSpaces(event.room_id);
if (allParentSpaces.has(event.state_key)) return;
this.addToRoomIdToParents(event.state_key, event.room_id); this.addToRoomIdToParents(event.state_key, event.room_id);
} else this.removeFromRoomIdToParents(event.state_key, event.room_id); } else this.removeFromRoomIdToParents(event.state_key, event.room_id);
this.emit(cons.events.roomList.ROOMLIST_UPDATED); this.emit(cons.events.roomList.ROOMLIST_UPDATED);

View File

@@ -4,7 +4,7 @@ function getSecret(key) {
return localStorage.getItem(key); return localStorage.getItem(key);
} }
const isAuthanticated = () => getSecret(cons.secretKey.ACCESS_TOKEN) !== null; const isAuthenticated = () => getSecret(cons.secretKey.ACCESS_TOKEN) !== null;
const secret = { const secret = {
accessToken: getSecret(cons.secretKey.ACCESS_TOKEN), accessToken: getSecret(cons.secretKey.ACCESS_TOKEN),
@@ -14,6 +14,6 @@ const secret = {
}; };
export { export {
isAuthanticated, isAuthenticated,
secret, secret,
}; };

View File

@@ -1,4 +1,5 @@
const cons = { const cons = {
version: '1.5.0',
secretKey: { secretKey: {
ACCESS_TOKEN: 'cinny_access_token', ACCESS_TOKEN: 'cinny_access_token',
DEVICE_ID: 'cinny_device_id', DEVICE_ID: 'cinny_device_id',
@@ -27,6 +28,7 @@ const cons = {
OPEN_PUBLIC_ROOMS: 'OPEN_PUBLIC_ROOMS', OPEN_PUBLIC_ROOMS: 'OPEN_PUBLIC_ROOMS',
OPEN_CREATE_ROOM: 'OPEN_CREATE_ROOM', OPEN_CREATE_ROOM: 'OPEN_CREATE_ROOM',
OPEN_INVITE_USER: 'OPEN_INVITE_USER', OPEN_INVITE_USER: 'OPEN_INVITE_USER',
OPEN_PROFILE_VIEWER: 'OPEN_PROFILE_VIEWER',
OPEN_SETTINGS: 'OPEN_SETTINGS', OPEN_SETTINGS: 'OPEN_SETTINGS',
OPEN_EMOJIBOARD: 'OPEN_EMOJIBOARD', OPEN_EMOJIBOARD: 'OPEN_EMOJIBOARD',
OPEN_READRECEIPTS: 'OPEN_READRECEIPTS', OPEN_READRECEIPTS: 'OPEN_READRECEIPTS',
@@ -57,6 +59,7 @@ const cons = {
CREATE_ROOM_OPENED: 'CREATE_ROOM_OPENED', CREATE_ROOM_OPENED: 'CREATE_ROOM_OPENED',
INVITE_USER_OPENED: 'INVITE_USER_OPENED', INVITE_USER_OPENED: 'INVITE_USER_OPENED',
SETTINGS_OPENED: 'SETTINGS_OPENED', SETTINGS_OPENED: 'SETTINGS_OPENED',
PROFILE_VIEWER_OPENED: 'PROFILE_VIEWER_OPENED',
EMOJIBOARD_OPENED: 'EMOJIBOARD_OPENED', EMOJIBOARD_OPENED: 'EMOJIBOARD_OPENED',
READRECEIPTS_OPENED: 'READRECEIPTS_OPENED', READRECEIPTS_OPENED: 'READRECEIPTS_OPENED',
ROOMOPTIONS_OPENED: 'ROOMOPTIONS_OPENED', ROOMOPTIONS_OPENED: 'ROOMOPTIONS_OPENED',

View File

@@ -69,6 +69,9 @@ class Navigation extends EventEmitter {
[cons.actions.navigation.OPEN_INVITE_USER]: () => { [cons.actions.navigation.OPEN_INVITE_USER]: () => {
this.emit(cons.events.navigation.INVITE_USER_OPENED, action.roomId, action.searchTerm); 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]: () => { [cons.actions.navigation.OPEN_SETTINGS]: () => {
this.emit(cons.events.navigation.SETTINGS_OPENED); this.emit(cons.events.navigation.SETTINGS_OPENED);
}, },

View File

@@ -37,6 +37,7 @@
/* text color | --tc-[background type]-[priority]: value */ /* text color | --tc-[background type]-[priority]: value */
--tc-surface-high: #000000; --tc-surface-high: #000000;
--tc-surface-normal: rgba(0, 0, 0, 68%); --tc-surface-normal: rgba(0, 0, 0, 68%);
--tc-surface-normal-low: rgba(0, 0, 0, 60%);
--tc-surface-low: rgba(0, 0, 0, 38%); --tc-surface-low: rgba(0, 0, 0, 38%);
--tc-primary-high: #ffffff; --tc-primary-high: #ffffff;
@@ -56,7 +57,7 @@
--tc-danger-low: rgba(240, 71, 71, 60%); --tc-danger-low: rgba(240, 71, 71, 60%);
--tc-code: #e62498; --tc-code: #e62498;
--tc-link: hsl(213deg 76% 56%);
--tc-tooltip: white; --tc-tooltip: white;
--tc-badge: white; --tc-badge: white;
@@ -175,24 +176,26 @@
--bg-surface-active: rgba(255, 255, 255, 5%); --bg-surface-active: rgba(255, 255, 255, 5%);
--bg-surface-border: rgba(0, 0, 0, 20%); --bg-surface-border: rgba(0, 0, 0, 20%);
--bg-primary: rgb(59, 119, 191); --bg-primary: rgb(42, 98, 166);
--bg-primary-hover: rgba(59, 119, 191, 80%); --bg-primary-hover: rgba(42, 98, 166, 80%);
--bg-primary-active: rgba(59, 119, 191, 70%); --bg-primary-active: rgba(42, 98, 166, 70%);
--bg-primary-border: rgba(59, 119, 191, 38%); --bg-primary-border: rgba(42, 98, 166, 38%);
--bg-tooltip: #000; --bg-tooltip: #000;
--bg-badge: hsl(0, 0%, 75%); --bg-badge: hsl(0, 0%, 75%);
/* text color | --tc-[background type]-[priority]: value */ /* text color | --tc-[background type]-[priority]: value */
--tc-surface-high: rgba(255, 255, 255, 94%); --tc-surface-high: rgba(255, 255, 255, 98%);
--tc-surface-normal: rgba(255, 255, 255, 74%); --tc-surface-normal: rgba(255, 255, 255, 84%);
--tc-surface-low: rgba(255, 255, 255, 38%); --tc-surface-normal-low: rgba(255, 255, 255, 60%);
--tc-surface-low: rgba(255, 255, 255, 48%);
--tc-primary-high: #ffffff; --tc-primary-high: #ffffff;
--tc-primary-normal: rgba(255, 255, 255, 0.68); --tc-primary-normal: rgba(255, 255, 255, 0.68);
--tc-primary-low: rgba(255, 255, 255, 0.4); --tc-primary-low: rgba(255, 255, 255, 0.4);
--tc-code: #e565b1; --tc-code: #e565b1;
--tc-link: hsl(213deg 94% 73%);
--tc-badge: black; --tc-badge: black;
/* system icons | --ic-[background type]-[priority]: value */ /* system icons | --ic-[background type]-[priority]: value */
@@ -226,6 +229,7 @@
/* text color | --tc-[background type]-[priority]: value */ /* text color | --tc-[background type]-[priority]: value */
--tc-surface-high: rgb(255, 251, 222, 94%); --tc-surface-high: rgb(255, 251, 222, 94%);
--tc-surface-normal: rgba(255, 251, 222, 74%); --tc-surface-normal: rgba(255, 251, 222, 74%);
--tc-surface-normal-low: rgba(255, 251, 222, 60%);
--tc-surface-low: rgba(255, 251, 222, 38%); --tc-surface-low: rgba(255, 251, 222, 38%);
@@ -257,7 +261,7 @@ body {
-webkit-tap-highlight-color: transparent; -webkit-tap-highlight-color: transparent;
} }
a { a {
color: var(--bg-primary); color: var(--tc-link);
text-decoration: none; text-decoration: none;
} }
b { b {
@@ -286,6 +290,11 @@ button {
overflow: visible; overflow: visible;
-webkit-appearance: button; -webkit-appearance: button;
} }
textarea, input[type="text"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
textarea { textarea {
color: inherit; color: inherit;
word-spacing: inherit; word-spacing: inherit;

View File

@@ -1,3 +1,4 @@
/* eslint-disable max-classes-per-file */
export function bytesToSize(bytes) { export function bytesToSize(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return 'n/a'; if (bytes === 0) return 'n/a';
@@ -33,3 +34,53 @@ export function abbreviateNumber(number) {
if (number > 99) return '99+'; if (number > 99) return '99+';
return number; 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);
}

View File

@@ -2,15 +2,18 @@ import initMatrix from '../client/initMatrix';
const WELL_KNOWN_URI = '/.well-known/matrix/client'; const WELL_KNOWN_URI = '/.well-known/matrix/client';
async function getBaseUrl(homeserver) { async function getBaseUrl(servername) {
const serverDiscoveryUrl = `https://${homeserver}${WELL_KNOWN_URI}`; let protocol = 'https://';
if (servername.match(/^https?:\/\//) !== null) protocol = '';
const serverDiscoveryUrl = `${protocol}${servername}${WELL_KNOWN_URI}`;
try { try {
const result = await fetch(serverDiscoveryUrl, { method: 'GET' }); const result = await (await fetch(serverDiscoveryUrl, { method: 'GET' })).json();
const data = await result.json();
return data?.['m.homeserver']?.base_url; const baseUrl = result?.['m.homeserver']?.base_url;
if (baseUrl === undefined) throw new Error();
return baseUrl;
} catch (e) { } catch (e) {
throw new Error('Homeserver not found'); throw new Error(`${protocol}${servername}`);
} }
} }
@@ -69,7 +72,15 @@ function doesRoomHaveUnread(room) {
return true; 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 { export {
getBaseUrl, getUsername, getUsernameOfRoomMember, getBaseUrl, getUsername, getUsernameOfRoomMember,
isRoomAliasAvailable, doesRoomHaveUnread, isRoomAliasAvailable, doesRoomHaveUnread, getPowerLabel,
}; };

View File

@@ -1,6 +1,7 @@
const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin'); const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const webpack = require('webpack'); const webpack = require('webpack');
const CopyPlugin = require("copy-webpack-plugin");
module.exports = { module.exports = {
entry: { entry: {
@@ -38,15 +39,13 @@ module.exports = {
use: ['html-loader'], use: ['html-loader'],
}, },
{ {
test: /\.(svg|png|jpe?g|gif|otf|ttf)$/, test: /\.(png|jpe?g|gif|otf|ttf)$/,
use: { type: 'asset/resource',
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]',
outputPath: 'assets',
},
},
}, },
{
test: /\.svg$/,
type: 'asset/inline',
}
], ],
}, },
plugins: [ plugins: [
@@ -70,5 +69,12 @@ module.exports = {
new webpack.DefinePlugin({ new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env), 'process.env': JSON.stringify(process.env),
}), }),
new CopyPlugin({
patterns: [
{ from: 'olm.wasm' },
{ from: '_redirects' },
{ from: 'config.json' },
],
}),
], ],
}; };

View File

@@ -4,7 +4,6 @@ const { merge } = require('webpack-merge');
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
module.exports = merge(common, { module.exports = merge(common, {
mode: 'production', mode: 'production',
@@ -36,11 +35,5 @@ module.exports = merge(common, {
new MiniCssExtractPlugin({ new MiniCssExtractPlugin({
filename: '[name].[contenthash].bundle.css', filename: '[name].[contenthash].bundle.css',
}), }),
new CopyPlugin({
patterns: [
{ from: 'olm.wasm' },
{ from: '_redirects' },
],
}),
], ],
}); });