Compare commits

..
71 changed files with 7401 additions and 4200 deletions

No files matched your search

+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
path: dist
retention-days: 1
- name: Get PR info
uses: actions/github-script@v6.2.0
uses: actions/github-script@v6.1.0
with:
script: |
var fs = require('fs');
+2 -2
View File
@@ -17,7 +17,7 @@ jobs:
# workflow_run action (https://github.com/actions/download-artifact/issues/60)
# so instead we get this mess:
- name: Download artifact
uses: actions/github-script@v6.2.0
uses: actions/github-script@v6.1.0
with:
script: |
var artifacts = await github.rest.actions.listWorkflowRunArtifacts({
@@ -51,7 +51,7 @@ jobs:
run: unzip -d dist previewbuild.zip && rm previewbuild.zip && unzip pr.json.zip && rm pr.json.zip
- name: Read PR Info
id: readctx
uses: actions/github-script@v6.2.0
uses: actions/github-script@v6.1.0
with:
script: |
var fs = require('fs');
+2 -11
View File
@@ -64,11 +64,10 @@ jobs:
NETLIFY_DEPLOY_TO_PROD: true
push-to-dockerhub:
name: Push Docker image to Docker Hub, ghcr
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v3.0.2
@@ -81,19 +80,11 @@ jobs:
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to the Container registry
uses: docker/login-action@v2.0.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4.0.1
with:
images: |
${{ secrets.DOCKER_USERNAME }}/cinny
ghcr.io/${{ github.repository }}
images: ajbura/cinny
- name: Build and push Docker image
uses: docker/build-push-action@v3.1.1
with:
-3
View File
@@ -1,3 +0,0 @@
legacy-peer-deps=true
save-exact=true
@matrix-org:registry=https://gitlab.matrix.org/api/v4/projects/27/packages/npm/
+1 -6
View File
@@ -36,9 +36,4 @@ It is not always possible to phrase every change in such a manner, but it is des
Also, we use [ESLint](https://eslint.org/) for clean and stylistically consistent code syntax, so make sure your pull request follow it.
**For any query or design discussion, join our [Matrix room](https://matrix.to/#/#cinny:matrix.org).**
## Helpful links
- [BEM methodology](http://getbem.com/introduction/)
- [Atomic design](https://bradfrost.com/blog/post/atomic-web-design/)
- [Matrix JavaScript SDK documentation](https://matrix-org.github.io/matrix-js-sdk/19.2.0/index.html)
**For any query or design discussion, join our [Matrix room](https://matrix.to/#/#cinny:matrix.org).**
+1 -1
View File
@@ -3,7 +3,7 @@ FROM node:17.9.0-alpine3.15 as builder
WORKDIR /src
COPY .npmrc package.json package-lock.json /src/
COPY package.json package-lock.json /src/
RUN npm ci
COPY . /src/
RUN npm run build
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2021-present Ajay Bura (ajbura)
Copyright (c) 2021 Ajay Bura (ajbura)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+33 -29
View File
@@ -1,5 +1,9 @@
# Cinny
<p>
<p align="center">
<img src="https://raw.githubusercontent.com/ajbura/cinny/dev/public/res/svg/cinny.svg?sanitize=true"
height="16">
<span><b>Cinny</b></span>
</p>
<p align="center">
<a href="https://github.com/ajbura/cinny/releases">
<img alt="GitHub release downloads" src="https://img.shields.io/github/downloads/ajbura/cinny/total?logo=github&style=social"></a>
<a href="https://hub.docker.com/r/ajbura/cinny">
@@ -12,30 +16,21 @@
<img alt="Sponsor Cinny" src="https://img.shields.io/opencollective/all/cinny?logo=opencollective&style=social"></a>
</p>
A Matrix client focusing primarily on simple, elegant and secure interface. The main goal is to have an instant messaging application that is easy on people and has a modern touch.
- [Roadmap](https://github.com/ajbura/cinny/projects/11)
**Cinny** is a Matrix client focusing primarily on simple, elegant and secure interface. The main goal is to have a client that is easy on end user
and feels a modern chat application.
- [Contributing](./CONTRIBUTING.md)
- [Roadmap](https://github.com/ajbura/cinny/projects/11)
## Getting started
Web app is available at https://app.cinny.in and gets updated on each new release. The `dev` branch is continuously deployed at https://dev.cinny.in but keep in mind that it could have things broken.
## Building and Running
You can also download our desktop app from [cinny-desktop repository](https://github.com/cinnyapp/cinny-desktop).
### Running pre-compiled
To host Cinny on your own, download tarball of the app from [GitHub release](https://github.com/cinnyapp/cinny/releases/latest).
You can serve the application with a webserver of your choice by simply copying `dist/` directory to the webroot.
To set default Homeserver on login and register page, place a customized [`config.json`](config.json) in webroot of your choice.
Alternatively you can just pull the [DockerHub image](https://hub.docker.com/r/ajbura/cinny) by:
```
docker pull ajbura/cinny
```
or [ghcr image](https://github.com/cinnyapp/cinny/pkgs/container/cinny) by:
```
docker pull ghcr.io/cinnyapp/cinny:latest
```
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.
<details>
<summary>PGP Public Key to verify tarball</summary>
<summary>PGP Public Key to verify pre-compiled tarball</summary>
```
-----BEGIN PGP PUBLIC KEY BLOCK-----
@@ -82,39 +77,48 @@ UeGsouhyuITLwEhScounZDqop+Dx
```
</details>
## Local development
### Building from source
> We recommend using a version manager as versions change very quickly. You will likely need to switch
between multiple Node.js versions based on the needs of different projects you're working on. [NVM on windows](https://github.com/coreybutler/nvm-windows#installation--upgrades) on Windows and [nvm](https://github.com/nvm-sh/nvm) on Linux/macOS are pretty good choices. Also recommended nodejs version is 16.15.0 LTS.
Execute the following commands to start a development server:
Execute the following commands to compile the app from its source code:
```sh
npm ci # Installs all dependencies
npm start # Serve a development version
```
To build the app:
```sh
npm run build # Compiles the app into the dist/ directory
```
You can then copy the files to a webserver's webroot of your choice.
To serve a development version of the app locally for testing, you need to use the command `npm start`.
### Running with Docker
This repository includes a Dockerfile, which builds the application from source and serves it with Nginx on port 80. To
use this locally, you can build the container like so:
```
docker build -t cinny:latest .
```
You can then run the container you've built with a command similar to this:
```
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 navigating to `http://localhost:8080`.
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`.
Alternatively you can just pull the [DockerHub image](https://hub.docker.com/r/ajbura/cinny) by `docker pull ajbura/cinny`.
### Configuring default Homeserver
To set default Homeserver on login and register page, place a customized [`config.json`](config.json) in webroot of your choice.
## License
Copyright (c) 2021-present Ajay Bura (ajbura)
Copyright (c) 2021 Ajay Bura (ajbura)
Code licensed under the MIT License: <http://opensource.org/licenses/MIT>
Executable
BIN
View File
Binary file not shown.
+6917 -2744
View File
File diff suppressed because it is too large. Load diff
+72 -65
View File
@@ -1,11 +1,11 @@
{
"name": "cinny",
"version": "2.1.3",
"version": "2.1.2",
"description": "Yet another matrix client",
"main": "index.js",
"engines": {
"npm": ">=6.14.8",
"node": ">=14.15.0"
"npm": ">=6.14.8 <=8.5.5",
"node": ">=14.15.0 <=17.9.0"
},
"scripts": {
"start": "webpack serve --config ./webpack.dev.js --open",
@@ -15,69 +15,76 @@
"author": "Ajay Bura",
"license": "MIT",
"dependencies": {
"@fontsource/inter": "4.5.12",
"@fontsource/roboto": "4.5.8",
"@khanacademy/simple-markdown": "0.8.3",
"@matrix-org/olm": "3.2.12",
"@tippyjs/react": "4.2.6",
"babel-polyfill": "6.26.0",
"blurhash": "1.1.5",
"browser-encrypt-attachment": "0.3.0",
"dateformat": "5.0.3",
"emojibase-data": "7.0.1",
"file-saver": "2.0.5",
"flux": "4.0.3",
"formik": "2.2.9",
"html-react-parser": "3.0.4",
"katex": "0.16.2",
"linkify-html": "4.0.0-beta.5",
"linkifyjs": "4.0.0-beta.5",
"matrix-js-sdk": "19.4.0",
"prop-types": "15.8.1",
"react": "17.0.2",
"react-autosize-textarea": "7.1.0",
"react-blurhash": "0.1.3",
"react-dnd": "15.1.2",
"react-dnd-html5-backend": "15.1.3",
"react-dom": "17.0.2",
"react-google-recaptcha": "2.1.0",
"react-modal": "3.15.1",
"sanitize-html": "2.7.1",
"tippy.js": "6.3.7",
"twemoji": "14.0.2"
"@fontsource/inter": "^4.5.12",
"@fontsource/roboto": "^4.5.8",
"@matrix-org/olm": "https://gitlab.matrix.org/api/v4/projects/27/packages/npm/@matrix-org/olm/-/@matrix-org/olm-3.2.12.tgz",
"@tippyjs/react": "^4.2.6",
"babel-polyfill": "^6.26.0",
"blurhash": "^1.1.5",
"browser-encrypt-attachment": "^0.3.0",
"dateformat": "^5.0.3",
"emojibase-data": "^7.0.1",
"file-saver": "^2.0.5",
"flux": "^4.0.3",
"formik": "^2.2.9",
"html-react-parser": "^3.0.1",
"katex": "^0.16.0",
"linkify-html": "^4.0.0-beta.5",
"linkifyjs": "^4.0.0-beta.5",
"matrix-js-sdk": "^19.2.0",
"micromark": "^3.0.10",
"micromark-extension-gfm": "^2.0.1",
"micromark-extension-math": "^2.0.2",
"micromark-util-chunked": "^1.0.0",
"micromark-util-resolve-all": "^1.0.0",
"micromark-util-symbol": "^1.0.1",
"prop-types": "^15.8.1",
"react": "^17.0.2",
"react-autosize-textarea": "^7.1.0",
"react-blurhash": "^0.1.3",
"react-dnd": "^15.1.2",
"react-dnd-html5-backend": "^15.1.3",
"react-dom": "^17.0.2",
"react-google-recaptcha": "^2.1.0",
"react-modal": "^3.15.1",
"sanitize-html": "^2.7.1",
"tippy.js": "^6.3.7",
"twemoji": "^14.0.2"
},
"devDependencies": {
"@babel/core": "7.18.13",
"@babel/preset-env": "7.18.10",
"@babel/preset-react": "7.18.6",
"assert": "2.0.0",
"babel-loader": "8.2.5",
"browserify-fs": "1.0.0",
"buffer": "6.0.3",
"clean-webpack-plugin": "4.0.0",
"copy-webpack-plugin": "11.0.0",
"crypto-browserify": "3.12.0",
"css-loader": "6.7.1",
"css-minimizer-webpack-plugin": "4.0.0",
"eslint": "8.23.0",
"eslint-config-airbnb": "19.0.4",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-jsx-a11y": "6.6.1",
"eslint-plugin-react": "7.31.1",
"eslint-plugin-react-hooks": "4.6.0",
"html-loader": "4.1.0",
"html-webpack-plugin": "5.3.1",
"mini-css-extract-plugin": "2.6.1",
"path-browserify": "1.0.1",
"sass": "1.54.5",
"sass-loader": "13.0.2",
"stream-browserify": "3.0.0",
"style-loader": "3.3.1",
"url": "0.11.0",
"util": "0.12.4",
"webpack": "5.74.0",
"webpack-cli": "4.10.0",
"webpack-dev-server": "4.10.1",
"webpack-merge": "5.7.3"
"@babel/core": "^7.18.10",
"@babel/preset-env": "^7.18.10",
"@babel/preset-react": "^7.18.6",
"assert": "^2.0.0",
"babel-loader": "^8.2.5",
"browserify-fs": "^1.0.0",
"buffer": "^6.0.3",
"clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^11.0.0",
"crypto-browserify": "^3.12.0",
"css-loader": "^6.7.1",
"css-minimizer-webpack-plugin": "^4.0.0",
"eslint": "^8.21.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsx-a11y": "^6.6.1",
"eslint-plugin-react": "^7.30.1",
"eslint-plugin-react-hooks": "^4.6.0",
"favicons": "^6.2.2",
"favicons-webpack-plugin": "^5.0.2",
"html-loader": "^4.1.0",
"html-webpack-plugin": "^5.3.1",
"mini-css-extract-plugin": "^2.6.1",
"path-browserify": "^1.0.1",
"sass": "^1.54.3",
"sass-loader": "^13.0.2",
"stream-browserify": "^3.0.0",
"style-loader": "^3.3.1",
"url": "^0.11.0",
"util": "^0.12.4",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.3",
"webpack-merge": "^5.7.3"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

-22
View File
@@ -15,28 +15,6 @@
<meta property="og:image" content="https://cinny.in/assets/favicon-48x48.png">
<meta property="og:description" content="A Matrix client where you can enjoy the conversation using simple, elegant and secure interface protected by e2ee with the power of open source.">
<meta name="theme-color" content="#000000">
<link id="favicon" rel="shortcut icon" href="./favicon.ico" />
<link rel="manifest" href="./manifest.json" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="application-name" content="Cinny" />
<meta name="apple-mobile-web-app-title" content="Cinny" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<link rel="apple-touch-icon" sizes="57x57" href="./res/apple/apple-touch-icon-57x57.png"/>
<link rel="apple-touch-icon" sizes="60x60" href="./res/apple/apple-touch-icon-60x60.png"/>
<link rel="apple-touch-icon" sizes="72x72" href="./res/apple/apple-touch-icon-72x72.png"/>
<link rel="apple-touch-icon" sizes="76x76" href="./res/apple/apple-touch-icon-76x76.png"/>
<link rel="apple-touch-icon" sizes="114x114" href="./res/apple/apple-touch-icon-114x114.png"/>
<link rel="apple-touch-icon" sizes="120x120" href="./res/apple/apple-touch-icon-120x120.png"/>
<link rel="apple-touch-icon" sizes="144x144" href="./res/apple/apple-touch-icon-144x144.png"/>
<link rel="apple-touch-icon" sizes="152x152" href="./res/apple/apple-touch-icon-152x152.png"/>
<link rel="apple-touch-icon" sizes="167x167" href="./res/apple/apple-touch-icon-167x167.png"/>
<link rel="apple-touch-icon" sizes="180x180" href="./res/apple/apple-touch-icon-180x180.png"/>
</head>
<body id="appBody">
<div id="root"></div>
-59
View File
@@ -1,59 +0,0 @@
{
"name": "Cinny",
"short_name": "Cinny",
"description": "Yet another matrix client",
"dir": "auto",
"lang": "en-US",
"display": "standalone",
"orientation": "portrait",
"start_url": "/",
"background_color": "#fff",
"theme_color": "#fff",
"icons": [
{
"src": "android-chrome-36x36.png",
"sizes": "36x36",
"type": "image/png"
},
{
"src": "android-chrome-48x48.png",
"sizes": "48x48",
"type": "image/png"
},
{
"src": "android-chrome-72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "android-chrome-96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "android-chrome-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "android-chrome-256x256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "android-chrome-384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2021-present Ajay Bura (ajbura)
Graphics (c) by Ajay Bura (ajbura)
Graphic content is licensed under a
Creative Commons Attribution 4.0 International License.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

-13
View File
@@ -1,13 +0,0 @@
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_2707_1961)">
<path d="M10.5867 17.3522C10.0727 17.4492 9.54226 17.5 9 17.5C4.30558 17.5 0.5 13.6944 0.5 9C0.5 4.30558 4.30558 0.5 9 0.5C13.6944 0.5 17.5 4.30558 17.5 9C17.5 9.54226 17.4492 10.0727 17.3522 10.5867C16.6511 10.2123 15.8503 10 15 10C12.2386 10 10 12.2386 10 15C10 15.8503 10.2123 16.6511 10.5867 17.3522Z" fill="white"/>
<path d="M10 6.39999C10 6.67614 9.77614 6.89999 9.5 6.89999C9.22386 6.89999 9 6.67614 9 6.39999C9 6.12385 9.22386 5.89999 9.5 5.89999C9.77614 5.89999 10 6.12385 10 6.39999Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M9 0C4 0 0 4 0 9C0 14 4 18 9 18C9.63967 18 10.263 17.9345 10.8636 17.8099C10.3186 17.0091 10 16.0417 10 15C10 12.2386 12.2386 10 15 10C16.0417 10 17.0091 10.3186 17.8099 10.8636C17.9345 10.263 18 9.63967 18 9C18 4 14 0 9 0ZM1.2 10.8L4.7 8.5V8.2C4.7 6.4 6 5 7.8 4.8H8.2C9.4 4.8 10.5 5.4 11.1 6.4C11.4 6.3 11.7 6.3 12 6.3C12.4 6.3 12.8 6.3 13.2 6.4C13.9 6.6 14.6 6.9 15.2 7.3C14.6 7.1 14 7 13.3 7C12.1 7 11.1 7.4 10.4 8.4C9.7 9.3 9.3 10.4 9.3 11.6C9.3 13.1 8.9 14.5 8 15.8C7.93744 15.8834 7.87923 15.9625 7.82356 16.0381C7.6123 16.325 7.43739 16.5626 7.2 16.8C4.2 16.1 1.9 13.8 1.2 10.8Z" fill="black"/>
<path d="M18 15C18 16.6569 16.6569 18 15 18C13.3431 18 12 16.6569 12 15C12 13.3431 13.3431 12 15 12C16.6569 12 18 13.3431 18 15Z" fill="#45B83B"/>
</g>
<defs>
<clipPath id="clip0_2707_1961">
<rect width="18" height="18" fill="white"/>
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

-13
View File
@@ -1,13 +0,0 @@
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_2707_2015)">
<path d="M10.5867 17.3522C10.0727 17.4492 9.54226 17.5 9 17.5C4.30558 17.5 0.5 13.6944 0.5 9C0.5 4.30558 4.30558 0.5 9 0.5C13.6944 0.5 17.5 4.30558 17.5 9C17.5 9.54226 17.4492 10.0727 17.3522 10.5867C16.6511 10.2123 15.8503 10 15 10C12.2386 10 10 12.2386 10 15C10 15.8503 10.2123 16.6511 10.5867 17.3522Z" fill="white"/>
<path d="M10 6.39999C10 6.67614 9.77614 6.89999 9.5 6.89999C9.22386 6.89999 9 6.67614 9 6.39999C9 6.12385 9.22386 5.89999 9.5 5.89999C9.77614 5.89999 10 6.12385 10 6.39999Z" fill="black"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M9 0C4 0 0 4 0 9C0 14 4 18 9 18C9.63967 18 10.263 17.9345 10.8636 17.8099C10.3186 17.0091 10 16.0417 10 15C10 12.2386 12.2386 10 15 10C16.0417 10 17.0091 10.3186 17.8099 10.8636C17.9345 10.263 18 9.63967 18 9C18 4 14 0 9 0ZM1.2 10.8L4.7 8.5V8.2C4.7 6.4 6 5 7.8 4.8H8.2C9.4 4.8 10.5 5.4 11.1 6.4C11.4 6.3 11.7 6.3 12 6.3C12.4 6.3 12.8 6.3 13.2 6.4C13.9 6.6 14.6 6.9 15.2 7.3C14.6 7.1 14 7 13.3 7C12.1 7 11.1 7.4 10.4 8.4C9.7 9.3 9.3 10.4 9.3 11.6C9.3 13.1 8.9 14.5 8 15.8C7.93744 15.8834 7.87923 15.9625 7.82356 16.0381C7.6123 16.325 7.43739 16.5626 7.2 16.8C4.2 16.1 1.9 13.8 1.2 10.8Z" fill="black"/>
<path d="M18 15C18 16.6569 16.6569 18 15 18C13.3431 18 12 16.6569 12 15C12 13.3431 13.3431 12 15 12C16.6569 12 18 13.3431 18 15Z" fill="#989898"/>
</g>
<defs>
<clipPath id="clip0_2707_2015">
<rect width="18" height="18" fill="white"/>
</clipPath>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

+5 -1
View File
@@ -1,4 +1,8 @@
import { avatarInitials, cssVar } from '../../../util/common';
import { avatarInitials } from '../../../util/common';
function cssVar(name) {
return getComputedStyle(document.body).getPropertyValue(name);
}
// renders the avatar and returns it as an URL
export default async function renderAvatar({
-22
View File
@@ -1,22 +0,0 @@
/* eslint-disable import/prefer-default-export */
import { useState, useEffect } from 'react';
import initMatrix from '../../client/initMatrix';
export function useAccountData(eventType) {
const mx = initMatrix.matrixClient;
const [event, setEvent] = useState(mx.getAccountData(eventType));
useEffect(() => {
const handleChange = (mEvent) => {
if (mEvent.getType() !== eventType) return;
setEvent(mEvent);
};
mx.on('accountData', handleChange);
return () => {
mx.removeListener('accountData', handleChange);
};
}, [eventType]);
return event;
}
@@ -1,174 +0,0 @@
import React from 'react';
import initMatrix from '../../../client/initMatrix';
import { openReusableContextMenu } from '../../../client/action/navigation';
import { getEventCords } from '../../../util/common';
import Text from '../../atoms/text/Text';
import Button from '../../atoms/button/Button';
import { MenuHeader } from '../../atoms/context-menu/ContextMenu';
import SettingTile from '../setting-tile/SettingTile';
import NotificationSelector from './NotificationSelector';
import ChevronBottomIC from '../../../../public/res/ic/outlined/chevron-bottom.svg';
import { useAccountData } from '../../hooks/useAccountData';
export const notifType = {
ON: 'on',
OFF: 'off',
NOISY: 'noisy',
};
export const typeToLabel = {
[notifType.ON]: 'On',
[notifType.OFF]: 'Off',
[notifType.NOISY]: 'Noisy',
};
Object.freeze(notifType);
const DM = '.m.rule.room_one_to_one';
const ENC_DM = '.m.rule.encrypted_room_one_to_one';
const ROOM = '.m.rule.message';
const ENC_ROOM = '.m.rule.encrypted';
export function getActionType(rule) {
const { actions } = rule;
if (actions.find((action) => action?.set_tweak === 'sound')) return notifType.NOISY;
if (actions.find((action) => action?.set_tweak === 'highlight')) return notifType.ON;
if (actions.find((action) => action === 'dont_notify')) return notifType.OFF;
return notifType.OFF;
}
export function getTypeActions(type, highlightValue = false) {
if (type === notifType.OFF) return ['dont_notify'];
const highlight = { set_tweak: 'highlight' };
if (typeof highlightValue === 'boolean') highlight.value = highlightValue;
if (type === notifType.ON) return ['notify', highlight];
const sound = { set_tweak: 'sound', value: 'default' };
return ['notify', sound, highlight];
}
function useGlobalNotif() {
const mx = initMatrix.matrixClient;
const pushRules = useAccountData('m.push_rules')?.getContent();
const underride = pushRules?.global?.underride ?? [];
const rulesToType = {
[DM]: notifType.ON,
[ENC_DM]: notifType.ON,
[ROOM]: notifType.NOISY,
[ENC_ROOM]: notifType.NOISY,
};
const getRuleCondition = (rule) => {
const condition = [];
if (rule === DM || rule === ENC_DM) {
condition.push({ kind: 'room_member_count', is: '2' });
}
condition.push({
kind: 'event_match',
key: 'type',
pattern: [ENC_DM, ENC_ROOM].includes(rule) ? 'm.room.encrypted' : 'm.room.message',
});
return condition;
};
const setRule = (rule, type) => {
const content = pushRules ?? {};
if (!content.global) content.global = {};
if (!content.global.underride) content.global.underride = [];
const ur = content.global.underride;
let ruleContent = ur.find((action) => action?.rule_id === rule);
if (!ruleContent) {
ruleContent = {
conditions: getRuleCondition(type),
actions: [],
rule_id: rule,
default: true,
enabled: true,
};
ur.push(ruleContent);
}
ruleContent.actions = getTypeActions(type);
mx.setAccountData('m.push_rules', content);
};
const dmRule = underride.find((rule) => rule.rule_id === DM);
const encDmRule = underride.find((rule) => rule.rule_id === ENC_DM);
const roomRule = underride.find((rule) => rule.rule_id === ROOM);
const encRoomRule = underride.find((rule) => rule.rule_id === ENC_ROOM);
if (dmRule) rulesToType[DM] = getActionType(dmRule);
if (encDmRule) rulesToType[ENC_DM] = getActionType(encDmRule);
if (roomRule) rulesToType[ROOM] = getActionType(roomRule);
if (encRoomRule) rulesToType[ENC_ROOM] = getActionType(encRoomRule);
return [rulesToType, setRule];
}
function GlobalNotification() {
const [rulesToType, setRule] = useGlobalNotif();
const onSelect = (evt, rule) => {
openReusableContextMenu(
'bottom',
getEventCords(evt, '.btn-surface'),
(requestClose) => (
<NotificationSelector
value={rulesToType[rule]}
onSelect={(value) => {
if (rulesToType[rule] !== value) setRule(rule, value);
requestClose();
}}
/>
),
);
};
return (
<div className="global-notification">
<MenuHeader>Global Notifications</MenuHeader>
<SettingTile
title="Direct messages"
options={(
<Button onClick={(evt) => onSelect(evt, DM)} iconSrc={ChevronBottomIC}>
{ typeToLabel[rulesToType[DM]] }
</Button>
)}
content={<Text variant="b3">Default notification settings for all direct message.</Text>}
/>
<SettingTile
title="Encrypted direct messages"
options={(
<Button onClick={(evt) => onSelect(evt, ENC_DM)} iconSrc={ChevronBottomIC}>
{typeToLabel[rulesToType[ENC_DM]]}
</Button>
)}
content={<Text variant="b3">Default notification settings for all encrypted direct message.</Text>}
/>
<SettingTile
title="Rooms messages"
options={(
<Button onClick={(evt) => onSelect(evt, ROOM)} iconSrc={ChevronBottomIC}>
{typeToLabel[rulesToType[ROOM]]}
</Button>
)}
content={<Text variant="b3">Default notification settings for all room message.</Text>}
/>
<SettingTile
title="Encrypted rooms messages"
options={(
<Button onClick={(evt) => onSelect(evt, ENC_ROOM)} iconSrc={ChevronBottomIC}>
{typeToLabel[rulesToType[ENC_ROOM]]}
</Button>
)}
content={<Text variant="b3">Default notification settings for all encrypted room message.</Text>}
/>
</div>
);
}
export default GlobalNotification;
@@ -1,64 +0,0 @@
import React from 'react';
import './IgnoreUserList.scss';
import initMatrix from '../../../client/initMatrix';
import * as roomActions from '../../../client/action/room';
import Text from '../../atoms/text/Text';
import Chip from '../../atoms/chip/Chip';
import Input from '../../atoms/input/Input';
import Button from '../../atoms/button/Button';
import { MenuHeader } from '../../atoms/context-menu/ContextMenu';
import SettingTile from '../setting-tile/SettingTile';
import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
import { useAccountData } from '../../hooks/useAccountData';
function IgnoreUserList() {
useAccountData('m.ignored_user_list');
const ignoredUsers = initMatrix.matrixClient.getIgnoredUsers();
const handleSubmit = (evt) => {
evt.preventDefault();
const { ignoreInput } = evt.target.elements;
const value = ignoreInput.value.trim();
const userIds = value.split(' ').filter((v) => v.match(/^@\S+:\S+$/));
if (userIds.length === 0) return;
ignoreInput.value = '';
roomActions.ignore(userIds);
};
return (
<div className="ignore-user-list">
<MenuHeader>Ignored users</MenuHeader>
<SettingTile
title="Ignore user"
content={(
<div className="ignore-user-list__users">
<Text variant="b3">Ignore userId if you do not want to receive their messages or invites.</Text>
<form onSubmit={handleSubmit}>
<Input name="ignoreInput" required />
<Button variant="primary" type="submit">Ignore</Button>
</form>
{ignoredUsers.length > 0 && (
<div>
{ignoredUsers.map((uId) => (
<Chip
iconSrc={CrossIC}
key={uId}
text={uId}
iconColor={CrossIC}
onClick={() => roomActions.unignore([uId])}
/>
))}
</div>
)}
</div>
)}
/>
</div>
);
}
export default IgnoreUserList;
@@ -1,17 +0,0 @@
.ignore-user-list {
&__users {
& form,
& > div:last-child {
display: flex;
flex-wrap: wrap;
gap: var(--sp-tight);
}
& form {
margin: var(--sp-extra-tight) 0 var(--sp-normal);
.input-container {
flex-grow: 1;
}
}
}
}
@@ -1,239 +0,0 @@
import React from 'react';
import './KeywordNotification.scss';
import initMatrix from '../../../client/initMatrix';
import { openReusableContextMenu } from '../../../client/action/navigation';
import { getEventCords } from '../../../util/common';
import Text from '../../atoms/text/Text';
import Chip from '../../atoms/chip/Chip';
import Input from '../../atoms/input/Input';
import Button from '../../atoms/button/Button';
import { MenuHeader } from '../../atoms/context-menu/ContextMenu';
import SettingTile from '../setting-tile/SettingTile';
import NotificationSelector from './NotificationSelector';
import ChevronBottomIC from '../../../../public/res/ic/outlined/chevron-bottom.svg';
import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
import { useAccountData } from '../../hooks/useAccountData';
import {
notifType, typeToLabel, getActionType, getTypeActions,
} from './GlobalNotification';
const DISPLAY_NAME = '.m.rule.contains_display_name';
const ROOM_PING = '.m.rule.roomnotif';
const USERNAME = '.m.rule.contains_user_name';
const KEYWORD = 'keyword';
function useKeywordNotif() {
const mx = initMatrix.matrixClient;
const pushRules = useAccountData('m.push_rules')?.getContent();
const override = pushRules?.global?.override ?? [];
const content = pushRules?.global?.content ?? [];
const rulesToType = {
[DISPLAY_NAME]: notifType.NOISY,
[ROOM_PING]: notifType.NOISY,
[USERNAME]: notifType.NOISY,
};
const setRule = (rule, type) => {
const evtContent = pushRules ?? {};
if (!evtContent.global) evtContent.global = {};
if (!evtContent.global.override) evtContent.global.override = [];
if (!evtContent.global.content) evtContent.global.content = [];
const or = evtContent.global.override;
const ct = evtContent.global.content;
if (rule === DISPLAY_NAME || rule === ROOM_PING) {
let orRule = or.find((r) => r?.rule_id === rule);
if (!orRule) {
orRule = {
conditions: [],
actions: [],
rule_id: rule,
default: true,
enabled: true,
};
or.push(orRule);
}
if (rule === DISPLAY_NAME) {
orRule.conditions = [{ kind: 'contains_display_name' }];
orRule.actions = getTypeActions(type, true);
} else {
orRule.conditions = [
{ kind: 'event_match', key: 'content.body', pattern: '@room' },
{ kind: 'sender_notification_permission', key: 'room' },
];
orRule.actions = getTypeActions(type, true);
}
} else if (rule === USERNAME) {
let usernameRule = ct.find((r) => r?.rule_id === rule);
if (!usernameRule) {
const userId = mx.getUserId();
const username = userId.match(/^@?(\S+):(\S+)$/)?.[1] ?? userId;
usernameRule = {
actions: [],
default: true,
enabled: true,
pattern: username,
rule_id: rule,
};
ct.push(usernameRule);
}
usernameRule.actions = getTypeActions(type, true);
} else {
const keyRules = ct.filter((r) => r.rule_id !== USERNAME);
keyRules.forEach((r) => {
// eslint-disable-next-line no-param-reassign
r.actions = getTypeActions(type, true);
});
}
mx.setAccountData('m.push_rules', evtContent);
};
const addKeyword = (keyword) => {
if (content.find((r) => r.rule_id === keyword)) return;
content.push({
rule_id: keyword,
pattern: keyword,
enabled: true,
default: false,
actions: getTypeActions(rulesToType[KEYWORD] ?? notifType.NOISY, true),
});
mx.setAccountData('m.push_rules', pushRules);
};
const removeKeyword = (rule) => {
pushRules.global.content = content.filter((r) => r.rule_id !== rule.rule_id);
mx.setAccountData('m.push_rules', pushRules);
};
const dsRule = override.find((rule) => rule.rule_id === DISPLAY_NAME);
const roomRule = override.find((rule) => rule.rule_id === ROOM_PING);
const usernameRule = content.find((rule) => rule.rule_id === USERNAME);
const keywordRule = content.find((rule) => rule.rule_id !== USERNAME);
if (dsRule) rulesToType[DISPLAY_NAME] = getActionType(dsRule);
if (roomRule) rulesToType[ROOM_PING] = getActionType(roomRule);
if (usernameRule) rulesToType[USERNAME] = getActionType(usernameRule);
if (keywordRule) rulesToType[KEYWORD] = getActionType(keywordRule);
return {
rulesToType,
pushRules,
setRule,
addKeyword,
removeKeyword,
};
}
function GlobalNotification() {
const {
rulesToType,
pushRules,
setRule,
addKeyword,
removeKeyword,
} = useKeywordNotif();
const keywordRules = pushRules?.global?.content.filter((r) => r.rule_id !== USERNAME) ?? [];
const onSelect = (evt, rule) => {
openReusableContextMenu(
'bottom',
getEventCords(evt, '.btn-surface'),
(requestClose) => (
<NotificationSelector
value={rulesToType[rule]}
onSelect={(value) => {
if (rulesToType[rule] !== value) setRule(rule, value);
requestClose();
}}
/>
),
);
};
const handleSubmit = (evt) => {
evt.preventDefault();
const { keywordInput } = evt.target.elements;
const value = keywordInput.value.trim();
if (value === '') return;
addKeyword(value);
keywordInput.value = '';
};
return (
<div className="keyword-notification">
<MenuHeader>Mentions & keywords</MenuHeader>
<SettingTile
title="Message containing my display name"
options={(
<Button onClick={(evt) => onSelect(evt, DISPLAY_NAME)} iconSrc={ChevronBottomIC}>
{ typeToLabel[rulesToType[DISPLAY_NAME]] }
</Button>
)}
content={<Text variant="b3">Default notification settings for all message containing your display name.</Text>}
/>
<SettingTile
title="Message containing my username"
options={(
<Button onClick={(evt) => onSelect(evt, USERNAME)} iconSrc={ChevronBottomIC}>
{ typeToLabel[rulesToType[USERNAME]] }
</Button>
)}
content={<Text variant="b3">Default notification settings for all message containing your username.</Text>}
/>
<SettingTile
title="Message containing @room"
options={(
<Button onClick={(evt) => onSelect(evt, ROOM_PING)} iconSrc={ChevronBottomIC}>
{typeToLabel[rulesToType[ROOM_PING]]}
</Button>
)}
content={<Text variant="b3">Default notification settings for all messages containing @room.</Text>}
/>
{ rulesToType[KEYWORD] && (
<SettingTile
title="Message containing keywords"
options={(
<Button onClick={(evt) => onSelect(evt, KEYWORD)} iconSrc={ChevronBottomIC}>
{typeToLabel[rulesToType[KEYWORD]]}
</Button>
)}
content={<Text variant="b3">Default notification settings for all message containing keywords.</Text>}
/>
)}
<SettingTile
title="Keywords"
content={(
<div className="keyword-notification__keyword">
<Text variant="b3">Get notification when a message contains keyword.</Text>
<form onSubmit={handleSubmit}>
<Input name="keywordInput" required />
<Button variant="primary" type="submit">Add</Button>
</form>
{keywordRules.length > 0 && (
<div>
{keywordRules.map((rule) => (
<Chip
iconSrc={CrossIC}
key={rule.rule_id}
text={rule.pattern}
iconColor={CrossIC}
onClick={() => removeKeyword(rule)}
/>
))}
</div>
)}
</div>
)}
/>
</div>
);
}
export default GlobalNotification;
@@ -1,17 +0,0 @@
.keyword-notification {
&__keyword {
& form,
& > div:last-child {
display: flex;
flex-wrap: wrap;
gap: var(--sp-tight);
}
& form {
margin: var(--sp-extra-tight) 0 var(--sp-normal);
.input-container {
flex-grow: 1;
}
}
}
}
@@ -1,26 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { MenuHeader, MenuItem } from '../../atoms/context-menu/ContextMenu';
import CheckIC from '../../../../public/res/ic/outlined/check.svg';
function NotificationSelector({
value, onSelect,
}) {
return (
<div>
<MenuHeader>Notification</MenuHeader>
<MenuItem iconSrc={value === 'off' ? CheckIC : null} variant={value === 'off' ? 'positive' : 'surface'} onClick={() => onSelect('off')}>Off</MenuItem>
<MenuItem iconSrc={value === 'on' ? CheckIC : null} variant={value === 'on' ? 'positive' : 'surface'} onClick={() => onSelect('on')}>On</MenuItem>
<MenuItem iconSrc={value === 'noisy' ? CheckIC : null} variant={value === 'noisy' ? 'positive' : 'surface'} onClick={() => onSelect('noisy')}>Noisy</MenuItem>
</div>
);
}
NotificationSelector.propTypes = {
value: PropTypes.oneOf(['off', 'on', 'noisy']).isRequired,
onSelect: PropTypes.func.isRequired,
};
export default NotificationSelector;
@@ -38,7 +38,7 @@
.image-lightbox__content {
display: flex;
justify-content: center;
max-height: 80vh;
max-height: 90vh;
& img {
background-color: var(--bg-surface-low);
+8 -14
View File
@@ -714,9 +714,9 @@ function getEditedBody(editedMEvent) {
}
function Message({
mEvent, isBodyOnly, roomTimeline,
focus, fullTime, isEdit, setEdit, cancelEdit,
mEvent, isBodyOnly, roomTimeline, focus, fullTime,
}) {
const [isEditing, setIsEditing] = useState(false);
const roomId = mEvent.getRoomId();
const { editedTimeline, reactionTimeline } = roomTimeline ?? {};
@@ -731,7 +731,7 @@ function Message({
const avatarSrc = mEvent.sender?.getAvatarUrl(initMatrix.matrixClient.baseUrl, 36, 36, 'crop') ?? null;
const edit = useCallback(() => {
setEdit(eventId);
setIsEditing(true);
}, []);
const reply = useCallback(() => {
replyTo(senderId, mEvent.getId(), body);
@@ -788,7 +788,7 @@ function Message({
eventId={mEvent.replyEventId}
/>
)}
{!isEdit && (
{!isEditing && (
<MessageBody
senderName={username}
isCustomHTML={isCustomHTML}
@@ -797,22 +797,22 @@ function Message({
isEdited={isEdited}
/>
)}
{isEdit && (
{isEditing && (
<MessageEdit
body={body}
onSave={(newBody) => {
if (newBody !== body) {
initMatrix.roomsInput.sendEditedMessage(roomId, mEvent, newBody);
}
cancelEdit();
setIsEditing(false);
}}
onCancel={cancelEdit}
onCancel={() => setIsEditing(false)}
/>
)}
{haveReactions && (
<MessageReactionGroup roomTimeline={roomTimeline} mEvent={mEvent} />
)}
{roomTimeline && !isEdit && (
{roomTimeline && !isEditing && (
<MessageOptions
roomTimeline={roomTimeline}
mEvent={mEvent}
@@ -829,9 +829,6 @@ Message.defaultProps = {
focus: false,
roomTimeline: null,
fullTime: false,
isEdit: false,
setEdit: null,
cancelEdit: null,
};
Message.propTypes = {
mEvent: PropTypes.shape({}).isRequired,
@@ -839,9 +836,6 @@ Message.propTypes = {
roomTimeline: PropTypes.shape({}),
focus: PropTypes.bool,
fullTime: PropTypes.bool,
isEdit: PropTypes.bool,
setEdit: PropTypes.func,
cancelEdit: PropTypes.func,
};
export { Message, MessageReply, PlaceholderMessage };
+16 -33
View File
@@ -15,7 +15,7 @@
display: flex;
}
}
&__avatar-container {
padding-top: 6px;
@include dir.side(margin, 0, var(--sp-tight));
@@ -101,6 +101,7 @@
}
}
.message__header {
display: flex;
align-items: baseline;
@@ -114,16 +115,10 @@
@extend .cp-txt__ellipsis;
color: inherit;
}
& > span:last-child {
display: none;
}
& > span:last-child { display: none; }
&:hover {
& > span:first-child {
display: none;
}
& > span:last-child {
display: block;
}
& > span:first-child { display: none; }
& > span:last-child { display: block; }
}
}
@@ -173,11 +168,7 @@
& > .text > a {
white-space: initial !important;
}
& p:not(:last-child) {
margin-bottom: var(--sp-normal);
}
& span[data-mx-pill] {
background-color: hsla(0, 0%, 64%, 0.15);
padding: 0 2px;
@@ -200,7 +191,7 @@
& span[data-mx-spoiler] {
border-radius: 4px;
background-color: rgba(124, 124, 124, 0.5);
color: transparent;
color:transparent;
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
@@ -229,8 +220,6 @@
padding: var(--sp-extra-tight) 0;
&-btns button {
margin: var(--sp-tight) 0 0 0;
padding: var(--sp-ultra-tight) var(--sp-tight);
min-width: 0;
@include dir.side(margin, 0, var(--sp-tight));
}
}
@@ -266,9 +255,9 @@
}
&-count {
margin: 0 var(--sp-ultra-tight);
color: var(--tc-surface-normal);
color: var(--tc-surface-normal)
}
&-tooltip .react-emoji {
&-tooltip .react-emoji {
width: 16px;
height: 16px;
margin: 0 var(--sp-ultra-tight);
@@ -281,19 +270,19 @@
}
}
&:active {
background-color: var(--bg-surface-active);
background-color: var(--bg-surface-active)
}
&--active {
background-color: var(--bg-caution-active);
@media (hover: hover) {
&:hover {
background-color: var(--bg-caution-hover);
}
}
&:active {
background-color: var(--bg-caution-active);
background-color: var(--bg-caution-active)
}
}
}
@@ -314,12 +303,7 @@
// markdown formating
.message__body {
& h1,
h2,
h3,
h4,
h5,
h6 {
& h1, h2, h3, h4, h5, h6 {
margin: 0;
margin-bottom: var(--sp-ultra-tight);
font-weight: var(--fw-medium);
@@ -440,8 +424,7 @@
@include scrollbar.scroll__h;
@include scrollbar.scroll--auto-hide;
& td,
& th {
& td, & th {
padding: var(--sp-extra-tight);
border: 1px solid var(--bg-surface-border);
border-width: 0 1px 1px 0;
@@ -449,11 +432,11 @@
&:last-child {
border-width: 0;
border-bottom-width: 1px;
[dir='rtl'] & {
[dir=rtl] & {
border-width: 0 1px 1px 0;
}
}
[dir='rtl'] &:first-child {
[dir=rtl] &:first-child {
border-width: 0;
border-bottom-width: 1px;
}
@@ -177,7 +177,7 @@ function getUserImagePack(mx) {
}
const userImagePack = ImagePack.parsePack(mx.getUserId(), accountDataEmoji.event.content);
if (userImagePack) userImagePack.displayName ??= 'Personal Emoji';
userImagePack.displayName ??= 'Personal Emoji';
return userImagePack;
}
+1 -3
View File
@@ -56,9 +56,7 @@ function Drawer() {
useEffect(() => {
requestAnimationFrame(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = 0;
}
scrollRef.current.scrollTop = 0;
});
}, [selectedTab]);
@@ -11,7 +11,7 @@ import { selectRoom, openReusableContextMenu } from '../../../client/action/navi
import * as roomActions from '../../../client/action/room';
import {
getUsername, getUsernameOfRoomMember, getPowerLabel, hasDMWith, hasDevices,
getUsername, getUsernameOfRoomMember, getPowerLabel, hasDMWith, hasDevices
} from '../../../util/matrixUtil';
import { getEventCords } from '../../../util/common';
import colorMXID from '../../../util/colorMXID';
@@ -209,18 +209,19 @@ function ProfileFooter({ roomId, userId, onRequestClose }) {
};
const toggleIgnore = async () => {
const isIgnored = mx.getIgnoredUsers().includes(userId);
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);
if (isIgnored) {
await roomActions.unignore([userId]);
} else {
await roomActions.ignore([userId]);
}
await mx.setIgnoredUsers(ignoredUsers);
if (isMountedRef.current === false) return;
setIsUserIgnored(!isIgnored);
setIsUserIgnored(uIndex < 0);
setIsIgnoring(false);
} catch {
setIsIgnoring(false);
+45 -9
View File
@@ -8,6 +8,13 @@ import twemoji from 'twemoji';
import { twemojify } from '../../../util/twemojify';
import initMatrix from '../../../client/initMatrix';
import { toggleMarkdown } from '../../../client/action/settings';
import * as roomActions from '../../../client/action/room';
import {
openCreateRoom,
openPublicRooms,
openInviteUser,
} from '../../../client/action/navigation';
import { getEmojiForCompletion } from '../emoji-board/custom-emoji';
import AsyncSearch from '../../../util/AsyncSearch';
@@ -15,7 +22,37 @@ import Text from '../../atoms/text/Text';
import ScrollView from '../../atoms/scroll/ScrollView';
import FollowingMembers from '../../molecules/following-members/FollowingMembers';
import { addRecentEmoji, getRecentEmojis } from '../emoji-board/recent';
import commands from './commands';
const commands = [{
name: 'markdown',
description: 'Toggle markdown for messages.',
exe: () => toggleMarkdown(),
}, {
name: 'startDM',
isOptions: true,
description: 'Start direct message with user. Example: /startDM/@johndoe.matrix.org',
exe: (roomId, searchTerm) => openInviteUser(undefined, searchTerm),
}, {
name: 'createRoom',
description: 'Create new room',
exe: () => openCreateRoom(),
}, {
name: 'join',
isOptions: true,
description: 'Join room with alias. Example: /join/#cinny:matrix.org',
exe: (roomId, searchTerm) => openPublicRooms(searchTerm),
}, {
name: 'leave',
description: 'Leave current room',
exe: (roomId) => {
roomActions.leave(roomId);
},
}, {
name: 'invite',
isOptions: true,
description: 'Invite user to room. Example: /invite/@johndoe:matrix.org',
exe: (roomId, searchTerm) => openInviteUser(roomId, searchTerm),
}];
function CmdItem({ onClick, children }) {
return (
@@ -34,16 +71,16 @@ function renderSuggestions({ prefix, option, suggestions }, fireCmd) {
const cmdOptString = (typeof option === 'string') ? `/${option}` : '/?';
return cmds.map((cmd) => (
<CmdItem
key={cmd}
key={cmd.name}
onClick={() => {
fireCmd({
prefix: cmdPrefix,
option,
result: commands[cmd],
result: cmd,
});
}}
>
<Text variant="b2">{`${cmd}${cmd.isOptions ? cmdOptString : ''}`}</Text>
<Text variant="b2">{`${cmd.name}${cmd.isOptions ? cmdOptString : ''}`}</Text>
</CmdItem>
));
}
@@ -172,8 +209,8 @@ function RoomViewCmdBar({ roomId, roomTimeline, viewEvent }) {
const mx = initMatrix.matrixClient;
const setupSearch = {
'/': () => {
asyncSearch.setup(Object.keys(commands), { isContain: true });
setCmd({ prefix, suggestions: Object.keys(commands) });
asyncSearch.setup(commands, { keys: ['name'], isContain: true });
setCmd({ prefix, suggestions: commands });
},
':': () => {
const parentIds = initMatrix.roomList.getAllParentSpaces(roomId);
@@ -205,9 +242,8 @@ function RoomViewCmdBar({ roomId, roomTimeline, viewEvent }) {
}
function fireCmd(myCmd) {
if (myCmd.prefix === '/') {
viewEvent.emit('cmd_fired', {
replace: `/${myCmd.result.name}`,
});
myCmd.result.exe(roomId, myCmd.option);
viewEvent.emit('cmd_fired');
}
if (myCmd.prefix === ':') {
if (!myCmd.result.mxc) addRecentEmoji(myCmd.result.unicode);
+2 -59
View File
@@ -118,15 +118,7 @@ function handleOnClickCapture(e) {
}
}
function renderEvent(
roomTimeline,
mEvent,
prevMEvent,
isFocus,
isEdit,
setEdit,
cancelEdit,
) {
function renderEvent(roomTimeline, mEvent, prevMEvent, isFocus = false) {
const isBodyOnly = (prevMEvent !== null
&& prevMEvent.getSender() === mEvent.getSender()
&& prevMEvent.getType() !== 'm.room.member'
@@ -155,9 +147,6 @@ function renderEvent(
roomTimeline={roomTimeline}
focus={isFocus}
fullTime={false}
isEdit={isEdit}
setEdit={setEdit}
cancelEdit={cancelEdit}
/>
);
}
@@ -397,8 +386,6 @@ function RoomViewContent({ eventId, roomTimeline }) {
const timelineSVRef = useRef(null);
const timelineScrollRef = useRef(null);
const eventLimitRef = useRef(null);
const [editEventId, setEditEventId] = useState(null);
const cancelEdit = () => setEditEventId(null);
const readUptoEvtStore = useStore(roomTimeline);
const [onLimitUpdate, forceUpdateLimit] = useForceUpdate();
@@ -483,42 +470,6 @@ function RoomViewContent({ eventId, roomTimeline }) {
}
}, [newEvent]);
const listenKeyboard = useCallback((event) => {
if (event.ctrlKey || event.altKey || event.metaKey) return;
if (event.key !== 'ArrowUp') return;
if (navigation.isRawModalVisible) return;
if (document.activeElement.id !== 'message-textarea') return;
if (document.activeElement.value !== '') return;
const {
timeline: tl, activeTimeline, liveTimeline, matrixClient: mx,
} = roomTimeline;
const limit = eventLimitRef.current;
if (activeTimeline !== liveTimeline) return;
if (tl.length > limit.length) return;
const mTypes = ['m.text'];
for (let i = tl.length - 1; i >= 0; i -= 1) {
const mE = tl[i];
if (
mE.getSender() === mx.getUserId()
&& mE.getType() === 'm.room.message'
&& mTypes.includes(mE.getContent()?.msgtype)
) {
setEditEventId(mE.getId());
return;
}
}
}, [roomTimeline]);
useEffect(() => {
document.body.addEventListener('keydown', listenKeyboard);
return () => {
document.body.removeEventListener('keydown', listenKeyboard);
};
}, [listenKeyboard]);
const handleTimelineScroll = (event) => {
const timelineScroll = timelineScrollRef.current;
if (!event.target) return;
@@ -584,15 +535,7 @@ function RoomViewContent({ eventId, roomTimeline }) {
const isFocus = focusId === mEvent.getId();
if (isFocus) jumpToItemIndex = itemCountIndex;
tl.push(renderEvent(
roomTimeline,
mEvent,
isNewEvent ? null : prevMEvent,
isFocus,
editEventId === mEvent.getId(),
setEditEventId,
cancelEdit,
));
tl.push(renderEvent(roomTimeline, mEvent, isNewEvent ? null : prevMEvent, isFocus));
itemCountIndex += 1;
}
if (roomTimeline.canPaginateForward() || limit.length < timeline.length) {
+4 -5
View File
@@ -33,10 +33,9 @@ function RoomViewHeader({ roomId }) {
const [, forceUpdate] = useForceUpdate();
const mx = initMatrix.matrixClient;
const isDM = initMatrix.roomList.directs.has(roomId);
const room = mx.getRoom(roomId);
let avatarSrc = room.getAvatarUrl(mx.baseUrl, 36, 36, 'crop');
avatarSrc = isDM ? room.getAvatarFallbackMember()?.getAvatarUrl(mx.baseUrl, 36, 36, 'crop') : avatarSrc;
const roomName = room.name;
let avatarSrc = mx.getRoom(roomId).getAvatarUrl(mx.baseUrl, 36, 36, 'crop');
avatarSrc = isDM ? mx.getRoom(roomId).getAvatarFallbackMember()?.getAvatarUrl(mx.baseUrl, 36, 36, 'crop') : avatarSrc;
const roomName = mx.getRoom(roomId).name;
const roomHeaderBtnRef = useRef(null);
useEffect(() => {
@@ -94,7 +93,7 @@ function RoomViewHeader({ roomId }) {
</TitleWrapper>
<RawIcon src={ChevronBottomIC} />
</button>
{mx.isRoomEncrypted(roomId) === false && <IconButton onClick={() => toggleRoomSettings(tabText.SEARCH)} tooltip="Search" src={SearchIC} />}
<IconButton onClick={() => toggleRoomSettings(tabText.SEARCH)} tooltip="Search" src={SearchIC} />
<IconButton className="room-header__drawer-btn" onClick={togglePeopleDrawer} tooltip="People" src={UserIC} />
<IconButton className="room-header__members-btn" onClick={() => toggleRoomSettings(tabText.MEMBERS)} tooltip="Members" src={UserIC} />
<IconButton
+7 -40
View File
@@ -21,7 +21,6 @@ import ScrollView from '../../atoms/scroll/ScrollView';
import { MessageReply } from '../../molecules/message/Message';
import StickerBoard from '../sticker-board/StickerBoard';
import { confirmDialog } from '../../molecules/confirm-dialog/ConfirmDialog';
import CirclePlusIC from '../../../../public/res/ic/outlined/circle-plus.svg';
import EmojiIC from '../../../../public/res/ic/outlined/emoji.svg';
@@ -34,8 +33,6 @@ import MarkdownIC from '../../../../public/res/ic/outlined/markdown.svg';
import FileIC from '../../../../public/res/ic/outlined/file.svg';
import CrossIC from '../../../../public/res/ic/outlined/cross.svg';
import commands from './commands';
const CMD_REGEX = /(^\/|:|@)(\S*)$/;
let isTyping = false;
let isCmdActivated = false;
@@ -185,54 +182,30 @@ function RoomViewInput({
};
}, [roomId]);
const sendBody = async (body, msgType = 'm.text') => {
const sendMessage = async () => {
requestAnimationFrame(() => deactivateCmdAndEmit());
const msgBody = textAreaRef.current.value;
if (roomsInput.isSending(roomId)) return;
if (msgBody.trim() === '' && attachment === null) return;
sendIsTyping(false);
roomsInput.setMessage(roomId, body);
roomsInput.setMessage(roomId, msgBody);
if (attachment !== null) {
roomsInput.setAttachment(roomId, attachment);
}
textAreaRef.current.disabled = true;
textAreaRef.current.style.cursor = 'not-allowed';
await roomsInput.sendInput(roomId, msgType);
await roomsInput.sendInput(roomId);
textAreaRef.current.disabled = false;
textAreaRef.current.style.cursor = 'unset';
focusInput();
textAreaRef.current.value = roomsInput.getMessage(roomId);
viewEvent.emit('message_sent');
textAreaRef.current.style.height = 'unset';
if (replyTo !== null) setReplyTo(null);
};
const processCommand = (cmdBody) => {
const spaceIndex = cmdBody.indexOf(' ');
const cmdName = cmdBody.slice(1, spaceIndex > -1 ? spaceIndex : undefined);
const cmdData = spaceIndex > -1 ? cmdBody.slice(spaceIndex + 1) : '';
if (!commands[cmdName]) {
confirmDialog('Invalid Command', `"${cmdName}" is not a valid command.`, 'Alright');
return;
}
if (['me', 'shrug'].includes(cmdName)) {
commands[cmdName].exe(roomId, cmdData, (message, msgType) => sendBody(message, msgType));
return;
}
commands[cmdName].exe(roomId, cmdData);
};
const sendMessage = async () => {
requestAnimationFrame(() => deactivateCmdAndEmit());
const msgBody = textAreaRef.current.value.trim();
if (msgBody.startsWith('/')) {
processCommand(msgBody.trim());
textAreaRef.current.value = '';
textAreaRef.current.style.height = 'unset';
return;
}
if (msgBody === '' && attachment === null) return;
sendBody(msgBody, 'm.text');
};
const handleSendSticker = async (data) => {
roomsInput.sendSticker(roomId, data);
};
@@ -290,11 +263,6 @@ function RoomViewInput({
};
const handleKeyDown = (e) => {
if (e.key === 'Escape') {
e.preventDefault();
roomsInput.cancelReplyTo(roomId);
setReplyTo(null);
}
if (e.key === 'Enter' && e.shiftKey === false) {
e.preventDefault();
sendMessage();
@@ -453,7 +421,6 @@ function RoomViewInput({
/>
<MessageReply
userId={replyTo.userId}
onKeyDown={handleKeyDown}
name={getUsername(replyTo.userId)}
color={colorMXID(replyTo.userId)}
body={replyTo.body}
-211
View File
@@ -1,211 +0,0 @@
import React from 'react';
import './commands.scss';
import initMatrix from '../../../client/initMatrix';
import * as roomActions from '../../../client/action/room';
import { hasDMWith, hasDevices } from '../../../util/matrixUtil';
import { selectRoom, openReusableDialog } from '../../../client/action/navigation';
import Text from '../../atoms/text/Text';
import SettingTile from '../../molecules/setting-tile/SettingTile';
const MXID_REG = /^@\S+:\S+$/;
const ROOM_ID_ALIAS_REG = /^(#|!)\S+:\S+$/;
const ROOM_ID_REG = /^!\S+:\S+$/;
const MXC_REG = /^mxc:\/\/\S+$/;
export function processMxidAndReason(data) {
let reason;
let idData = data;
const reasonMatch = data.match(/\s-r\s/);
if (reasonMatch) {
idData = data.slice(0, reasonMatch.index);
reason = data.slice(reasonMatch.index + reasonMatch[0].length);
if (reason.trim() === '') reason = undefined;
}
const rawIds = idData.split(' ');
const userIds = rawIds.filter((id) => id.match(MXID_REG));
return {
userIds,
reason,
};
}
const commands = {
me: {
name: 'me',
description: 'Display action',
exe: (roomId, data, onSuccess) => {
const body = data.trim();
if (body === '') return;
onSuccess(body, 'm.emote');
},
},
shrug: {
name: 'shrug',
description: 'Send ¯\\_(ツ)_/¯ as message',
exe: (roomId, data, onSuccess) => onSuccess(
`¯\\_(ツ)_/¯${data.trim() !== '' ? ` ${data}` : ''}`,
'm.text',
),
},
help: {
name: 'help',
description: 'View all commands',
// eslint-disable-next-line no-use-before-define
exe: () => openHelpDialog(),
},
startdm: {
name: 'startdm',
description: 'Start DM with user. Example: /startdm userId1 userId2',
exe: async (roomId, data) => {
const mx = initMatrix.matrixClient;
const rawIds = data.split(' ');
const userIds = rawIds.filter((id) => id.match(MXID_REG) && id !== mx.getUserId());
if (userIds.length === 0) return;
if (userIds.length === 1) {
const dmRoomId = hasDMWith(userIds[0]);
if (dmRoomId) {
selectRoom(dmRoomId);
return;
}
}
const devices = await Promise.all(userIds.map(hasDevices));
const isEncrypt = devices.every((hasDevice) => hasDevice);
const result = await roomActions.createDM(userIds, isEncrypt);
selectRoom(result.room_id);
},
},
join: {
name: 'join',
description: 'Join room with alias. Example: /join alias1 alias2',
exe: (roomId, data) => {
const rawIds = data.split(' ');
const roomIds = rawIds.filter((id) => id.match(ROOM_ID_ALIAS_REG));
roomIds.map((id) => roomActions.join(id));
},
},
leave: {
name: 'leave',
description: 'Leave current room.',
exe: (roomId, data) => {
if (data.trim() === '') {
roomActions.leave(roomId);
return;
}
const rawIds = data.split(' ');
const roomIds = rawIds.filter((id) => id.match(ROOM_ID_REG));
roomIds.map((id) => roomActions.leave(id));
},
},
invite: {
name: 'invite',
description: 'Invite user to room. Example: /invite userId1 userId2 [-r reason]',
exe: (roomId, data) => {
const { userIds, reason } = processMxidAndReason(data);
userIds.map((id) => roomActions.invite(roomId, id, reason));
},
},
disinvite: {
name: 'disinvite',
description: 'Disinvite user to room. Example: /disinvite userId1 userId2 [-r reason]',
exe: (roomId, data) => {
const { userIds, reason } = processMxidAndReason(data);
userIds.map((id) => roomActions.kick(roomId, id, reason));
},
},
kick: {
name: 'kick',
description: 'Kick user from room. Example: /kick userId1 userId2 [-r reason]',
exe: (roomId, data) => {
const { userIds, reason } = processMxidAndReason(data);
userIds.map((id) => roomActions.kick(roomId, id, reason));
},
},
ban: {
name: 'ban',
description: 'Ban user from room. Example: /ban userId1 userId2 [-r reason]',
exe: (roomId, data) => {
const { userIds, reason } = processMxidAndReason(data);
userIds.map((id) => roomActions.ban(roomId, id, reason));
},
},
unban: {
name: 'unban',
description: 'Unban user from room. Example: /unban userId1 userId2',
exe: (roomId, data) => {
const rawIds = data.split(' ');
const userIds = rawIds.filter((id) => id.match(MXID_REG));
userIds.map((id) => roomActions.unban(roomId, id));
},
},
ignore: {
name: 'ignore',
description: 'Ignore user. Example: /ignore userId1 userId2',
exe: (roomId, data) => {
const rawIds = data.split(' ');
const userIds = rawIds.filter((id) => id.match(MXID_REG));
if (userIds.length > 0) roomActions.ignore(userIds);
},
},
unignore: {
name: 'unignore',
description: 'Unignore user. Example: /unignore userId1 userId2',
exe: (roomId, data) => {
const rawIds = data.split(' ');
const userIds = rawIds.filter((id) => id.match(MXID_REG));
if (userIds.length > 0) roomActions.unignore(userIds);
},
},
myroomnick: {
name: 'myroomnick',
description: 'Change my room nick',
exe: (roomId, data) => {
const nick = data.trim();
if (nick === '') return;
roomActions.setMyRoomNick(roomId, nick);
},
},
myroomavatar: {
name: 'myroomavatar',
description: 'Change my room avatar. Example /myroomavatar mxc://xyzabc',
exe: (roomId, data) => {
if (data.match(MXC_REG)) {
roomActions.setMyRoomAvatar(roomId, data);
}
},
},
converttodm: {
name: 'converttodm',
description: 'Convert room to direct message',
exe: (roomId) => {
roomActions.convertToDm(roomId);
},
},
converttoroom: {
name: 'converttoroom',
description: 'Convert direct message to room',
exe: (roomId) => {
roomActions.convertToRoom(roomId);
},
},
};
function openHelpDialog() {
openReusableDialog(
<Text variant="s1" weight="medium">Commands</Text>,
() => (
<div className="commands-dialog">
{Object.keys(commands).map((cmdName) => (
<SettingTile
key={cmdName}
title={cmdName}
content={<Text variant="b3">{commands[cmdName].description}</Text>}
/>
))}
</div>
),
);
}
export default commands;
-10
View File
@@ -1,10 +0,0 @@
.commands-dialog {
& > * {
padding: var(--sp-tight) var(--sp-normal);
border-bottom: 1px solid var(--bg-surface-border);
&:last-child {
border-bottom: none;
margin-bottom: var(--sp-extra-loose);
}
}
}
+8 -5
View File
@@ -168,7 +168,7 @@ function Search() {
}
};
const noti = initMatrix.notifications;
const notifs = initMatrix.notifications;
const renderRoomSelector = (item) => {
let imageSrc = null;
let iconSrc = null;
@@ -178,6 +178,9 @@ function Search() {
iconSrc = joinRuleToIconSrc(item.room.getJoinRule(), item.type === 'space');
}
const isUnread = notifs.hasNoti(item.roomId);
const noti = notifs.getNoti(item.roomId);
return (
<RoomSelector
key={item.roomId}
@@ -186,9 +189,9 @@ function Search() {
roomId={item.roomId}
imageSrc={imageSrc}
iconSrc={iconSrc}
isUnread={noti.hasNoti(item.roomId)}
notificationCount={noti.getTotalNoti(item.roomId)}
isAlert={noti.getHighlightNoti(item.roomId) > 0}
isUnread={isUnread}
notificationCount={noti.total}
isAlert={noti.highlight > 0}
onClick={() => openItem(item.roomId, item.type)}
/>
);
@@ -204,7 +207,7 @@ function Search() {
size="small"
>
<div className="search-dialog">
<form className="search-dialog__input" onSubmit={(e) => { e.preventDefault(); openFirstResult(); }}>
<form className="search-dialog__input" onSubmit={(e) => { e.preventDefault(); openFirstResult()}}>
<RawIcon src={SearchIC} size="small" />
<Input
onChange={handleOnChange}
+18 -26
View File
@@ -25,9 +25,6 @@ import SettingTile from '../../molecules/setting-tile/SettingTile';
import ImportE2ERoomKeys from '../../molecules/import-export-e2e-room-keys/ImportE2ERoomKeys';
import ExportE2ERoomKeys from '../../molecules/import-export-e2e-room-keys/ExportE2ERoomKeys';
import { ImagePackUser, ImagePackGlobal } from '../../molecules/image-pack/ImagePack';
import GlobalNotification from '../../molecules/global-notification/GlobalNotification';
import KeywordNotification from '../../molecules/global-notification/KeywordNotification';
import IgnoreUserList from '../../molecules/global-notification/IgnoreUserList';
import ProfileEditor from '../profile-editor/ProfileEditor';
import CrossSigning from './CrossSigning';
@@ -153,29 +150,24 @@ function NotificationsSection() {
};
return (
<>
<div className="settings-notifications">
<MenuHeader>Notification & Sound</MenuHeader>
<SettingTile
title="Desktop notification"
options={renderOptions()}
content={<Text variant="b3">Show desktop notification when new messages arrive.</Text>}
/>
<SettingTile
title="Notification Sound"
options={(
<Toggle
isActive={settings.isNotificationSounds}
onToggle={() => { toggleNotificationSounds(); updateState({}); }}
/>
)}
content={<Text variant="b3">Play sound when new messages arrive.</Text>}
/>
</div>
<GlobalNotification />
<KeywordNotification />
<IgnoreUserList />
</>
<div className="settings-notifications">
<MenuHeader>Notification & Sound</MenuHeader>
<SettingTile
title="Desktop notification"
options={renderOptions()}
content={<Text variant="b3">Show desktop notification when new messages arrive.</Text>}
/>
<SettingTile
title="Notification Sound"
options={(
<Toggle
isActive={settings.isNotificationSounds}
onToggle={() => { toggleNotificationSounds(); updateState({}); }}
/>
)}
content={<Text variant="b3">Play sound when new messages arrive.</Text>}
/>
</div>
);
}
-3
View File
@@ -38,9 +38,6 @@
}
.settings-appearance__card,
.settings-notifications,
.global-notification,
.keyword-notification,
.ignore-user-list,
.settings-security__card,
.settings-security .device-manage,
.settings-about__card,
+6 -59
View File
@@ -6,7 +6,7 @@ import { getIdServer } from '../../util/matrixUtil';
/**
* https://github.com/matrix-org/matrix-react-sdk/blob/1e6c6e9d800890c732d60429449bc280de01a647/src/Rooms.js#L73
* @param {string} roomId Id of room to add
* @param {string} userId User id to which dm || undefined to remove
* @param {string} userId User id to which dm
* @returns {Promise} A promise
*/
function addRoomToMDirect(roomId, userId) {
@@ -79,23 +79,13 @@ function guessDMRoomTargetId(room, myUserId) {
return oldestMember.userId;
}
function convertToDm(roomId) {
const mx = initMatrix.matrixClient;
const room = mx.getRoom(roomId);
return addRoomToMDirect(roomId, guessDMRoomTargetId(room, mx.getUserId()));
}
function convertToRoom(roomId) {
return addRoomToMDirect(roomId, undefined);
}
/**
*
* @param {string} roomId
* @param {boolean} isDM
* @param {string[]} via
*/
async function join(roomIdOrAlias, isDM = false, via = undefined) {
async function join(roomIdOrAlias, isDM, via) {
const mx = initMatrix.matrixClient;
const roomIdParts = roomIdOrAlias.split(':');
const viaServers = via || [roomIdParts[1]];
@@ -160,10 +150,10 @@ async function create(options, isDM = false) {
}
}
async function createDM(userIdOrIds, isEncrypted = true) {
async function createDM(userId, isEncrypted = true) {
const options = {
is_direct: true,
invite: Array.isArray(userIdOrIds) ? userIdOrIds : [userIdOrIds],
invite: [userId],
visibility: 'private',
preset: 'trusted_private_chat',
initial_state: [],
@@ -272,10 +262,10 @@ async function createRoom(opts) {
return result;
}
async function invite(roomId, userId, reason) {
async function invite(roomId, userId) {
const mx = initMatrix.matrixClient;
const result = await mx.invite(roomId, userId, undefined, reason);
const result = await mx.invite(roomId, userId);
return result;
}
@@ -300,21 +290,6 @@ async function unban(roomId, userId) {
return result;
}
async function ignore(userIds) {
const mx = initMatrix.matrixClient;
let ignoredUsers = mx.getIgnoredUsers().concat(userIds);
ignoredUsers = [...new Set(ignoredUsers)];
await mx.setIgnoredUsers(ignoredUsers);
}
async function unignore(userIds) {
const mx = initMatrix.matrixClient;
const ignoredUsers = mx.getIgnoredUsers();
await mx.setIgnoredUsers(ignoredUsers.filter((id) => !userIds.includes(id)));
}
async function setPowerLevel(roomId, userId, powerLevel) {
const mx = initMatrix.matrixClient;
const room = mx.getRoom(roomId);
@@ -325,37 +300,9 @@ async function setPowerLevel(roomId, userId, powerLevel) {
return result;
}
async function setMyRoomNick(roomId, nick) {
const mx = initMatrix.matrixClient;
const room = mx.getRoom(roomId);
const mEvent = room.currentState.getStateEvents('m.room.member', mx.getUserId());
const content = mEvent?.getContent();
if (!content) return;
await mx.sendStateEvent(roomId, 'm.room.member', {
...content,
displayname: nick,
}, mx.getUserId());
}
async function setMyRoomAvatar(roomId, mxc) {
const mx = initMatrix.matrixClient;
const room = mx.getRoom(roomId);
const mEvent = room.currentState.getStateEvents('m.room.member', mx.getUserId());
const content = mEvent?.getContent();
if (!content) return;
await mx.sendStateEvent(roomId, 'm.room.member', {
...content,
avatar_url: mxc,
}, mx.getUserId());
}
export {
convertToDm,
convertToRoom,
join, leave,
createDM, createRoom,
invite, kick, ban, unban,
ignore, unignore,
setPowerLevel,
setMyRoomNick, setMyRoomAvatar,
};
+1 -4
View File
@@ -67,7 +67,7 @@ class InitMatrix extends EventEmitter {
},
PREPARED: (prevState) => {
console.log('PREPARED state');
console.log('Previous state: ', prevState);
console.log('previous state: ', prevState);
// TODO: remove global.initMatrix at end
global.initMatrix = this;
if (prevState === null) {
@@ -76,9 +76,6 @@ class InitMatrix extends EventEmitter {
this.roomsInput = new RoomsInput(this.matrixClient, this.roomList);
this.notifications = new Notifications(this.roomList);
this.emit('init_loading_finished');
this.notifications._initNoti();
} else {
this.notifications._initNoti();
}
},
RECONNECTING: () => {
+6 -43
View File
@@ -5,11 +5,6 @@ import { selectRoom } from '../action/navigation';
import cons from './cons';
import navigation from './navigation';
import settings from './settings';
import { setFavicon } from '../../util/common';
import LogoSVG from '../../../public/res/svg/cinny.svg';
import LogoUnreadSVG from '../../../public/res/svg/cinny-unread.svg';
import LogoHighlightSVG from '../../../public/res/svg/cinny-highlight.svg';
function isNotifEvent(mEvent) {
const eType = mEvent.getType();
@@ -37,24 +32,22 @@ class Notifications extends EventEmitter {
constructor(roomList) {
super();
this.initialized = false;
this.favicon = LogoSVG;
this.matrixClient = roomList.matrixClient;
this.roomList = roomList;
this.roomIdToNoti = new Map();
// this._initNoti();
this._initNoti();
this._listenEvents();
// Ask for permission by default after loading
window.Notification?.requestPermission();
// TODO:
window.notifications = this;
}
async _initNoti() {
this.initialized = false;
this.roomIdToNoti = new Map();
_initNoti() {
const addNoti = (roomId) => {
const room = this.matrixClient.getRoom(roomId);
if (this.getNotiType(room.roomId) === cons.notifs.MUTE) return;
@@ -66,9 +59,6 @@ class Notifications extends EventEmitter {
};
[...this.roomList.rooms].forEach(addNoti);
[...this.roomList.directs].forEach(addNoti);
this.initialized = true;
this._updateFavicon();
}
doesRoomHaveUnread(room) {
@@ -114,8 +104,7 @@ class Notifications extends EventEmitter {
}
getTotalNoti(roomId) {
const { total, highlight } = this.getNoti(roomId);
if (highlight > total) return highlight;
const { total } = this.getNoti(roomId);
return total;
}
@@ -140,30 +129,6 @@ class Notifications extends EventEmitter {
}
}
async _updateFavicon() {
if (!this.initialized) return;
let unread = false;
let highlight = false;
[...this.roomIdToNoti.values()].find((noti) => {
if (!unread) {
unread = noti.total > 0 || noti.highlight > 0;
}
highlight = noti.highlight > 0;
if (unread && highlight) return true;
return false;
});
let newFavicon = LogoSVG;
if (unread && !highlight) {
newFavicon = LogoUnreadSVG;
}
if (unread && highlight) {
newFavicon = LogoHighlightSVG;
}
if (newFavicon === this.favicon) return;
this.favicon = newFavicon;
setFavicon(this.favicon);
}
_setNoti(roomId, total, highlight) {
const addNoti = (id, t, h, fromId) => {
const prevTotal = this.roomIdToNoti.get(id)?.total ?? null;
@@ -190,7 +155,6 @@ class Notifications extends EventEmitter {
allParentSpaces.forEach((spaceId) => {
addNoti(spaceId, addT, addH, roomId);
});
this._updateFavicon();
}
_deleteNoti(roomId, total, highlight) {
@@ -223,7 +187,6 @@ class Notifications extends EventEmitter {
allParentSpaces.forEach((spaceId) => {
removeNoti(spaceId, total, highlight, roomId);
});
this._updateFavicon();
}
async _displayPopupNoti(mEvent, room) {
+1 -14
View File
@@ -257,10 +257,10 @@ class RoomList extends EventEmitter {
const latestMDirects = this.getMDirects();
latestMDirects.forEach((directId) => {
const myRoom = this.matrixClient.getRoom(directId);
if (this.mDirects.has(directId)) return;
this.mDirects.add(directId);
const myRoom = this.matrixClient.getRoom(directId);
if (myRoom === null) return;
if (myRoom.getMyMembership() === 'join') {
this.directs.add(directId);
@@ -268,19 +268,6 @@ class RoomList extends EventEmitter {
this.emit(cons.events.roomList.ROOMLIST_UPDATED);
}
});
[...this.directs].forEach((directId) => {
if (latestMDirects.has(directId)) return;
this.mDirects.delete(directId);
const myRoom = this.matrixClient.getRoom(directId);
if (myRoom === null) return;
if (myRoom.getMyMembership() === 'join') {
this.directs.delete(directId);
this.rooms.add(directId);
this.emit(cons.events.roomList.ROOMLIST_UPDATED);
}
});
});
this.matrixClient.on('Room.name', (room) => {
+16 -12
View File
@@ -1,12 +1,15 @@
import EventEmitter from 'events';
import { micromark } from 'micromark';
import { gfm, gfmHtml } from 'micromark-extension-gfm';
import encrypt from 'browser-encrypt-attachment';
import { math } from 'micromark-extension-math';
import { encode } from 'blurhash';
import { getShortcodeToEmoji } from '../../app/organisms/emoji-board/custom-emoji';
import { mathExtensionHtml, spoilerExtension, spoilerExtensionHtml } from '../../util/markdown';
import { getBlobSafeMimeType } from '../../util/mimetypes';
import { sanitizeText } from '../../util/sanitize';
import cons from './cons';
import settings from './settings';
import { htmlOutput, parser } from '../../util/markdown';
const blurhashField = 'xyz.amorgan.blurhash';
const MXID_REGEX = /\B@\S+:\S+\.\S+[^.,:;?!\s]/g;
@@ -101,11 +104,14 @@ function getVideoThumbnail(video, width, height, mimeType) {
}
function getFormattedBody(markdown) {
let content = parser(markdown);
if (content.length === 1 && content[0].type === 'paragraph') {
content = content[0].content;
}
return htmlOutput(content);
const result = micromark(markdown, {
extensions: [gfm(), spoilerExtension(), math()],
htmlExtensions: [gfmHtml(), spoilerExtensionHtml, mathExtensionHtml],
});
const bodyParts = result.match(/^(<p>)(.*)(<\/p>)$/);
if (bodyParts === null) return result;
if (bodyParts[2].indexOf('</p>') >= 0) return result;
return bodyParts[2];
}
function getReplyFormattedBody(roomId, reply) {
@@ -274,7 +280,7 @@ class RoomsInput extends EventEmitter {
return this.roomIdToInput.get(roomId)?.isSending || false;
}
async sendInput(roomId, msgType) {
async sendInput(roomId) {
const room = this.matrixClient.getRoom(roomId);
const input = this.getInput(roomId);
input.isSending = true;
@@ -288,7 +294,7 @@ class RoomsInput extends EventEmitter {
const rawMessage = input.message;
let content = {
body: rawMessage,
msgtype: msgType ?? 'm.text',
msgtype: 'm.text',
};
// Apply formatting if relevant
@@ -459,14 +465,12 @@ class RoomsInput extends EventEmitter {
const room = this.matrixClient.getRoom(roomId);
const isReply = typeof mEvent.getWireContent()['m.relates_to']?.['m.in_reply_to'] !== 'undefined';
const msgtype = mEvent.getWireContent().msgtype ?? 'm.text';
const content = {
body: ` * ${editedBody}`,
msgtype,
msgtype: 'm.text',
'm.new_content': {
body: editedBody,
msgtype,
msgtype: 'm.text',
},
'm.relates_to': {
event_id: mEvent.getId(),
+1 -1
View File
@@ -1,5 +1,5 @@
const cons = {
version: '2.1.3',
version: '2.1.2',
secretKey: {
ACCESS_TOKEN: 'cinny_access_token',
DEVICE_ID: 'cinny_device_id',
+5 -13
View File
@@ -39,7 +39,7 @@ class Navigation extends EventEmitter {
}
_mapRoomToSpace(roomId) {
const { roomList, accountData } = this.initMatrix;
const { roomList } = this.initMatrix;
if (
this.selectedTab === cons.tabs.HOME
&& roomList.rooms.has(roomId)
@@ -61,21 +61,13 @@ class Navigation extends EventEmitter {
const parents = roomList.roomIdToParents.get(roomId);
if (!parents) return;
if (parents.has(this.selectedSpaceId)) {
this.spaceToRoom.set(this.selectedSpaceId, {
[...parents].forEach((pId) => {
this.spaceToRoom.set(pId, {
roomId,
timestamp: Date.now(),
});
} else if (accountData.categorizedSpaces.has(this.selectedSpaceId)) {
const categories = roomList.getCategorizedSpaces([this.selectedSpaceId]);
const parent = [...parents].find((pId) => categories.has(pId));
if (parent) {
this.spaceToRoom.set(parent, {
roomId,
timestamp: Date.now(),
});
}
}
});
}
_selectRoom(roomId, eventId) {
-10
View File
@@ -115,16 +115,6 @@ export function avatarInitials(text) {
return [...text][0];
}
export function cssVar(name) {
return getComputedStyle(document.body).getPropertyValue(name);
}
export function setFavicon(url) {
const favicon = document.querySelector('#favicon');
if (!favicon) return;
favicon.setAttribute('href', url);
}
export function copyToClipboard(text) {
if (navigator.clipboard) {
navigator.clipboard.writeText(text);
+187 -78
View File
@@ -1,89 +1,198 @@
import SimpleMarkdown from '@khanacademy/simple-markdown';
/* eslint-disable no-param-reassign */
/* eslint-disable no-plusplus */
/* eslint-disable no-continue */
const {
defaultRules, parserFor, outputFor, anyScopeRegex, blockRegex, inlineRegex, htmlTag, sanitizeText,
} = SimpleMarkdown;
import { codes } from 'micromark-util-symbol/codes';
import { types } from 'micromark-util-symbol/types';
import { resolveAll } from 'micromark-util-resolve-all';
import { splice } from 'micromark-util-chunked';
function mathHtml(wrap, node) {
return htmlTag(wrap, htmlTag('code', sanitizeText(node.content)), { 'data-mx-maths': node.content });
function inlineExtension(marker, len, key) {
const keySeq = `${key}Sequence`;
const keySeqTmp = `${keySeq}Temporary`;
return () => {
function tokenize(effects, ok, nok) {
const { previous, events } = this;
let size = 0;
function more(code) {
// consume more markers if the maximum length hasn't been reached yet
if (code === marker && size < len) {
effects.consume(code);
size += 1;
return more;
}
// check for minimum length
if (size < len) return nok(code);
effects.exit(keySeqTmp);
return ok(code);
}
function start(code) {
// ignore code if it's not a marker
if (code !== marker) return nok(code);
if (previous === marker
&& events[events.length - 1][1].type !== types.characterEscape) return nok(code);
effects.enter(keySeqTmp);
return more(code);
}
return start;
}
function resolve(events, context) {
let i = -1;
while (++i < events.length) {
if (events[i][0] !== 'enter' || events[i][1].type !== keySeqTmp) continue;
let open = i;
while (open--) {
if (events[open][0] !== 'exit' || events[open][1].type !== keySeqTmp) continue;
events[i][1].type = keySeq;
events[open][1].type = keySeq;
const border = {
type: key,
start: { ...events[open][1].start },
end: { ...events[i][1].end },
};
const text = {
type: `${key}Text`,
start: { ...events[open][1].end },
end: { ...events[i][1].start },
};
const nextEvents = [
['enter', border, context],
['enter', events[open][1], context],
['exit', events[open][1], context],
['enter', text, context],
];
splice(
nextEvents,
nextEvents.length,
0,
resolveAll(
context.parser.constructs.insideSpan.null,
events.slice(open + 1, i),
context,
),
);
splice(nextEvents, nextEvents.length, 0, [
['exit', text, context],
['enter', events[i][1], context],
['exit', events[i][1], context],
['exit', border, context],
]);
splice(events, open - 1, i - open + 3, nextEvents);
i = open + nextEvents.length - 2;
break;
}
}
events.forEach((event) => {
if (event[1].type === keySeqTmp) {
event[1].type = types.data;
}
});
return events;
}
const tokenizer = {
tokenize,
resolveAll: resolve,
};
return {
text: { [marker]: tokenizer },
insideSpan: { null: [tokenizer] },
attentionMarkers: { null: [marker] },
};
};
}
const rules = {
...defaultRules,
Array: {
...defaultRules.Array,
plain: (arr, output, state) => arr.map((node) => output(node, state)).join(''),
const spoilerExtension = inlineExtension(codes.verticalBar, 2, 'spoiler');
const spoilerExtensionHtml = {
enter: {
spoiler() {
this.tag('<span data-mx-spoiler>');
},
},
displayMath: {
order: defaultRules.list.order + 0.5,
match: blockRegex(/^\$\$\n*([\s\S]+?)\n*\$\$/),
parse: (capture) => ({ content: capture[1] }),
plain: (node) => `$$\n${node.content}\n$$`,
html: (node) => mathHtml('div', node),
},
newline: {
...defaultRules.newline,
plain: () => '\n',
},
paragraph: {
...defaultRules.paragraph,
plain: (node, output, state) => `${output(node.content, state)}\n\n`,
html: (node, output, state) => htmlTag('p', output(node.content, state)),
},
escape: {
...defaultRules.escape,
plain: (node, output, state) => `\\${output(node.content, state)}`,
},
em: {
...defaultRules.em,
plain: (node, output, state) => `_${output(node.content, state)}_`,
},
strong: {
...defaultRules.strong,
plain: (node, output, state) => `**${output(node.content, state)}**`,
},
u: {
...defaultRules.u,
plain: (node, output, state) => `__${output(node.content, state)}__`,
},
del: {
...defaultRules.del,
plain: (node, output, state) => `~~${output(node.content, state)}~~`,
},
spoiler: {
order: defaultRules.em.order - 0.5,
match: inlineRegex(/^\|\|([\s\S]+?)\|\|(?:\(([\s\S]+?)\))?/),
parse: (capture, parse, state) => ({
content: parse(capture[1], state),
reason: capture[2],
}),
plain: (node) => `[spoiler${node.reason ? `: ${node.reason}` : ''}](mxc://somewhere)`,
html: (node, output, state) => `<span data-mx-spoiler${node.reason ? `="${sanitizeText(node.reason)}"` : ''}>${output(node.content, state)}</span>`,
},
inlineMath: {
order: defaultRules.del.order + 0.5,
match: inlineRegex(/^\$(\S[\s\S]+?\S|\S)\$(?!\d)/),
parse: (capture) => ({ content: capture[1] }),
plain: (node) => `$${node.content}$`,
html: (node) => mathHtml('span', node),
},
br: {
...defaultRules.br,
match: anyScopeRegex(/^ *\n/),
plain: () => '\n',
},
text: {
...defaultRules.text,
match: anyScopeRegex(/^[\s\S]+?(?=[^0-9A-Za-z\s\u00c0-\uffff]| *\n|\w+:\S|$)/),
plain: (node) => node.content,
exit: {
spoiler() {
this.tag('</span>');
},
},
};
const parser = parserFor(rules);
const plainOutput = outputFor(rules, 'plain');
const htmlOutput = outputFor(rules, 'html');
const mathExtensionHtml = {
enter: {
mathFlow() {
this.lineEndingIfNeeded();
},
mathFlowFenceMeta() {
this.buffer();
},
mathText() {
this.buffer();
},
},
exit: {
mathFlow() {
const value = this.encode(this.resume().replace(/(?:\r?\n|\r)$/, ''));
this.tag('<div data-mx-maths="');
this.tag(value);
this.tag('"><code>');
this.raw(value);
this.tag('</code></div>');
this.setData('mathFlowOpen');
this.setData('slurpOneLineEnding');
},
mathFlowFence() {
// After the first fence.
if (!this.getData('mathFlowOpen')) {
this.setData('mathFlowOpen', true);
this.setData('slurpOneLineEnding', true);
this.buffer();
}
},
mathFlowFenceMeta() {
this.resume();
},
mathFlowValue(token) {
this.raw(this.sliceSerialize(token));
},
mathText() {
const value = this.encode(this.resume());
this.tag('<span data-mx-maths="');
this.tag(value);
this.tag('"><code>');
this.raw(value);
this.tag('</code></span>');
},
mathTextData(token) {
this.raw(this.sliceSerialize(token));
},
},
};
export {
parser, plainOutput, htmlOutput,
inlineExtension,
spoilerExtension, spoilerExtensionHtml,
mathExtensionHtml,
};
+3 -4
View File
@@ -26,13 +26,12 @@ export const ALLOWED_BLOB_MIMETYPES = [
];
export function getBlobSafeMimeType(mimetype) {
const [type] = mimetype.split(';');
if (!ALLOWED_BLOB_MIMETYPES.includes(type)) {
if (!ALLOWED_BLOB_MIMETYPES.includes(mimetype)) {
return 'application/octet-stream';
}
// Required for Chromium browsers
if (type === 'video/quicktime') {
if (mimetype === 'video/quicktime') {
return 'video/mp4';
}
return type;
return mimetype;
}
+1 -1
View File
@@ -19,7 +19,7 @@ const permittedTagToAttributes = {
div: ['data-mx-maths'],
a: ['name', 'target', 'href', 'rel'],
img: ['width', 'height', 'alt', 'title', 'src', 'data-mx-emoticon'],
ol: ['start'],
o: ['start'],
code: ['class'],
};
+18 -2
View File
@@ -1,4 +1,5 @@
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const webpack = require('webpack');
@@ -51,12 +52,27 @@ module.exports = {
},
plugins: [
new HtmlWebpackPlugin({ template: './public/index.html' }),
new FaviconsWebpackPlugin({
logo: './public/res/svg/cinny.svg',
mode: 'webapp',
devMode: 'light',
favicons: {
appName: 'Cinny',
appDescription: 'Yet another matrix client',
developerName: 'Ajay Bura',
developerURL: 'https://github.com/ajbura',
icons: {
coast: false,
yandex: false,
appleStartup: false,
}
}
}),
new CopyPlugin({
patterns: [
{ from: 'node_modules/@matrix-org/olm/olm.wasm' },
{ from: 'olm.wasm' },
{ from: '_redirects' },
{ from: 'config.json' },
{ from: 'public/res/android'}
],
}),
new webpack.ProvidePlugin({