Compare commits

..
Author SHA1 Message Date
Krishan de198b8e96 Merge branch 'dev' into update-actions 2022-09-07 13:45:56 +05:30
Krishan 8b6dcc1427 fix name 2022-09-07 12:37:45 +05:30
Krishan 8e18cc918f Simplify PR actions 2022-09-07 12:24:16 +05:30
Krishan 382d880110 Replace action with one we use already 2022-09-07 12:22:28 +05:30
85 changed files with 17551 additions and 4213 deletions

No files matched your search

+3
View File
@@ -1,2 +1,5 @@
webpack.common.js
webpack.dev.js
webpack.prod.js
experiment
node_modules
+2 -35
View File
@@ -4,58 +4,25 @@ module.exports = {
es2021: true,
},
extends: [
"eslint:recommended",
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
'plugin:react/recommended',
'airbnb',
'prettier',
],
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 'latest',
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'react',
'@typescript-eslint'
],
rules: {
'linebreak-style': 0,
'no-underscore-dangle': 0,
"no-shadow": "off",
"import/prefer-default-export": "off",
"import/extensions": "off",
"import/no-unresolved": "off",
"import/no-extraneous-dependencies": [
"error",
{
devDependencies: true,
},
],
'react/no-unstable-nested-components': [
'error',
{ allowAsProps: true },
],
"react/jsx-filename-extension": [
"error",
{
extensions: [".tsx", ".jsx"],
},
],
"react/require-default-props": "off",
"react/jsx-props-no-spreading": "off",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "error",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-shadow": "error"
},
};
+3 -3
View File
@@ -1,8 +1,7 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base",
":dependencyDashboardApproval"
"config:base"
],
"labels": [ "Dependencies" ],
"packageRules": [
@@ -11,5 +10,6 @@
}
],
"lockFileMaintenance": { "enabled": true },
"dependencyDashboard": true
"dependencyDashboard": true,
"dependencyDashboardApproval": true
}
+9 -9
View File
@@ -1,4 +1,4 @@
name: Build pull request
name: 'Build pull request'
on:
pull_request:
@@ -6,24 +6,24 @@ on:
jobs:
build-pull-request:
name: Build pull request
name: 'Build pull request'
runs-on: ubuntu-latest
env:
PR_NUMBER: ${{github.event.number}}
steps:
- name: Checkout repository
uses: actions/checkout@v3.2.0
uses: actions/checkout@v3.0.2
- name: Setup node
uses: actions/setup-node@v3.5.1
uses: actions/setup-node@v3.4.1
with:
node-version: 18.12.1
cache: "npm"
node-version: 17.9.0
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build app
run: npm run build
- name: Upload artifact
uses: actions/upload-artifact@v3.1.1
uses: actions/upload-artifact@v3.1.0
with:
name: preview
path: dist
@@ -31,8 +31,8 @@ jobs:
- name: Save pr number
run: echo ${PR_NUMBER} > ./pr.txt
- name: Upload pr number
uses: actions/upload-artifact@v3.1.1
uses: actions/upload-artifact@v3.1.0
with:
name: pr
path: ./pr.txt
retention-days: 1
retention-days: 1
+10 -13
View File
@@ -1,13 +1,11 @@
name: Deploy PR to Netlify
on:
workflow_run:
workflows: ["Build pull request"]
types: [completed]
jobs:
deploy-pull-request:
name: Deploy pull request
name: 'Deploy pull request'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -15,16 +13,16 @@ jobs:
if: ${{ github.event.workflow_run.conclusion == 'success' }}
steps:
- name: Download pr number
uses: dawidd6/action-download-artifact@e6e25ac3a2b93187502a8be1ef9e9603afc34925
uses: dawidd6/action-download-artifact@7847792dd435a50521b8e3bd3576dae7459d1fa8
with:
workflow: ${{ github.event.workflow.id }}
run_id: ${{ github.event.workflow_run.id }}
name: pr
- name: Output pr number
id: pr
run: echo "id=$(<pr.txt)" >> $GITHUB_OUTPUT
run: echo "::set-output name=id::$(<pr.txt)"
- name: Download artifact
uses: dawidd6/action-download-artifact@e6e25ac3a2b93187502a8be1ef9e9603afc34925
uses: dawidd6/action-download-artifact@7847792dd435a50521b8e3bd3576dae7459d1fa8
with:
workflow: ${{ github.event.workflow.id }}
run_id: ${{ github.event.workflow_run.id }}
@@ -32,7 +30,7 @@ jobs:
path: dist
- name: Deploy to Netlify
id: netlify
uses: nwtgck/actions-netlify@5da65c9f74c7961c5501a3ba329b8d0912f39c03
uses: nwtgck/actions-netlify@b7c1504e00c6b8a249d1848cc1b522a4865eed99
with:
publish-dir: dist
deploy-message: "Deploy PR ${{ steps.pr.outputs.id }}"
@@ -42,15 +40,14 @@ jobs:
enable-commit-comment: false
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_PR_CINNY }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE3_ID }}
timeout-minutes: 1
- name: Comment preview on PR
uses: thollander/actions-comment-pull-request@c22fb302208b7b170d252a61a505d2ea27245eff
- name: Edit PR Description
uses: Beakyn/gha-comment-pull-request@2167a7aee24f9e61ce76a23039f322e49a990409
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
pr_number: ${{ steps.pr.outputs.id }}
comment_tag: ${{ steps.pr.outputs.id }}
message: |
pull-request-number: ${{ steps.pr.outputs.id }}
description-message: |
Preview: ${{ steps.netlify.outputs.deploy-url }}
⚠️ Exercise caution. Use test accounts. ⚠️
+4 -2
View File
@@ -9,11 +9,13 @@ on:
jobs:
docker-build:
runs-on: ubuntu-latest
env:
PR_NUMBER: ${{github.event.number}}
steps:
- name: Checkout repository
uses: actions/checkout@v3.2.0
uses: actions/checkout@v3.0.2
- name: Build Docker image
uses: docker/build-push-action@v3.2.0
uses: docker/build-push-action@v3.1.1
with:
context: .
push: false
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v3.2.0
uses: actions/checkout@v3.0.2
- name: NPM Lockfile Changes
uses: codepunkt/npm-lockfile-changes@b40543471c36394409466fdb277a73a0856d7891
with:
+8 -8
View File
@@ -1,4 +1,4 @@
name: Deploy to Netlify (dev)
name: 'Deploy to Netlify (dev)'
on:
push:
@@ -7,22 +7,22 @@ on:
jobs:
deploy-to-netlify:
name: Deploy to Netlify
name: 'Deploy to Netlify'
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3.2.0
uses: actions/checkout@v3.0.2
- name: Setup node
uses: actions/setup-node@v3.5.1
uses: actions/setup-node@v3.4.1
with:
node-version: 18.12.1
cache: "npm"
node-version: 17.9.0
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build app
run: npm run build
- name: Deploy to Netlify
uses: nwtgck/actions-netlify@5da65c9f74c7961c5501a3ba329b8d0912f39c03
uses: nwtgck/actions-netlify@b7c1504e00c6b8a249d1848cc1b522a4865eed99
with:
publish-dir: dist
deploy-message: "Dev deploy ${{ github.sha }}"
@@ -33,5 +33,5 @@ jobs:
github-deployment-description: 'Nightly deployment on each commit to dev branch'
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_DEV }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE2_ID }}
timeout-minutes: 1
+16 -16
View File
@@ -1,4 +1,4 @@
name: Production deploy
name: 'Production deploy'
on:
release:
@@ -6,22 +6,22 @@ on:
jobs:
deploy-and-tarball:
name: Netlify deploy and tarball
name: 'Netlify deploy and tarball'
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3.2.0
uses: actions/checkout@v3.0.2
- name: Setup node
uses: actions/setup-node@v3.5.1
uses: actions/setup-node@v3.4.1
with:
node-version: 18.12.1
cache: "npm"
node-version: 17.9.0
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build app
run: npm run build
- name: Deploy to Netlify
uses: nwtgck/actions-netlify@5da65c9f74c7961c5501a3ba329b8d0912f39c03
uses: nwtgck/actions-netlify@b7c1504e00c6b8a249d1848cc1b522a4865eed99
with:
publish-dir: dist
deploy-message: "Prod deploy ${{ github.ref_name }}"
@@ -32,7 +32,7 @@ jobs:
github-deployment-description: 'Stable deployment on each release'
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_APP }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
timeout-minutes: 1
- name: Get version from tag
id: vars
@@ -50,7 +50,7 @@ jobs:
gpg --export | xxd -p
echo '${{ secrets.GNUPG_PASSPHRASE }}' | gpg --batch --yes --pinentry-mode loopback --passphrase-fd 0 --armor --detach-sign cinny-${{ steps.vars.outputs.tag }}.tar.gz
- name: Upload tagged release
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844
uses: softprops/action-gh-release@1e07f4398721186383de40550babbdf2b84acfc5
with:
files: |
cinny-${{ steps.vars.outputs.tag }}.tar.gz
@@ -64,31 +64,31 @@ jobs:
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v3.2.0
uses: actions/checkout@v3.0.2
- name: Set up QEMU
uses: docker/setup-qemu-action@v2.1.0
uses: docker/setup-qemu-action@v2.0.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2.2.1
uses: docker/setup-buildx-action@v2.0.0
- name: Login to Docker Hub
uses: docker/login-action@v2.1.0
uses: docker/login-action@v2.0.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to the Container registry
uses: docker/login-action@v2.1.0
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.1.1
uses: docker/metadata-action@v4.0.1
with:
images: |
${{ secrets.DOCKER_USERNAME }}/cinny
ghcr.io/${{ github.repository }}
- name: Build and push Docker image
uses: docker/build-push-action@v3.2.0
uses: docker/build-push-action@v3.1.1
with:
context: .
platforms: linux/amd64,linux/arm64
-6
View File
@@ -1,6 +0,0 @@
dist
node_modules
package.json
package-lock.json
LICENSE
README.md
-4
View File
@@ -1,4 +0,0 @@
{
"printWidth": 100,
"singleQuote": true
}
-3
View File
@@ -1,3 +0,0 @@
{
"recommendations": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"]
}
-5
View File
@@ -1,5 +0,0 @@
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"typescript.tsdk": "node_modules/typescript/lib"
}
+1 -1
View File
@@ -41,4 +41,4 @@ Also, we use [ESLint](https://eslint.org/) for clean and stylistically consisten
## 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/index.html)
- [Matrix JavaScript SDK documentation](https://matrix-org.github.io/matrix-js-sdk/19.2.0/index.html)
+2 -2
View File
@@ -1,5 +1,5 @@
## Builder
FROM node:18.12.1-alpine3.15 as builder
FROM node:17.9.0-alpine3.15 as builder
WORKDIR /src
@@ -10,7 +10,7 @@ RUN npm run build
## App
FROM nginx:1.23.3-alpine
FROM nginx:1.23.1-alpine
COPY --from=builder /src/dist /app
+1 -1
View File
@@ -84,7 +84,7 @@ UeGsouhyuITLwEhScounZDqop+Dx
## Local development
> 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 Hydrogen LTS (v18).
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:
```sh
+1 -1
View File
@@ -1,9 +1,9 @@
{
"defaultHomeserver": 3,
"homeserverList": [
"converser.eu",
"envs.net",
"halogen.city",
"kde.org",
"matrix.org",
"mozilla.org"
],
-101
View File
@@ -1,101 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cinny</title>
<meta name="name" content="Cinny" />
<meta name="author" content="Ajay Bura" />
<meta
name="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="keywords"
content="cinny, cinnyapp, cinnychat, matrix, matrix client, matrix.org, element"
/>
<meta property="og:title" content="Cinny" />
<meta property="og:url" content="https://cinny.in" />
<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="./public/favicon.ico" />
<link rel="manifest" href="./public/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="./public/res/apple/apple-touch-icon-57x57.png"
/>
<link
rel="apple-touch-icon"
sizes="60x60"
href="./public/res/apple/apple-touch-icon-60x60.png"
/>
<link
rel="apple-touch-icon"
sizes="72x72"
href="./public/res/apple/apple-touch-icon-72x72.png"
/>
<link
rel="apple-touch-icon"
sizes="76x76"
href="./public/res/apple/apple-touch-icon-76x76.png"
/>
<link
rel="apple-touch-icon"
sizes="114x114"
href="./public/res/apple/apple-touch-icon-114x114.png"
/>
<link
rel="apple-touch-icon"
sizes="120x120"
href="./public/res/apple/apple-touch-icon-120x120.png"
/>
<link
rel="apple-touch-icon"
sizes="144x144"
href="./public/res/apple/apple-touch-icon-144x144.png"
/>
<link
rel="apple-touch-icon"
sizes="152x152"
href="./public/res/apple/apple-touch-icon-152x152.png"
/>
<link
rel="apple-touch-icon"
sizes="167x167"
href="./public/res/apple/apple-touch-icon-167x167.png"
/>
<link
rel="apple-touch-icon"
sizes="180x180"
href="./public/res/apple/apple-touch-icon-180x180.png"
/>
</head>
<body id="appBody">
<script>
window.global ||= window;
</script>
<div id="root"></div>
<audio id="notificationSound">
<source src="./public/sound/notification.ogg" type="audio/ogg" />
</audio>
<audio id="inviteSound">
<source src="./public/sound/invite.ogg" type="audio/ogg" />
</audio>
<script type="module" src="./src/index.jsx"></script>
</body>
</html>
+16955 -1597
View File
File diff suppressed because it is too large. Load diff
+45 -42
View File
@@ -1,80 +1,83 @@
{
"name": "cinny",
"version": "2.2.2",
"version": "2.1.3",
"description": "Yet another matrix client",
"main": "index.js",
"engines": {
"node": ">=16.0.0"
"npm": ">=6.14.8",
"node": ">=14.15.0"
},
"scripts": {
"start": "vite",
"build": "vite build",
"lint": "yarn check:eslint && yarn check:prettier",
"check:eslint": "eslint src/*",
"check:prettier": "prettier --check .",
"fix:prettier": "prettier --write .",
"typecheck": "tsc --noEmit"
"start": "webpack serve --config ./webpack.dev.js --open",
"build": "webpack --config ./webpack.prod.js"
},
"keywords": [],
"author": "Ajay Bura",
"license": "MIT",
"dependencies": {
"@fontsource/inter": "4.5.14",
"@fontsource/inter": "4.5.12",
"@fontsource/roboto": "4.5.8",
"@khanacademy/simple-markdown": "0.8.6",
"@matrix-org/olm": "3.2.14",
"@khanacademy/simple-markdown": "0.8.3",
"@matrix-org/olm": "3.2.12",
"@tippyjs/react": "4.2.6",
"@vanilla-extract/css": "1.9.3",
"@vanilla-extract/recipes": "0.3.0",
"@vanilla-extract/vite-plugin": "3.7.1",
"blurhash": "2.0.4",
"babel-polyfill": "6.26.0",
"blurhash": "1.1.5",
"browser-encrypt-attachment": "0.3.0",
"classnames": "2.3.2",
"dateformat": "5.0.3",
"emojibase-data": "7.0.1",
"file-saver": "2.0.5",
"flux": "4.0.3",
"focus-trap-react": "10.0.2",
"folds": "1.0.4",
"formik": "2.2.9",
"html-react-parser": "3.0.4",
"immer": "9.0.16",
"jotai": "1.12.0",
"katex": "0.16.4",
"linkify-html": "4.0.2",
"linkifyjs": "4.0.2",
"matrix-js-sdk": "22.0.0",
"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.2.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.16.1",
"sanitize-html": "2.8.0",
"react-modal": "3.15.1",
"sanitize-html": "2.7.1",
"tippy.js": "6.3.7",
"twemoji": "14.0.2"
},
"devDependencies": {
"@rollup/plugin-wasm": "6.1.1",
"@types/react": "18.0.26",
"@types/react-dom": "18.0.9",
"@typescript-eslint/eslint-plugin": "5.46.1",
"@typescript-eslint/parser": "5.46.1",
"@vitejs/plugin-react": "3.0.0",
"eslint": "8.29.0",
"@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-config-prettier": "8.5.0",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-jsx-a11y": "6.6.1",
"eslint-plugin-react": "7.31.11",
"eslint-plugin-react": "7.31.1",
"eslint-plugin-react-hooks": "4.6.0",
"prettier": "2.8.1",
"sass": "1.56.2",
"typescript": "4.9.4",
"vite": "4.0.4",
"vite-plugin-static-copy": "0.13.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"
}
}
+50
View File
@@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cinny</title>
<meta name="name" content="Cinny">
<meta name="author" content="Ajay Bura">
<meta name="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="keywords" content="cinny, cinnyapp, cinnychat, matrix, matrix client, matrix.org, element">
<meta property="og:title" content="Cinny">
<meta property="og:url" content="https://cinny.in">
<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>
<audio id="notificationSound">
<source src="./sound/notification.ogg" type="audio/ogg" />
</audio>
<audio id="inviteSound">
<source src="./sound/invite.ogg" type="audio/ogg" />
</audio>
</body>
</html>
+10 -10
View File
@@ -11,49 +11,49 @@
"theme_color": "#fff",
"icons": [
{
"src": "/public/android/android-chrome-36x36.png",
"src": "android-chrome-36x36.png",
"sizes": "36x36",
"type": "image/png"
},
{
"src": "/public/android/android-chrome-48x48.png",
"src": "android-chrome-48x48.png",
"sizes": "48x48",
"type": "image/png"
},
{
"src": "/public/android/android-chrome-72x72.png",
"src": "android-chrome-72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "/public/android/android-chrome-96x96.png",
"src": "android-chrome-96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "/public/android/android-chrome-144x144.png",
"src": "android-chrome-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "/public/android/android-chrome-192x192.png",
"src": "android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/public/android/android-chrome-256x256.png",
"src": "android-chrome-256x256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "/public/android/android-chrome-384x384.png",
"src": "android-chrome-384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "/public/android/android-chrome-512x512.png",
"src": "android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
}
-1
View File
@@ -1,6 +1,5 @@
import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import './Math.scss';
import katex from 'katex';
import 'katex/dist/katex.min.css';
-3
View File
@@ -1,3 +0,0 @@
.katex-display {
margin: 0 !important;
}
-111
View File
@@ -1,111 +0,0 @@
import { style } from '@vanilla-extract/css';
import { recipe, RecipeVariants } from '@vanilla-extract/recipes';
import { color, config, DefaultReset, toRem } from 'folds';
export const Sidebar = style([
DefaultReset,
{
width: toRem(66),
backgroundColor: color.Background.Container,
borderRight: `${config.borderWidth.B300} solid ${color.Background.ContainerLine}`,
display: 'flex',
flexDirection: 'column',
color: color.Background.OnContainer,
},
]);
export const SidebarStack = style([
DefaultReset,
{
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
gap: config.space.S300,
padding: `${config.space.S300} 0`,
},
]);
const PUSH_X = 2;
export const SidebarAvatarBox = recipe({
base: [
DefaultReset,
{
display: 'flex',
alignItems: 'center',
position: 'relative',
transition: 'transform 200ms cubic-bezier(0, 0.8, 0.67, 0.97)',
selectors: {
'&:hover': {
transform: `translateX(${toRem(PUSH_X)})`,
},
'&::before': {
content: '',
display: 'none',
position: 'absolute',
left: toRem(-11.5 - PUSH_X),
width: toRem(3 + PUSH_X),
height: toRem(16),
borderRadius: `0 ${toRem(4)} ${toRem(4)} 0`,
background: 'CurrentColor',
transition: 'height 200ms linear',
},
'&:hover::before': {
display: 'block',
width: toRem(3),
},
},
},
],
variants: {
active: {
true: {
selectors: {
'&::before': {
display: 'block',
height: toRem(24),
},
'&:hover::before': {
width: toRem(3 + PUSH_X),
},
},
},
},
},
});
export type SidebarAvatarBoxVariants = RecipeVariants<typeof SidebarAvatarBox>;
export const SidebarBadgeBox = recipe({
base: [
DefaultReset,
{
position: 'absolute',
zIndex: 1,
},
],
variants: {
hasCount: {
true: {
top: toRem(-6),
right: toRem(-6),
},
false: {
top: toRem(-2),
right: toRem(-2),
},
},
},
defaultVariants: {
hasCount: false,
},
});
export type SidebarBadgeBoxVariants = RecipeVariants<typeof SidebarBadgeBox>;
export const SidebarBadgeOutline = style({
boxShadow: `0 0 0 ${config.borderWidth.B500} ${color.Background.Container}`,
});
-8
View File
@@ -1,8 +0,0 @@
import classNames from 'classnames';
import { as } from 'folds';
import React from 'react';
import * as css from './Sidebar.css';
export const Sidebar = as<'div'>(({ as: AsSidebar = 'div', className, ...props }, ref) => (
<AsSidebar className={classNames(css.Sidebar, className)} {...props} ref={ref} />
));
@@ -1,75 +0,0 @@
import classNames from 'classnames';
import { as, Avatar, Box, color, config, Text, Tooltip, TooltipProvider } from 'folds';
import React, { forwardRef, MouseEventHandler, ReactNode } from 'react';
import * as css from './Sidebar.css';
const SidebarAvatarBox = as<'div', css.SidebarAvatarBoxVariants>(
({ as: AsSidebarAvatarBox = 'div', className, active, ...props }, ref) => (
<AsSidebarAvatarBox
className={classNames(css.SidebarAvatarBox({ active }), className)}
{...props}
ref={ref}
/>
)
);
export const SidebarAvatar = forwardRef<
HTMLDivElement,
css.SidebarAvatarBoxVariants &
css.SidebarBadgeBoxVariants & {
outlined?: boolean;
avatarChildren: ReactNode;
tooltip: ReactNode | string;
notificationBadge?: (badgeClassName: string) => ReactNode;
onClick?: MouseEventHandler<HTMLButtonElement>;
onContextMenu?: MouseEventHandler<HTMLButtonElement>;
}
>(
(
{
active,
hasCount,
outlined,
avatarChildren,
tooltip,
notificationBadge,
onClick,
onContextMenu,
},
ref
) => (
<SidebarAvatarBox active={active} ref={ref}>
<TooltipProvider
delay={0}
position="right"
tooltip={
<Tooltip>
<Text size="T300">{tooltip}</Text>
</Tooltip>
}
>
{(avRef) => (
<Avatar
ref={avRef}
as="button"
onClick={onClick}
onContextMenu={onContextMenu}
style={{
border: outlined
? `${config.borderWidth.B300} solid ${color.Background.ContainerLine}`
: undefined,
cursor: 'pointer',
}}
>
{avatarChildren}
</Avatar>
)}
</TooltipProvider>
{notificationBadge && (
<Box className={css.SidebarBadgeBox({ hasCount })}>
{notificationBadge(css.SidebarBadgeOutline)}
</Box>
)}
</SidebarAvatarBox>
)
);
@@ -1,21 +0,0 @@
import React, { ReactNode } from 'react';
import { Box, Scroll } from 'folds';
type SidebarContentProps = {
scrollable: ReactNode;
sticky: ReactNode;
};
export function SidebarContent({ scrollable, sticky }: SidebarContentProps) {
return (
<>
<Box direction="Column" grow="Yes">
<Scroll variant="Background" size="0">
{scrollable}
</Scroll>
</Box>
<Box direction="Column" shrink="No">
{sticky}
</Box>
</>
);
}
@@ -1,10 +0,0 @@
import React from 'react';
import classNames from 'classnames';
import { as } from 'folds';
import * as css from './Sidebar.css';
export const SidebarStack = as<'div'>(
({ as: AsSidebarStack = 'div', className, ...props }, ref) => (
<AsSidebarStack className={classNames(css.SidebarStack, className)} {...props} ref={ref} />
)
);
@@ -1,13 +0,0 @@
import React from 'react';
import { Line, toRem } from 'folds';
export function SidebarStackSeparator() {
return (
<Line
role="separator"
style={{ width: toRem(24), margin: '0 auto' }}
variant="Background"
size="300"
/>
);
}
-5
View File
@@ -1,5 +0,0 @@
export * from './Sidebar';
export * from './SidebarAvatar';
export * from './SidebarContent';
export * from './SidebarStack';
export * from './SidebarStackSeparator';
@@ -27,7 +27,9 @@ function ImagePackUpload({ onUpload }) {
setProgress(true);
const image = await scaleDownImage(imgFile, 512, 512);
const { content_uri: url } = await mx.uploadContent(image);
const url = await mx.uploadContent(image, {
onlyContentUri: true,
});
onUpload(shortcode, url);
setProgress(false);
@@ -22,7 +22,7 @@ function ImageUpload({
const file = e.target.files.item(0);
if (file === null) return;
try {
const uPromise = initMatrix.matrixClient.uploadContent(file);
const uPromise = initMatrix.matrixClient.uploadContent(file, { onlyContentUri: false });
setUploadPromise(uPromise);
const res = await uPromise;
+13 -19
View File
@@ -8,9 +8,7 @@ import './Message.scss';
import { twemojify } from '../../../util/twemojify';
import initMatrix from '../../../client/initMatrix';
import {
getUsername, getUsernameOfRoomMember, parseReply, trimHTMLReply,
} from '../../../util/matrixUtil';
import { getUsername, getUsernameOfRoomMember, parseReply } from '../../../util/matrixUtil';
import colorMXID from '../../../util/colorMXID';
import { getEventCords } from '../../../util/common';
import { redactEvent, sendReaction } from '../../../client/action/roomTimeline';
@@ -40,7 +38,6 @@ import BinIC from '../../../../public/res/ic/outlined/bin.svg';
import { confirmDialog } from '../confirm-dialog/ConfirmDialog';
import { getBlobSafeMimeType } from '../../../util/mimetypes';
import { html, plain } from '../../../util/markdown';
function PlaceholderMessage() {
return (
@@ -251,7 +248,7 @@ const MessageBody = React.memo(({
if (!isCustomHTML) {
// If this is a plaintext message, wrap it in a <p> element (automatically applying
// white-space: pre-wrap) in order to preserve newlines
content = (<p className="message__body-plain">{content}</p>);
content = (<p>{content}</p>);
}
return (
@@ -300,12 +297,12 @@ function MessageEdit({ body, onSave, onCancel }) {
if (e.key === 'Enter' && e.shiftKey === false) {
e.preventDefault();
onSave(editInputRef.current.value, body);
onSave(editInputRef.current.value);
}
};
return (
<form className="message__edit" onSubmit={(e) => { e.preventDefault(); onSave(editInputRef.current.value, body); }}>
<form className="message__edit" onSubmit={(e) => { e.preventDefault(); onSave(editInputRef.current.value); }}>
<Input
forwardRef={editInputRef}
onKeyDown={handleKeyDown}
@@ -732,37 +729,36 @@ function Message({
let { body } = content;
const username = mEvent.sender ? getUsernameOfRoomMember(mEvent.sender) : getUsername(senderId);
const avatarSrc = mEvent.sender?.getAvatarUrl(initMatrix.matrixClient.baseUrl, 36, 36, 'crop') ?? null;
let isCustomHTML = content.format === 'org.matrix.custom.html';
let customHTML = isCustomHTML ? content.formatted_body : null;
const edit = useCallback(() => {
setEdit(eventId);
}, []);
const reply = useCallback(() => {
replyTo(senderId, mEvent.getId(), body, customHTML);
}, [body, customHTML]);
replyTo(senderId, mEvent.getId(), body);
}, [body]);
if (body === undefined) return null;
if (msgType === 'm.emote') className.push('message--type-emote');
let isCustomHTML = content.format === 'org.matrix.custom.html';
const isEdited = roomTimeline ? editedTimeline.has(eventId) : false;
const haveReactions = roomTimeline
? reactionTimeline.has(eventId) || !!mEvent.getServerAggregatedRelation('m.annotation')
: false;
const isReply = !!mEvent.replyEventId;
let customHTML = isCustomHTML ? content.formatted_body : null;
if (isEdited) {
const editedList = editedTimeline.get(eventId);
const editedMEvent = editedList[editedList.length - 1];
[body, isCustomHTML, customHTML] = getEditedBody(editedMEvent);
if (typeof body !== 'string') return null;
}
if (isReply) {
body = parseReply(body)?.body ?? body;
customHTML = trimHTMLReply(customHTML);
}
if (typeof body !== 'string') body = '';
return (
<div className={className.join(' ')}>
{
@@ -803,11 +799,9 @@ function Message({
)}
{isEdit && (
<MessageEdit
body={(customHTML
? html(customHTML, { kind: 'edit', onlyPlain: true }).plain
: plain(body, { kind: 'edit', onlyPlain: true }).plain)}
onSave={(newBody, oldBody) => {
if (newBody !== oldBody) {
body={body}
onSave={(newBody) => {
if (newBody !== body) {
initMatrix.roomsInput.sendEditedMessage(roomId, mEvent, newBody);
}
cancelEdit();
+3 -3
View File
@@ -163,7 +163,7 @@
.message__body {
word-break: break-word;
& > .text > .message__body-plain {
& > .text > * {
white-space: pre-wrap;
}
@@ -174,8 +174,8 @@
white-space: initial !important;
}
& > .text > p + p {
margin-top: var(--sp-normal);
& p:not(:last-child) {
margin-bottom: var(--sp-normal);
}
& span[data-mx-pill] {
@@ -57,7 +57,7 @@ export function HomeSpaceOptions({ spaceId, afterOptionSelect }) {
iconSrc={HashGlobeIC}
onClick={() => { afterOptionSelect(); openPublicRooms(); }}
>
Explore public rooms
Join public room
</MenuItem>
)}
{ !spaceId && (
+1 -1
View File
@@ -25,7 +25,7 @@ function Home({ spaceId }) {
let directIds = [];
if (spaceId) {
const spaceChildIds = roomList.getSpaceChildren(spaceId) ?? [];
const spaceChildIds = roomList.getSpaceChildren(spaceId);
spaceIds = spaceChildIds.filter((roomId) => spaces.has(roomId));
roomIds = spaceChildIds.filter((roomId) => rooms.has(roomId));
directIds = spaceChildIds.filter((roomId) => directs.has(roomId));
@@ -1,14 +1,12 @@
import React from 'react';
import './Navigation.scss';
import { Sidebar1 } from './Sidebar1';
import SideBar from './SideBar';
import Drawer from './Drawer';
function Navigation() {
return (
<div className="navigation">
<Sidebar1 />
<SideBar />
<Drawer />
</div>
+9 -7
View File
@@ -7,7 +7,10 @@
width: var(--navigation-sidebar-width);
height: 100%;
background-color: var(--bg-surface-extra-low);
@include dir.side(border, none, 1px solid var(--bg-surface-border));
@include dir.side(border,
none,
1px solid var(--bg-surface-border),
);
&__scrollable,
&__sticky {
@@ -21,7 +24,7 @@
.scrollable-content {
&::after {
content: '';
content: "";
display: block;
width: 100%;
height: 8px;
@@ -30,8 +33,7 @@
background-image: linear-gradient(
to top,
var(--bg-surface-extra-low),
var(--bg-surface-extra-low-transparent)
);
var(--bg-surface-extra-low-transparent));
position: sticky;
bottom: -1px;
left: 0;
@@ -42,7 +44,7 @@
.space-container,
.sticky-container {
@extend .cp-fx__column--c-c;
padding: var(--sp-ultra-tight) 0;
& > .sidebar-avatar,
@@ -61,7 +63,7 @@
box-shadow: var(--bs-danger-border);
animation-name: pushRight;
animation-duration: 400ms;
animation-iteration-count: 30;
animation-iteration-count: infinite;
animation-direction: alternate;
}
@@ -72,4 +74,4 @@
to {
transform: translateX(0) scale(1);
}
}
}
-125
View File
@@ -1,125 +0,0 @@
import React from 'react';
import { Icon, Icons, Badge, AvatarFallback, Text } from 'folds';
import { useAtom } from 'jotai';
import {
Sidebar,
SidebarContent,
SidebarStackSeparator,
SidebarStack,
SidebarAvatar,
} from '../../components/sidebar';
import { selectedTabAtom, SidebarTab } from '../../state/selectedTab';
export function Sidebar1() {
const [selectedTab, setSelectedTab] = useAtom(selectedTabAtom);
return (
<Sidebar>
<SidebarContent
scrollable={
<>
<SidebarStack>
<SidebarAvatar
active={selectedTab === SidebarTab.Home}
outlined
tooltip="Home"
avatarChildren={<Icon src={Icons.Home} filled />}
onClick={() => setSelectedTab(SidebarTab.Home)}
/>
<SidebarAvatar
active={selectedTab === SidebarTab.People}
outlined
tooltip="People"
avatarChildren={<Icon src={Icons.User} />}
onClick={() => setSelectedTab(SidebarTab.People)}
/>
</SidebarStack>
<SidebarStackSeparator />
<SidebarStack>
<SidebarAvatar
tooltip="Space A"
notificationBadge={(badgeClassName) => (
<Badge
className={badgeClassName}
size="200"
variant="Secondary"
fill="Solid"
radii="Pill"
/>
)}
avatarChildren={
<AvatarFallback
style={{
backgroundColor: 'red',
color: 'white',
}}
>
<Text size="T500">B</Text>
</AvatarFallback>
}
/>
<SidebarAvatar
tooltip="Space B"
hasCount
notificationBadge={(badgeClassName) => (
<Badge className={badgeClassName} radii="Pill" fill="Solid" variant="Secondary">
<Text size="L400">64</Text>
</Badge>
)}
avatarChildren={
<AvatarFallback
style={{
backgroundColor: 'green',
color: 'white',
}}
>
<Text size="T500">C</Text>
</AvatarFallback>
}
/>
</SidebarStack>
<SidebarStackSeparator />
<SidebarStack>
<SidebarAvatar
outlined
tooltip="Explore Community"
avatarChildren={<Icon src={Icons.Explore} />}
/>
<SidebarAvatar
outlined
tooltip="Create Space"
avatarChildren={<Icon src={Icons.Plus} />}
/>
</SidebarStack>
</>
}
sticky={
<>
<SidebarStackSeparator />
<SidebarStack>
<SidebarAvatar
outlined
tooltip="Search"
avatarChildren={<Icon src={Icons.Search} />}
/>
<SidebarAvatar
tooltip="User Settings"
avatarChildren={
<AvatarFallback
style={{
backgroundColor: 'blue',
color: 'white',
}}
>
<Text size="T500">A</Text>
</AvatarFallback>
}
/>
</SidebarStack>
</>
}
/>
</Sidebar>
);
}
@@ -20,6 +20,7 @@ function ProfileEditor({ userId }) {
const [isEditing, setIsEditing] = useState(false);
const mx = initMatrix.matrixClient;
const user = mx.getUser(mx.getUserId());
const fallbackUsername = userId.match(/^@?(\S+):(\S+)$/)[1];
const displayNameRef = useRef(null);
const [avatarSrc, setAvatarSrc] = useState(user.avatarUrl ? mx.mxcUrlToHttp(user.avatarUrl, 80, 80, 'crop') : null);
@@ -95,7 +96,7 @@ function ProfileEditor({ userId }) {
const renderInfo = () => (
<div className="profile-editor__info" style={{ marginBottom: avatarSrc ? '24px' : '0' }}>
<div>
<Text variant="h2" primary weight="medium">{twemojify(username) ?? userId}</Text>
<Text variant="h2" primary weight="medium">{twemojify(username) ?? fallbackUsername}</Text>
<IconButton
src={PencilIC}
size="extra-small"
@@ -110,7 +111,7 @@ function ProfileEditor({ userId }) {
return (
<div className="profile-editor">
<ImageUpload
text={username ?? userId}
text={username ?? fallbackUsername}
bgColor={colorMXID(userId)}
imageSrc={avatarSrc}
onUpload={handleAvatarUpload}
+12 -12
View File
@@ -30,6 +30,7 @@ import StickerIC from '../../../../public/res/ic/outlined/sticker.svg';
import ShieldIC from '../../../../public/res/ic/outlined/shield.svg';
import VLCIC from '../../../../public/res/ic/outlined/vlc.svg';
import VolumeFullIC from '../../../../public/res/ic/outlined/volume-full.svg';
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';
@@ -43,6 +44,7 @@ function RoomViewInput({
roomId, roomTimeline, viewEvent,
}) {
const [attachment, setAttachment] = useState(null);
const [isMarkdown, setIsMarkdown] = useState(settings.isMarkdown);
const [replyTo, setReplyTo] = useState(null);
const textAreaRef = useRef(null);
@@ -61,9 +63,11 @@ function RoomViewInput({
}
useEffect(() => {
settings.on(cons.events.settings.MARKDOWN_TOGGLED, setIsMarkdown);
roomsInput.on(cons.events.roomsInput.ATTACHMENT_SET, setAttachment);
viewEvent.on('focus_msg_input', requestFocusInput);
return () => {
settings.removeListener(cons.events.settings.MARKDOWN_TOGGLED, setIsMarkdown);
roomsInput.removeListener(cons.events.roomsInput.ATTACHMENT_SET, setAttachment);
viewEvent.removeListener('focus_msg_input', requestFocusInput);
};
@@ -143,11 +147,9 @@ function RoomViewInput({
textAreaRef.current.focus();
}
function setUpReply(userId, eventId, body, formattedBody) {
function setUpReply(userId, eventId, body) {
setReplyTo({ userId, eventId, body });
roomsInput.setReplyTo(roomId, {
userId, eventId, body, formattedBody,
});
roomsInput.setReplyTo(roomId, { userId, eventId, body });
focusInput();
}
@@ -183,10 +185,7 @@ function RoomViewInput({
};
}, [roomId]);
const sendBody = async (body, options) => {
const opt = options ?? {};
if (!opt.msgType) opt.msgType = 'm.text';
if (typeof opt.autoMarkdown !== 'boolean') opt.autoMarkdown = true;
const sendBody = async (body, msgType = 'm.text') => {
if (roomsInput.isSending(roomId)) return;
sendIsTyping(false);
@@ -196,7 +195,7 @@ function RoomViewInput({
}
textAreaRef.current.disabled = true;
textAreaRef.current.style.cursor = 'not-allowed';
await roomsInput.sendInput(roomId, opt);
await roomsInput.sendInput(roomId, msgType);
textAreaRef.current.disabled = false;
textAreaRef.current.style.cursor = 'unset';
focusInput();
@@ -214,8 +213,8 @@ function RoomViewInput({
confirmDialog('Invalid Command', `"${cmdName}" is not a valid command.`, 'Alright');
return;
}
if (['me', 'shrug', 'plain'].includes(cmdName)) {
commands[cmdName].exe(roomId, cmdData, sendBody);
if (['me', 'shrug'].includes(cmdName)) {
commands[cmdName].exe(roomId, cmdData, (message, msgType) => sendBody(message, msgType));
return;
}
commands[cmdName].exe(roomId, cmdData);
@@ -231,7 +230,7 @@ function RoomViewInput({
return;
}
if (msgBody === '' && attachment === null) return;
sendBody(msgBody);
sendBody(msgBody, 'm.text');
};
const handleSendSticker = async (data) => {
@@ -380,6 +379,7 @@ function RoomViewInput({
/>
</Text>
</ScrollView>
{isMarkdown && <RawIcon size="extra-small" src={MarkdownIC} />}
</div>
<div ref={rightOptionsRef} className="room-input__option-container">
<IconButton
+6 -15
View File
@@ -38,7 +38,7 @@ const commands = {
exe: (roomId, data, onSuccess) => {
const body = data.trim();
if (body === '') return;
onSuccess(body, { msgType: 'm.emote' });
onSuccess(body, 'm.emote');
},
},
shrug: {
@@ -46,18 +46,9 @@ const commands = {
description: 'Send ¯\\_(ツ)_/¯ as message',
exe: (roomId, data, onSuccess) => onSuccess(
`¯\\_(ツ)_/¯${data.trim() !== '' ? ` ${data}` : ''}`,
{ msgType: 'm.text' },
'm.text',
),
},
plain: {
name: 'plain',
description: 'Send plain text message',
exe: (roomId, data, onSuccess) => {
const body = data.trim();
if (body === '') return;
onSuccess(body, { msgType: 'm.text', autoMarkdown: false });
},
},
help: {
name: 'help',
description: 'View all commands',
@@ -66,7 +57,7 @@ const commands = {
},
startdm: {
name: 'startdm',
description: 'Start direct message with user. Example: /startdm userId1',
description: 'Start DM with user. Example: /startdm userId1 userId2',
exe: async (roomId, data) => {
const mx = initMatrix.matrixClient;
const rawIds = data.split(' ');
@@ -87,7 +78,7 @@ const commands = {
},
join: {
name: 'join',
description: 'Join room with address. Example: /join address1 address2',
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));
@@ -168,7 +159,7 @@ const commands = {
},
myroomnick: {
name: 'myroomnick',
description: 'Change nick in current room.',
description: 'Change my room nick',
exe: (roomId, data) => {
const nick = data.trim();
if (nick === '') return;
@@ -177,7 +168,7 @@ const commands = {
},
myroomavatar: {
name: 'myroomavatar',
description: 'Change profile picture in current room. Example /myroomavatar mxc://xyzabc',
description: 'Change my room avatar. Example /myroomavatar mxc://xyzabc',
exe: (roomId, data) => {
if (data.match(MXC_REG)) {
roomActions.setMyRoomAvatar(roomId, data);
+2 -2
View File
@@ -9,6 +9,7 @@ import {
toggleSystemTheme, toggleMarkdown, toggleMembershipEvents, toggleNickAvatarEvents,
toggleNotifications, toggleNotificationSounds,
} from '../../../client/action/settings';
import logout from '../../../client/action/logout';
import { usePermission } from '../../hooks/usePermission';
import Text from '../../atoms/text/Text';
@@ -238,7 +239,6 @@ function AboutSection() {
<div className="settings-about__btns">
<Button onClick={() => window.open('https://github.com/ajbura/cinny')}>Source code</Button>
<Button onClick={() => window.open('https://cinny.in/#sponsor')}>Support</Button>
<Button onClick={() => initMatrix.clearCacheAndReload()} variant="danger">Clear cache & reload</Button>
</div>
</div>
</div>
@@ -327,7 +327,7 @@ function Settings() {
const handleTabChange = (tabItem) => setSelectedTab(tabItem);
const handleLogout = async () => {
if (await confirmDialog('Logout', 'Are you sure that you want to logout your session?', 'Logout', 'danger')) {
initMatrix.logout();
logout();
}
};
@@ -5,8 +5,6 @@
& pre {
padding: var(--sp-extra-tight);
white-space: pre-wrap;
word-break: break-all;
}
&__card {
+2 -7
View File
@@ -1,5 +1,4 @@
import React, { StrictMode } from 'react';
import { Provider } from 'jotai';
import React from 'react';
import { isAuthenticated } from '../../client/state/auth';
@@ -7,11 +6,7 @@ import Auth from '../templates/auth/Auth';
import Client from '../templates/client/Client';
function App() {
return (
<StrictMode>
<Provider>{isAuthenticated() ? <Client /> : <Auth />}</Provider>
</StrictMode>
);
return isAuthenticated() ? <Client /> : <Auth />;
}
export default App;
-63
View File
@@ -1,63 +0,0 @@
import { useAtomValue, WritableAtom } from 'jotai';
import { selectAtom } from 'jotai/utils';
import { MatrixClient } from 'matrix-js-sdk';
import { useCallback } from 'react';
import { isDirectInvite, isRoom, isSpace, isUnsupportedRoom } from '../../utils/room';
import { compareRoomsEqual, RoomsAction } from '../utils';
import { MDirectAction } from '../mDirectList';
export const useSpaceInvites = (
mx: MatrixClient,
allInvitesAtom: WritableAtom<string[], RoomsAction>
) => {
const selector = useCallback(
(rooms: string[]) => rooms.filter((roomId) => isSpace(mx.getRoom(roomId))),
[mx]
);
return useAtomValue(selectAtom(allInvitesAtom, selector, compareRoomsEqual));
};
export const useRoomInvites = (
mx: MatrixClient,
allInvitesAtom: WritableAtom<string[], RoomsAction>,
mDirectAtom: WritableAtom<Set<string>, MDirectAction>
) => {
const mDirects = useAtomValue(mDirectAtom);
const selector = useCallback(
(rooms: string[]) =>
rooms.filter(
(roomId) =>
isRoom(mx.getRoom(roomId)) &&
!(mDirects.has(roomId) || isDirectInvite(mx.getRoom(roomId), mx.getUserId()))
),
[mx, mDirects]
);
return useAtomValue(selectAtom(allInvitesAtom, selector, compareRoomsEqual));
};
export const useDirectInvites = (
mx: MatrixClient,
allInvitesAtom: WritableAtom<string[], RoomsAction>,
mDirectAtom: WritableAtom<Set<string>, MDirectAction>
) => {
const mDirects = useAtomValue(mDirectAtom);
const selector = useCallback(
(rooms: string[]) =>
rooms.filter(
(roomId) => mDirects.has(roomId) || isDirectInvite(mx.getRoom(roomId), mx.getUserId())
),
[mx, mDirects]
);
return useAtomValue(selectAtom(allInvitesAtom, selector, compareRoomsEqual));
};
export const useUnsupportedInvites = (
mx: MatrixClient,
allInvitesAtom: WritableAtom<string[], RoomsAction>
) => {
const selector = useCallback(
(rooms: string[]) => rooms.filter((roomId) => isUnsupportedRoom(mx.getRoom(roomId))),
[mx]
);
return useAtomValue(selectAtom(allInvitesAtom, selector, compareRoomsEqual));
};
-54
View File
@@ -1,54 +0,0 @@
import { useAtomValue, WritableAtom } from 'jotai';
import { selectAtom } from 'jotai/utils';
import { MatrixClient } from 'matrix-js-sdk';
import { useCallback } from 'react';
import { isRoom, isSpace, isUnsupportedRoom } from '../../utils/room';
import { compareRoomsEqual, RoomsAction } from '../utils';
import { MDirectAction } from '../mDirectList';
export const useSpaces = (mx: MatrixClient, allRoomsAtom: WritableAtom<string[], RoomsAction>) => {
const selector = useCallback(
(rooms: string[]) => rooms.filter((roomId) => isSpace(mx.getRoom(roomId))),
[mx]
);
return useAtomValue(selectAtom(allRoomsAtom, selector, compareRoomsEqual));
};
export const useRooms = (
mx: MatrixClient,
allRoomsAtom: WritableAtom<string[], RoomsAction>,
mDirectAtom: WritableAtom<Set<string>, MDirectAction>
) => {
const mDirects = useAtomValue(mDirectAtom);
const selector = useCallback(
(rooms: string[]) =>
rooms.filter((roomId) => isRoom(mx.getRoom(roomId)) && !mDirects.has(roomId)),
[mx, mDirects]
);
return useAtomValue(selectAtom(allRoomsAtom, selector, compareRoomsEqual));
};
export const useDirects = (
mx: MatrixClient,
allRoomsAtom: WritableAtom<string[], RoomsAction>,
mDirectAtom: WritableAtom<Set<string>, MDirectAction>
) => {
const mDirects = useAtomValue(mDirectAtom);
const selector = useCallback(
(rooms: string[]) =>
rooms.filter((roomId) => isRoom(mx.getRoom(roomId)) && mDirects.has(roomId)),
[mx, mDirects]
);
return useAtomValue(selectAtom(allRoomsAtom, selector, compareRoomsEqual));
};
export const useUnsupportedRooms = (
mx: MatrixClient,
allRoomsAtom: WritableAtom<string[], RoomsAction>
) => {
const selector = useCallback(
(rooms: string[]) => rooms.filter((roomId) => isUnsupportedRoom(mx.getRoom(roomId))),
[mx]
);
return useAtomValue(selectAtom(allRoomsAtom, selector, compareRoomsEqual));
};
-34
View File
@@ -1,34 +0,0 @@
import { atom, useAtomValue, useSetAtom, WritableAtom } from 'jotai';
import { SetAtom } from 'jotai/core/atom';
import { selectAtom } from 'jotai/utils';
import { useMemo } from 'react';
import { Settings } from '../settings';
export const useSetSetting = <K extends keyof Settings>(
settingsAtom: WritableAtom<Settings, Settings>,
key: K
) => {
const setterAtom = useMemo(
() =>
atom<null, Settings[K]>(null, (get, set, value) => {
const s = { ...get(settingsAtom) };
s[key] = value;
set(settingsAtom, s);
}),
[settingsAtom, key]
);
return useSetAtom(setterAtom);
};
export const useSetting = <K extends keyof Settings>(
settingsAtom: WritableAtom<Settings, Settings>,
key: K
): [Settings[K], SetAtom<Settings[K], void>] => {
const selector = useMemo(() => (s: Settings) => s[key], [key]);
const setting = useAtomValue(selectAtom(settingsAtom, selector));
const setter = useSetSetting(settingsAtom, key);
return [setting, setter];
};
-16
View File
@@ -1,16 +0,0 @@
import { MatrixClient } from 'matrix-js-sdk';
import { allInvitesAtom, useBindAllInvitesAtom } from '../inviteList';
import { allRoomsAtom, useBindAllRoomsAtom } from '../roomList';
import { mDirectAtom, useBindMDirectAtom } from '../mDirectList';
import { muteChangesAtom, mutedRoomsAtom, useBindMutedRoomsAtom } from '../mutedRoomList';
import { roomToUnreadAtom, useBindRoomToUnreadAtom } from '../roomToUnread';
import { roomToParentsAtom, useBindRoomToParentsAtom } from '../roomToParents';
export const useBindAtoms = (mx: MatrixClient) => {
useBindMDirectAtom(mx, mDirectAtom);
useBindAllInvitesAtom(mx, allInvitesAtom);
useBindAllRoomsAtom(mx, allRoomsAtom);
useBindRoomToParentsAtom(mx, roomToParentsAtom);
useBindMutedRoomsAtom(mx, mutedRoomsAtom);
useBindRoomToUnreadAtom(mx, roomToUnreadAtom, muteChangesAtom);
};
-32
View File
@@ -1,32 +0,0 @@
import { atom, WritableAtom } from 'jotai';
import { MatrixClient } from 'matrix-js-sdk';
import { useMemo } from 'react';
import { Membership } from '../../types/matrix/room';
import { RoomsAction, useBindRoomsWithMembershipsAtom } from './utils';
const baseRoomsAtom = atom<string[]>([]);
export const allInvitesAtom = atom<string[], RoomsAction>(
(get) => get(baseRoomsAtom),
(get, set, action) => {
if (action.type === 'INITIALIZE') {
set(baseRoomsAtom, action.rooms);
return;
}
set(baseRoomsAtom, (ids) => {
const newIds = ids.filter((id) => id !== action.roomId);
if (action.type === 'PUT') newIds.push(action.roomId);
return newIds;
});
}
);
export const useBindAllInvitesAtom = (
mx: MatrixClient,
allRooms: WritableAtom<string[], RoomsAction>
) => {
useBindRoomsWithMembershipsAtom(
mx,
allRooms,
useMemo(() => [Membership.Invite], [])
);
};
-47
View File
@@ -1,47 +0,0 @@
import { atom, useSetAtom, WritableAtom } from 'jotai';
import { ClientEvent, MatrixClient, MatrixEvent } from 'matrix-js-sdk';
import { useEffect } from 'react';
import { AccountDataEvent } from '../../types/matrix/accountData';
import { getAccountData, getMDirects } from '../utils/room';
export type MDirectAction = {
type: 'INITIALIZE' | 'UPDATE';
rooms: Set<string>;
};
const baseMDirectAtom = atom(new Set<string>());
export const mDirectAtom = atom<Set<string>, MDirectAction>(
(get) => get(baseMDirectAtom),
(get, set, action) => {
set(baseMDirectAtom, action.rooms);
}
);
export const useBindMDirectAtom = (
mx: MatrixClient,
mDirect: WritableAtom<Set<string>, MDirectAction>
) => {
const setMDirect = useSetAtom(mDirect);
useEffect(() => {
const mDirectEvent = getAccountData(mx, AccountDataEvent.Direct);
if (mDirectEvent) {
setMDirect({
type: 'INITIALIZE',
rooms: getMDirects(mDirectEvent),
});
}
const handleAccountData = (event: MatrixEvent) => {
setMDirect({
type: 'UPDATE',
rooms: getMDirects(event),
});
};
mx.on(ClientEvent.AccountData, handleAccountData);
return () => {
mx.removeListener(ClientEvent.AccountData, handleAccountData);
};
}, [mx, setMDirect]);
};
-101
View File
@@ -1,101 +0,0 @@
import { atom, WritableAtom, useSetAtom } from 'jotai';
import { ClientEvent, IPushRule, IPushRules, MatrixClient, MatrixEvent } from 'matrix-js-sdk';
import { useEffect } from 'react';
import { MuteChanges } from '../../types/matrix/room';
import { findMutedRule, isMutedRule } from '../utils/room';
export type MutedRoomsUpdate =
| {
type: 'INITIALIZE';
addRooms: string[];
}
| {
type: 'UPDATE';
addRooms: string[];
removeRooms: string[];
};
export const muteChangesAtom = atom<MuteChanges>({
added: [],
removed: [],
});
const baseMutedRoomsAtom = atom(new Set<string>());
export const mutedRoomsAtom = atom<Set<string>, MutedRoomsUpdate>(
(get) => get(baseMutedRoomsAtom),
(get, set, action) => {
const mutedRooms = new Set([...get(mutedRoomsAtom)]);
if (action.type === 'INITIALIZE') {
set(baseMutedRoomsAtom, new Set([...action.addRooms]));
set(muteChangesAtom, {
added: [...action.addRooms],
removed: [],
});
return;
}
if (action.type === 'UPDATE') {
action.removeRooms.forEach((roomId) => mutedRooms.delete(roomId));
action.addRooms.forEach((roomId) => mutedRooms.add(roomId));
set(baseMutedRoomsAtom, mutedRooms);
set(muteChangesAtom, {
added: [...action.addRooms],
removed: [...action.removeRooms],
});
}
}
);
export const useBindMutedRoomsAtom = (
mx: MatrixClient,
mutedAtom: WritableAtom<Set<string>, MutedRoomsUpdate>
) => {
const setMuted = useSetAtom(mutedAtom);
useEffect(() => {
const overrideRules = mx.getAccountData('m.push_rules')?.getContent<IPushRules>()
?.global?.override;
if (overrideRules) {
const mutedRooms = overrideRules.reduce<string[]>((rooms, rule) => {
if (isMutedRule(rule)) rooms.push(rule.rule_id);
return rooms;
}, []);
setMuted({
type: 'INITIALIZE',
addRooms: mutedRooms,
});
}
}, [mx, setMuted]);
useEffect(() => {
const handlePushRules = (mEvent: MatrixEvent, oldMEvent?: MatrixEvent) => {
if (mEvent.getType() === 'm.push_rules') {
const override = mEvent?.getContent()?.global?.override as IPushRule[] | undefined;
const oldOverride = oldMEvent?.getContent()?.global?.override as IPushRule[] | undefined;
if (!override || !oldOverride) return;
const isMuteToggled = (rule: IPushRule, otherOverride: IPushRule[]) => {
const roomId = rule.rule_id;
const isMuted = isMutedRule(rule);
if (!isMuted) return false;
const isOtherMuted = findMutedRule(otherOverride, roomId);
if (isOtherMuted) return false;
return true;
};
const mutedRules = override.filter((rule) => isMuteToggled(rule, oldOverride));
const unMutedRules = oldOverride.filter((rule) => isMuteToggled(rule, override));
setMuted({
type: 'UPDATE',
addRooms: mutedRules.map((rule) => rule.rule_id),
removeRooms: unMutedRules.map((rule) => rule.rule_id),
});
}
};
mx.on(ClientEvent.AccountData, handlePushRules);
return () => {
mx.removeListener(ClientEvent.AccountData, handlePushRules);
};
}, [mx, setMuted]);
};
-31
View File
@@ -1,31 +0,0 @@
import { atom, WritableAtom } from 'jotai';
import { MatrixClient } from 'matrix-js-sdk';
import { useMemo } from 'react';
import { Membership } from '../../types/matrix/room';
import { RoomsAction, useBindRoomsWithMembershipsAtom } from './utils';
const baseRoomsAtom = atom<string[]>([]);
export const allRoomsAtom = atom<string[], RoomsAction>(
(get) => get(baseRoomsAtom),
(get, set, action) => {
if (action.type === 'INITIALIZE') {
set(baseRoomsAtom, action.rooms);
return;
}
set(baseRoomsAtom, (ids) => {
const newIds = ids.filter((id) => id !== action.roomId);
if (action.type === 'PUT') newIds.push(action.roomId);
return newIds;
});
}
);
export const useBindAllRoomsAtom = (
mx: MatrixClient,
allRooms: WritableAtom<string[], RoomsAction>
) => {
useBindRoomsWithMembershipsAtom(
mx,
allRooms,
useMemo(() => [Membership.Join], [])
);
};
-120
View File
@@ -1,120 +0,0 @@
import produce from 'immer';
import { atom, useSetAtom, WritableAtom } from 'jotai';
import {
ClientEvent,
MatrixClient,
MatrixEvent,
Room,
RoomEvent,
RoomStateEvent,
} from 'matrix-js-sdk';
import { useEffect } from 'react';
import { Membership, RoomToParents, StateEvent } from '../../types/matrix/room';
import {
getRoomToParents,
getSpaceChildren,
isSpace,
isValidChild,
mapParentWithChildren,
} from '../utils/room';
export type RoomToParentsAction =
| {
type: 'INITIALIZE';
roomToParents: RoomToParents;
}
| {
type: 'PUT';
parent: string;
children: string[];
}
| {
type: 'DELETE';
roomId: string;
};
const baseRoomToParents = atom<RoomToParents>(new Map());
export const roomToParentsAtom = atom<RoomToParents, RoomToParentsAction>(
(get) => get(baseRoomToParents),
(get, set, action) => {
if (action.type === 'INITIALIZE') {
set(baseRoomToParents, action.roomToParents);
return;
}
if (action.type === 'PUT') {
set(
baseRoomToParents,
produce(get(baseRoomToParents), (draftRoomToParents) => {
mapParentWithChildren(draftRoomToParents, action.parent, action.children);
})
);
return;
}
if (action.type === 'DELETE') {
set(
baseRoomToParents,
produce(get(baseRoomToParents), (draftRoomToParents) => {
const noParentRooms: string[] = [];
draftRoomToParents.delete(action.roomId);
draftRoomToParents.forEach((parents, child) => {
parents.delete(action.roomId);
if (parents.size === 0) noParentRooms.push(child);
});
noParentRooms.forEach((room) => draftRoomToParents.delete(room));
})
);
}
}
);
export const useBindRoomToParentsAtom = (
mx: MatrixClient,
roomToParents: WritableAtom<RoomToParents, RoomToParentsAction>
) => {
const setRoomToParents = useSetAtom(roomToParents);
useEffect(() => {
setRoomToParents({ type: 'INITIALIZE', roomToParents: getRoomToParents(mx) });
const handleAddRoom = (room: Room) => {
if (isSpace(room) && room.getMyMembership() !== Membership.Invite) {
setRoomToParents({ type: 'PUT', parent: room.roomId, children: getSpaceChildren(room) });
}
};
const handleMembershipChange = (room: Room, membership: string) => {
if (isSpace(room) && membership === Membership.Join) {
setRoomToParents({ type: 'PUT', parent: room.roomId, children: getSpaceChildren(room) });
}
};
const handleStateChange = (mEvent: MatrixEvent) => {
if (mEvent.getType() === StateEvent.SpaceChild) {
const childId = mEvent.getStateKey();
const roomId = mEvent.getRoomId();
if (childId && roomId) {
if (isValidChild(mEvent)) {
setRoomToParents({ type: 'PUT', parent: roomId, children: [childId] });
} else {
setRoomToParents({ type: 'DELETE', roomId: childId });
}
}
}
};
const handleDeleteRoom = (roomId: string) => {
setRoomToParents({ type: 'DELETE', roomId });
};
mx.on(ClientEvent.Room, handleAddRoom);
mx.on(RoomEvent.MyMembership, handleMembershipChange);
mx.on(RoomStateEvent.Events, handleStateChange);
mx.on(ClientEvent.DeleteRoom, handleDeleteRoom);
return () => {
mx.removeListener(ClientEvent.Room, handleAddRoom);
mx.removeListener(RoomEvent.MyMembership, handleMembershipChange);
mx.removeListener(RoomStateEvent.Events, handleStateChange);
mx.removeListener(ClientEvent.DeleteRoom, handleDeleteRoom);
};
}, [mx, setRoomToParents]);
};
-219
View File
@@ -1,219 +0,0 @@
import produce from 'immer';
import { atom, useSetAtom, PrimitiveAtom, WritableAtom, useAtomValue } from 'jotai';
import { IRoomTimelineData, MatrixClient, MatrixEvent, Room, RoomEvent } from 'matrix-js-sdk';
import { ReceiptContent, ReceiptType } from 'matrix-js-sdk/lib/@types/read_receipts';
import { useEffect } from 'react';
import {
MuteChanges,
Membership,
NotificationType,
RoomToUnread,
UnreadInfo,
} from '../../types/matrix/room';
import {
getAllParents,
getNotificationType,
getUnreadInfo,
getUnreadInfos,
isNotificationEvent,
roomHaveUnread,
} from '../utils/room';
import { roomToParentsAtom } from './roomToParents';
export type RoomToUnreadAction =
| {
type: 'RESET';
unreadInfos: UnreadInfo[];
}
| {
type: 'PUT';
unreadInfo: UnreadInfo;
}
| {
type: 'DELETE';
roomId: string;
};
const putUnreadInfo = (
roomToUnread: RoomToUnread,
allParents: Set<string>,
unreadInfo: UnreadInfo
) => {
const oldUnread = roomToUnread.get(unreadInfo.roomId) ?? { highlight: 0, total: 0, from: null };
roomToUnread.set(unreadInfo.roomId, {
highlight: unreadInfo.highlight,
total: unreadInfo.total,
from: null,
});
const newH = unreadInfo.highlight - oldUnread.highlight;
const newT = unreadInfo.total - oldUnread.total;
allParents.forEach((parentId) => {
const oldParentUnread = roomToUnread.get(parentId) ?? { highlight: 0, total: 0, from: null };
roomToUnread.set(parentId, {
highlight: (oldParentUnread.highlight += newH),
total: (oldParentUnread.total += newT),
from: new Set([...(oldParentUnread.from ?? []), unreadInfo.roomId]),
});
});
};
const deleteUnreadInfo = (roomToUnread: RoomToUnread, allParents: Set<string>, roomId: string) => {
const oldUnread = roomToUnread.get(roomId);
if (!oldUnread) return;
roomToUnread.delete(roomId);
allParents.forEach((parentId) => {
const oldParentUnread = roomToUnread.get(parentId);
if (!oldParentUnread) return;
const newFrom = new Set([...(oldParentUnread.from ?? roomId)]);
newFrom.delete(roomId);
if (newFrom.size === 0) {
roomToUnread.delete(parentId);
return;
}
roomToUnread.set(parentId, {
highlight: oldParentUnread.highlight - oldUnread.highlight,
total: oldParentUnread.total - oldUnread.total,
from: newFrom,
});
});
};
const baseRoomToUnread = atom<RoomToUnread>(new Map());
export const roomToUnreadAtom = atom<RoomToUnread, RoomToUnreadAction>(
(get) => get(baseRoomToUnread),
(get, set, action) => {
if (action.type === 'RESET') {
const draftRoomToUnread: RoomToUnread = new Map();
action.unreadInfos.forEach((unreadInfo) => {
putUnreadInfo(
draftRoomToUnread,
getAllParents(get(roomToParentsAtom), unreadInfo.roomId),
unreadInfo
);
});
set(baseRoomToUnread, draftRoomToUnread);
return;
}
if (action.type === 'PUT') {
set(
baseRoomToUnread,
produce(get(baseRoomToUnread), (draftRoomToUnread) =>
putUnreadInfo(
draftRoomToUnread,
getAllParents(get(roomToParentsAtom), action.unreadInfo.roomId),
action.unreadInfo
)
)
);
return;
}
if (action.type === 'DELETE' && get(baseRoomToUnread).has(action.roomId)) {
set(
baseRoomToUnread,
produce(get(baseRoomToUnread), (draftRoomToUnread) =>
deleteUnreadInfo(
draftRoomToUnread,
getAllParents(get(roomToParentsAtom), action.roomId),
action.roomId
)
)
);
}
}
);
export const useBindRoomToUnreadAtom = (
mx: MatrixClient,
unreadAtom: WritableAtom<RoomToUnread, RoomToUnreadAction>,
muteChangesAtom: PrimitiveAtom<MuteChanges>
) => {
const setUnreadAtom = useSetAtom(unreadAtom);
const muteChanges = useAtomValue(muteChangesAtom);
useEffect(() => {
setUnreadAtom({
type: 'RESET',
unreadInfos: getUnreadInfos(mx),
});
}, [mx, setUnreadAtom]);
useEffect(() => {
const handleTimelineEvent = (
mEvent: MatrixEvent,
room: Room | undefined,
toStartOfTimeline: boolean | undefined,
removed: boolean,
data: IRoomTimelineData
) => {
if (!room || !data.liveEvent || room.isSpaceRoom() || !isNotificationEvent(mEvent)) return;
if (getNotificationType(mx, room.roomId) === NotificationType.Mute) {
setUnreadAtom({
type: 'DELETE',
roomId: room.roomId,
});
return;
}
if (mEvent.getSender() === mx.getUserId()) return;
setUnreadAtom({ type: 'PUT', unreadInfo: getUnreadInfo(room) });
};
mx.on(RoomEvent.Timeline, handleTimelineEvent);
return () => {
mx.removeListener(RoomEvent.Timeline, handleTimelineEvent);
};
}, [mx, setUnreadAtom]);
useEffect(() => {
const handleReceipt = (mEvent: MatrixEvent, room: Room) => {
if (mEvent.getType() === 'm.receipt') {
const myUserId = mx.getUserId();
if (!myUserId) return;
if (room.isSpaceRoom()) return;
const content = mEvent.getContent<ReceiptContent>();
const isMyReceipt = Object.keys(content).find((eventId) =>
(Object.keys(content[eventId]) as ReceiptType[]).find(
(receiptType) => content[eventId][receiptType][myUserId]
)
);
if (isMyReceipt) {
setUnreadAtom({ type: 'DELETE', roomId: room.roomId });
}
}
};
mx.on(RoomEvent.Receipt, handleReceipt);
return () => {
mx.removeListener(RoomEvent.Receipt, handleReceipt);
};
}, [mx, setUnreadAtom]);
useEffect(() => {
muteChanges.removed.forEach((roomId) => {
const room = mx.getRoom(roomId);
if (!room) return;
if (!roomHaveUnread(mx, room)) return;
setUnreadAtom({ type: 'PUT', unreadInfo: getUnreadInfo(room) });
});
muteChanges.added.forEach((roomId) => {
setUnreadAtom({ type: 'DELETE', roomId });
});
}, [mx, setUnreadAtom, muteChanges]);
useEffect(() => {
const handleMembershipChange = (room: Room, membership: string) => {
if (membership !== Membership.Join) {
setUnreadAtom({
type: 'DELETE',
roomId: room.roomId,
});
}
};
mx.on(RoomEvent.MyMembership, handleMembershipChange);
return () => {
mx.removeListener(RoomEvent.MyMembership, handleMembershipChange);
};
}, [mx, setUnreadAtom]);
};
-3
View File
@@ -1,3 +0,0 @@
import { atom } from 'jotai';
export const selectedRoomAtom = atom<string | undefined>(undefined);
-8
View File
@@ -1,8 +0,0 @@
import { atom } from 'jotai';
export enum SidebarTab {
Home = 'Home',
People = 'People',
}
export const selectedTabAtom = atom<SidebarTab | string>(SidebarTab.Home);
-47
View File
@@ -1,47 +0,0 @@
import { atom } from 'jotai';
const STORAGE_KEY = 'settings';
export interface Settings {
themeIndex: number;
useSystemTheme: boolean;
isMarkdown: boolean;
isPeopleDrawer: boolean;
hideMembershipEvents: boolean;
hideNickAvatarEvents: boolean;
showNotifications: boolean;
isNotificationSounds: boolean;
}
const defaultSettings: Settings = {
themeIndex: 0,
useSystemTheme: true,
isMarkdown: true,
isPeopleDrawer: true,
hideMembershipEvents: false,
hideNickAvatarEvents: true,
showNotifications: true,
isNotificationSounds: true,
};
export const getSettings = () => {
const settings = localStorage.getItem(STORAGE_KEY);
if (settings === null) return defaultSettings;
return JSON.parse(settings) as Settings;
};
export const setSettings = (settings: Settings) => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
};
const baseSettings = atom<Settings>(getSettings());
export const settingsAtom = atom<Settings, Settings>(
(get) => get(baseSettings),
(get, set, update) => {
set(baseSettings, update);
setSettings(update);
}
);
-34
View File
@@ -1,34 +0,0 @@
import produce from 'immer';
import { atom } from 'jotai';
import { MatrixClient } from 'matrix-js-sdk';
type RoomInfo = {
roomId: string;
timestamp: number;
};
type TabToRoom = Map<string, RoomInfo>;
type TabToRoomAction = {
type: 'PUT';
tabInfo: { tabId: string; roomInfo: RoomInfo };
};
const baseTabToRoom = atom<TabToRoom>(new Map());
export const tabToRoomAtom = atom<TabToRoom, TabToRoomAction>(
(get) => get(baseTabToRoom),
(get, set, action) => {
if (action.type === 'PUT') {
set(
baseTabToRoom,
produce(get(baseTabToRoom), (draft) => {
draft.set(action.tabInfo.tabId, action.tabInfo.roomInfo);
})
);
}
}
);
export const useBindTabToRoomAtom = (mx: MatrixClient) => {
console.log(mx);
// TODO:
};
-64
View File
@@ -1,64 +0,0 @@
import { useSetAtom, WritableAtom } from 'jotai';
import { ClientEvent, MatrixClient, Room, RoomEvent } from 'matrix-js-sdk';
import { useEffect } from 'react';
import { Membership } from '../../types/matrix/room';
export type RoomsAction =
| {
type: 'INITIALIZE';
rooms: string[];
}
| {
type: 'PUT' | 'DELETE';
roomId: string;
};
export const useBindRoomsWithMembershipsAtom = (
mx: MatrixClient,
roomsAtom: WritableAtom<string[], RoomsAction>,
memberships: Membership[]
) => {
const setRoomsAtom = useSetAtom(roomsAtom);
useEffect(() => {
const satisfyMembership = (room: Room): boolean =>
!!memberships.find((membership) => membership === room.getMyMembership());
setRoomsAtom({
type: 'INITIALIZE',
rooms: mx
.getRooms()
.filter(satisfyMembership)
.map((room) => room.roomId),
});
const handleAddRoom = (room: Room) => {
if (satisfyMembership(room)) {
setRoomsAtom({ type: 'PUT', roomId: room.roomId });
}
};
const handleMembershipChange = (room: Room) => {
if (!satisfyMembership(room)) {
setRoomsAtom({ type: 'DELETE', roomId: room.roomId });
}
};
const handleDeleteRoom = (roomId: string) => {
setRoomsAtom({ type: 'DELETE', roomId });
};
mx.on(ClientEvent.Room, handleAddRoom);
mx.on(RoomEvent.MyMembership, handleMembershipChange);
mx.on(ClientEvent.DeleteRoom, handleDeleteRoom);
return () => {
mx.removeListener(ClientEvent.Room, handleAddRoom);
mx.removeListener(RoomEvent.MyMembership, handleMembershipChange);
mx.removeListener(ClientEvent.DeleteRoom, handleDeleteRoom);
};
}, [mx, memberships, setRoomsAtom]);
};
export const compareRoomsEqual = (a: string[], b: string[]) => {
if (a.length !== b.length) return false;
return a.every((roomId, roomIdIndex) => roomId === b[roomIdIndex]);
};
+4 -18
View File
@@ -7,21 +7,18 @@ import { initRoomListListener } from '../../../client/event/roomList';
import Text from '../../atoms/text/Text';
import Spinner from '../../atoms/spinner/Spinner';
import Navigation from '../../organisms/navigation/Navigation';
import ContextMenu, { MenuItem } from '../../atoms/context-menu/ContextMenu';
import IconButton from '../../atoms/button/IconButton';
import ReusableContextMenu from '../../atoms/context-menu/ReusableContextMenu';
import Room from '../../organisms/room/Room';
import Windows from '../../organisms/pw/Windows';
import Dialogs from '../../organisms/pw/Dialogs';
import EmojiBoardOpener from '../../organisms/emoji-board/EmojiBoardOpener';
import logout from '../../../client/action/logout';
import initMatrix from '../../../client/initMatrix';
import navigation from '../../../client/state/navigation';
import cons from '../../../client/state/cons';
import DragDrop from '../../organisms/drag-drop/DragDrop';
import VerticalMenuIC from '../../../../public/res/ic/outlined/vertical-menu.svg';
function Client() {
const [isLoading, changeLoading] = useState(true);
const [loadingMsg, setLoadingMsg] = useState('Heating up');
@@ -77,20 +74,9 @@ function Client() {
if (isLoading) {
return (
<div className="loading-display">
<div className="loading__menu">
<ContextMenu
placement="bottom"
content={(
<>
<MenuItem onClick={() => initMatrix.clearCacheAndReload()}>
Clear cache & reload
</MenuItem>
<MenuItem onClick={() => initMatrix.logout()}>Logout</MenuItem>
</>
)}
render={(toggle) => <IconButton size="extra-small" onClick={toggle} src={VerticalMenuIC} />}
/>
</div>
<button className="loading__logout" onClick={logout} type="button">
<Text variant="b3">Logout</Text>
</button>
<Spinner />
<Text className="loading__message" variant="b2">{loadingMsg}</Text>
+4 -4
View File
@@ -45,12 +45,12 @@
position: absolute;
bottom: var(--sp-normal);
}
.loading__menu {
.loading__logout {
position: absolute;
top: var(--sp-extra-tight);
bottom: var(--sp-extra-tight);
right: var(--sp-extra-tight);
cursor: pointer;
.context-menu__item .text {
margin: 0 !important;
.text {
color: var(--tc-link);
}
}
-8
View File
@@ -1,8 +0,0 @@
export type DisposeCallback<Q extends unknown[] = [], R = void> = (...args: Q) => R;
export type DisposableContext<P extends unknown[] = [], Q extends unknown[] = [], R = void> = (
...args: P
) => DisposeCallback<Q, R>;
export const disposable = <P extends unknown[], Q extends unknown[] = [], R = void>(
context: DisposableContext<P, Q, R>
) => context;
-217
View File
@@ -1,217 +0,0 @@
import {
IPushRule,
IPushRules,
MatrixClient,
MatrixEvent,
NotificationCountType,
Room,
} from 'matrix-js-sdk';
import { AccountDataEvent } from '../../types/matrix/accountData';
import {
NotificationType,
RoomToParents,
RoomType,
StateEvent,
UnreadInfo,
} from '../../types/matrix/room';
export const getStateEvent = (
room: Room,
eventType: StateEvent,
stateKey = ''
): MatrixEvent | null => room.currentState.getStateEvents(eventType, stateKey);
export const getStateEvents = (room: Room, eventType: StateEvent): MatrixEvent[] =>
room.currentState.getStateEvents(eventType);
export const getAccountData = (
mx: MatrixClient,
eventType: AccountDataEvent
): MatrixEvent | undefined => mx.getAccountData(eventType);
export const getMDirects = (mDirectEvent: MatrixEvent): Set<string> => {
const roomIds = new Set<string>();
const userIdToDirects = mDirectEvent?.getContent();
if (userIdToDirects === undefined) return roomIds;
Object.keys(userIdToDirects).forEach((userId) => {
const directs = userIdToDirects[userId];
if (Array.isArray(directs)) {
directs.forEach((id) => {
if (typeof id === 'string') roomIds.add(id);
});
}
});
return roomIds;
};
export const isDirectInvite = (room: Room | null, myUserId: string | null): boolean => {
if (!room || !myUserId) return false;
const me = room.getMember(myUserId);
const memberEvent = me?.events?.member;
const content = memberEvent?.getContent();
return content?.is_direct === true;
};
export const isSpace = (room: Room | null): boolean => {
if (!room) return false;
const event = getStateEvent(room, StateEvent.RoomCreate);
if (!event) return false;
return event.getContent().type === RoomType.Space;
};
export const isRoom = (room: Room | null): boolean => {
if (!room) return false;
const event = getStateEvent(room, StateEvent.RoomCreate);
if (!event) return false;
return event.getContent().type === undefined;
};
export const isUnsupportedRoom = (room: Room | null): boolean => {
if (!room) return false;
const event = getStateEvent(room, StateEvent.RoomCreate);
if (!event) return true; // Consider room unsupported if m.room.create event doesn't exist
return event.getContent().type !== undefined && event.getContent().type !== RoomType.Space;
};
export function isValidChild(mEvent: MatrixEvent): boolean {
return mEvent.getType() === StateEvent.SpaceChild && Object.keys(mEvent.getContent()).length > 0;
}
export const getAllParents = (roomToParents: RoomToParents, roomId: string): Set<string> => {
const allParents = new Set<string>();
const addAllParentIds = (rId: string) => {
if (allParents.has(rId)) return;
allParents.add(rId);
const parents = roomToParents.get(rId);
parents?.forEach((id) => addAllParentIds(id));
};
addAllParentIds(roomId);
allParents.delete(roomId);
return allParents;
};
export const getSpaceChildren = (room: Room) =>
getStateEvents(room, StateEvent.SpaceChild).reduce<string[]>((filtered, mEvent) => {
const stateKey = mEvent.getStateKey();
if (isValidChild(mEvent) && stateKey) {
filtered.push(stateKey);
}
return filtered;
}, []);
export const mapParentWithChildren = (
roomToParents: RoomToParents,
roomId: string,
children: string[]
) => {
const allParents = getAllParents(roomToParents, roomId);
children.forEach((childId) => {
if (allParents.has(childId)) {
// Space cycle detected.
return;
}
const parents = roomToParents.get(childId) ?? new Set<string>();
parents.add(roomId);
roomToParents.set(childId, parents);
});
};
export const getRoomToParents = (mx: MatrixClient): RoomToParents => {
const map: RoomToParents = new Map();
mx.getRooms()
.filter((room) => isSpace(room))
.forEach((room) => mapParentWithChildren(map, room.roomId, getSpaceChildren(room)));
return map;
};
export const isMutedRule = (rule: IPushRule) =>
rule.actions[0] === 'dont_notify' && rule.conditions?.[0]?.kind === 'event_match';
export const findMutedRule = (overrideRules: IPushRule[], roomId: string) =>
overrideRules.find((rule) => rule.rule_id === roomId && isMutedRule(rule));
export const getNotificationType = (mx: MatrixClient, roomId: string): NotificationType => {
let roomPushRule: IPushRule | undefined;
try {
roomPushRule = mx.getRoomPushRule('global', roomId);
} catch {
roomPushRule = undefined;
}
if (!roomPushRule) {
const overrideRules = mx.getAccountData('m.push_rules')?.getContent<IPushRules>()
?.global?.override;
if (!overrideRules) return NotificationType.Default;
return findMutedRule(overrideRules, roomId) ? NotificationType.Mute : NotificationType.Default;
}
if (roomPushRule.actions[0] === 'notify') return NotificationType.AllMessages;
return NotificationType.MentionsAndKeywords;
};
export const isNotificationEvent = (mEvent: MatrixEvent) => {
const eType = mEvent.getType();
if (
['m.room.create', 'm.room.message', 'm.room.encrypted', 'm.room.member', 'm.sticker'].find(
(type) => type === eType
)
)
return false;
if (eType === 'm.room.member') return false;
if (mEvent.isRedacted()) return false;
if (mEvent.getRelation()?.rel_type === 'm.replace') return false;
return true;
};
export const roomHaveUnread = (mx: MatrixClient, room: Room) => {
const userId = mx.getUserId();
if (!userId) return false;
const readUpToId = room.getEventReadUpTo(userId);
const liveEvents = room.getLiveTimeline().getEvents();
if (liveEvents[liveEvents.length - 1]?.getSender() === userId) {
return false;
}
for (let i = liveEvents.length - 1; i >= 0; i -= 1) {
const event = liveEvents[i];
if (!event) return false;
if (event.getId() === readUpToId) return false;
if (isNotificationEvent(event)) return true;
}
return true;
};
export const getUnreadInfo = (room: Room): UnreadInfo => {
const total = room.getUnreadNotificationCount(NotificationCountType.Total);
const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight);
return {
roomId: room.roomId,
highlight,
total: highlight > total ? highlight : total,
};
};
export const getUnreadInfos = (mx: MatrixClient): UnreadInfo[] => {
const unreadInfos = mx.getRooms().reduce<UnreadInfo[]>((unread, room) => {
if (room.isSpaceRoom()) return unread;
if (room.getMyMembership() !== 'join') return unread;
if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return unread;
if (roomHaveUnread(mx, room)) {
unread.push(getUnreadInfo(room));
}
return unread;
}, []);
return unreadInfos;
};
+16
View File
@@ -0,0 +1,16 @@
import initMatrix from '../initMatrix';
async function logout() {
const mx = initMatrix.matrixClient;
mx.stopClient();
try {
await mx.logout();
} catch {
// ignore if failed to logout
}
mx.clearStores();
window.localStorage.clear();
window.location.reload();
}
export default logout;
+1 -2
View File
@@ -139,13 +139,12 @@ export function openViewSource(event) {
});
}
export function replyTo(userId, eventId, body, formattedBody) {
export function replyTo(userId, eventId, body) {
appDispatcher.dispatch({
type: cons.actions.navigation.CLICK_REPLY_TO,
userId,
eventId,
body,
formattedBody,
});
}
+10 -6
View File
@@ -236,12 +236,16 @@ async function createRoom(opts) {
});
}
if (parentId && joinRule === 'restricted') {
const caps = await mx.getCapabilities();
if (caps['m.room_versions'].available?.['9'] !== 'stable') {
throw new Error("ERROR: The server doesn't support restricted rooms");
}
if (Number(caps['m.room_versions'].default) < 9) {
options.room_version = '9';
try {
const caps = await mx.getCapabilities();
options.room_version = caps
?.['m.room_versions']
?.['org.matrix.msc3244.room_capabilities']
?.restricted
?.preferred
|| undefined;
} catch {
console.error('Can\'t find room version for restricted.');
}
options.initial_state.push({
type: 'm.room.join_rules',
+4 -24
View File
@@ -1,6 +1,5 @@
import EventEmitter from 'events';
import * as sdk from 'matrix-js-sdk';
import Olm from '@matrix-org/olm';
// import { logger } from 'matrix-js-sdk/lib/logger';
import { secret } from './state/auth';
@@ -11,7 +10,7 @@ import Notifications from './state/Notifications';
import { cryptoCallbacks } from './state/secretStorageKeys';
import navigation from './state/navigation';
global.Olm = Olm;
global.Olm = require('@matrix-org/olm');
// logger.disableAll();
@@ -79,7 +78,7 @@ class InitMatrix extends EventEmitter {
this.emit('init_loading_finished');
this.notifications._initNoti();
} else {
this.notifications?._initNoti();
this.notifications._initNoti();
}
},
RECONNECTING: () => {
@@ -99,32 +98,13 @@ class InitMatrix extends EventEmitter {
}
listenEvents() {
this.matrixClient.on('Session.logged_out', async () => {
this.matrixClient.on('Session.logged_out', () => {
this.matrixClient.stopClient();
await this.matrixClient.clearStores();
this.matrixClient.clearStores();
window.localStorage.clear();
window.location.reload();
});
}
async logout() {
this.matrixClient.stopClient();
try {
await this.matrixClient.logout();
} catch {
// ignore if failed to logout
}
await this.matrixClient.clearStores();
window.localStorage.clear();
window.location.reload();
}
clearCacheAndReload() {
this.matrixClient.stopClient();
this.matrixClient.store.deleteAllData().then(() => {
window.location.reload();
});
}
}
const initMatrix = new InitMatrix();
-7
View File
@@ -1,7 +0,0 @@
import { MatrixClient } from 'matrix-js-sdk';
import initMatrix from './initMatrix';
export const mx = (): MatrixClient => {
if (!initMatrix.matrixClient) console.error('Matrix client is used before initialization!');
return initMatrix.matrixClient!;
};
+1 -39
View File
@@ -10,7 +10,6 @@ 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';
import { html, plain } from '../../util/markdown';
function isNotifEvent(mEvent) {
const eType = mEvent.getType();
@@ -44,8 +43,6 @@ class Notifications extends EventEmitter {
this.roomList = roomList;
this.roomIdToNoti = new Map();
this.roomIdToPopupNotis = new Map();
this.eventIdToPopupNoti = new Map();
// this._initNoti();
this._listenEvents();
@@ -258,51 +255,20 @@ class Notifications extends EventEmitter {
scale: 8,
});
const content = mEvent.getContent();
const state = { kind: 'notification', onlyPlain: true };
let body;
if (content.format === 'org.matrix.custom.html') {
body = html(content.formatted_body, state);
} else {
body = plain(content.body, state);
}
const noti = new window.Notification(title, {
body: body.plain,
body: mEvent.getContent().body,
icon,
tag: mEvent.getId(),
silent: settings.isNotificationSounds,
});
if (settings.isNotificationSounds) {
noti.onshow = () => this._playNotiSound();
}
noti.onclick = () => selectRoom(room.roomId, mEvent.getId());
this.eventIdToPopupNoti.set(mEvent.getId(), noti);
if (this.roomIdToPopupNotis.has(room.roomId)) {
this.roomIdToPopupNotis.get(room.roomId).push(noti);
} else {
this.roomIdToPopupNotis.set(room.roomId, [noti]);
}
} else {
this._playNotiSound();
}
}
_deletePopupNoti(eventId) {
this.eventIdToPopupNoti.get(eventId)?.close();
this.eventIdToPopupNoti.delete(eventId);
}
_deletePopupRoomNotis(roomId) {
this.roomIdToPopupNotis.get(roomId)?.forEach((n) => {
this.eventIdToPopupNoti.delete(n.tag);
n.close();
});
this.roomIdToPopupNotis.delete(roomId);
}
_playNotiSound() {
if (!this._notiAudio) {
this._notiAudio = document.getElementById('notificationSound');
@@ -319,8 +285,6 @@ class Notifications extends EventEmitter {
_listenEvents() {
this.matrixClient.on('Room.timeline', (mEvent, room) => {
if (mEvent.isRedaction()) this._deletePopupNoti(mEvent.event.redacts);
if (room.isSpaceRoom()) return;
if (!isNotifEvent(mEvent)) return;
@@ -391,8 +355,6 @@ class Notifications extends EventEmitter {
if (readerUserId !== this.matrixClient.getUserId()) return;
this.deleteNoti(room.roomId);
this._deletePopupRoomNotis(room.roomId);
}
});
+167 -78
View File
@@ -6,9 +6,11 @@ import { getBlobSafeMimeType } from '../../util/mimetypes';
import { sanitizeText } from '../../util/sanitize';
import cons from './cons';
import settings from './settings';
import { markdown, plain } from '../../util/markdown';
import { htmlOutput, parser } from '../../util/markdown';
const blurhashField = 'xyz.amorgan.blurhash';
const MXID_REGEX = /\B@\S+:\S+\.\S+[^.,:;?!\s]/g;
const SHORTCODE_REGEX = /\B:([\w-]+):\B/g;
function encodeBlurhash(img) {
const canvas = document.createElement('canvas');
@@ -98,6 +100,91 @@ 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);
}
function getReplyFormattedBody(roomId, reply) {
const replyToLink = `<a href="https://matrix.to/#/${roomId}/${reply.eventId}">In reply to</a>`;
const userLink = `<a href="https://matrix.to/#/${reply.userId}">${reply.userId}</a>`;
const formattedReply = getFormattedBody(reply.body.replace(/\n/g, '\n> '));
return `<mx-reply><blockquote>${replyToLink}${userLink}<br />${formattedReply}</blockquote></mx-reply>`;
}
function bindReplyToContent(roomId, reply, content) {
const newContent = { ...content };
newContent.body = `> <${reply.userId}> ${reply.body.replace(/\n/g, '\n> ')}`;
newContent.body += `\n\n${content.body}`;
newContent.format = 'org.matrix.custom.html';
newContent['m.relates_to'] = content['m.relates_to'] || {};
newContent['m.relates_to']['m.in_reply_to'] = { event_id: reply.eventId };
const formattedReply = getReplyFormattedBody(roomId, reply);
newContent.formatted_body = formattedReply + (content.formatted_body || content.body);
return newContent;
}
function findAndReplace(text, regex, filter, replace) {
let copyText = text;
Array.from(copyText.matchAll(regex))
.filter(filter)
.reverse() /* to replace backward to forward */
.forEach((match) => {
const matchText = match[0];
const tag = replace(match);
copyText = copyText.substr(0, match.index)
+ tag
+ copyText.substr(match.index + matchText.length);
});
return copyText;
}
function formatUserPill(room, text) {
const { userIdsToDisplayNames } = room.currentState;
return findAndReplace(
text,
MXID_REGEX,
(match) => userIdsToDisplayNames[match[0]],
(match) => (
`<a href="https://matrix.to/#/${match[0]}">@${userIdsToDisplayNames[match[0]]}</a>`
),
);
}
function formatEmoji(mx, room, roomList, text) {
const parentIds = roomList.getAllParentSpaces(room.roomId);
const parentRooms = [...parentIds].map((id) => mx.getRoom(id));
const allEmoji = getShortcodeToEmoji(mx, [room, ...parentRooms]);
return findAndReplace(
text,
SHORTCODE_REGEX,
(match) => allEmoji.has(match[1]),
(match) => {
const emoji = allEmoji.get(match[1]);
let tag;
if (emoji.mxc) {
tag = `<img data-mx-emoticon="" src="${
emoji.mxc
}" alt=":${
emoji.shortcode
}:" title=":${
emoji.shortcode
}:" height="32" />`;
} else {
tag = emoji.unicode;
}
return tag;
},
);
}
class RoomsInput extends EventEmitter {
constructor(mx, roomList) {
super();
@@ -187,76 +274,8 @@ class RoomsInput extends EventEmitter {
return this.roomIdToInput.get(roomId)?.isSending || false;
}
getContent(roomId, options, message, reply, edit) {
const msgType = options?.msgType || 'm.text';
const autoMarkdown = options?.autoMarkdown ?? true;
async sendInput(roomId, msgType) {
const room = this.matrixClient.getRoom(roomId);
const userNames = room.currentState.userIdsToDisplayNames;
const parentIds = this.roomList.getAllParentSpaces(room.roomId);
const parentRooms = [...parentIds].map((id) => this.matrixClient.getRoom(id));
const emojis = getShortcodeToEmoji(this.matrixClient, [room, ...parentRooms]);
const output = settings.isMarkdown && autoMarkdown ? markdown : plain;
const body = output(message, { userNames, emojis });
const content = {
body: body.plain,
msgtype: msgType,
};
if (!body.onlyPlain || reply) {
content.format = 'org.matrix.custom.html';
content.formatted_body = body.html;
}
if (edit) {
content['m.new_content'] = { ...content };
content['m.relates_to'] = {
event_id: edit.getId(),
rel_type: 'm.replace',
};
const isReply = edit.getWireContent()['m.relates_to']?.['m.in_reply_to'];
if (isReply) {
content.format = 'org.matrix.custom.html';
content.formatted_body = body.html;
}
content.body = ` * ${content.body}`;
if (content.formatted_body) content.formatted_body = ` * ${content.formatted_body}`;
if (isReply) {
const eBody = edit.getContent().body;
const replyHead = eBody.substring(0, eBody.indexOf('\n\n'));
if (replyHead) content.body = `${replyHead}\n\n${content.body}`;
const eFBody = edit.getContent().formatted_body;
const fReplyHead = eFBody.substring(0, eFBody.indexOf('</mx-reply>'));
if (fReplyHead) content.formatted_body = `${fReplyHead}</mx-reply>${content.formatted_body}`;
}
}
if (reply) {
content['m.relates_to'] = {
'm.in_reply_to': {
event_id: reply.eventId,
},
};
content.body = `> <${reply.userId}> ${reply.body.replace(/\n/g, '\n> ')}\n\n${content.body}`;
const replyToLink = `<a href="https://matrix.to/#/${encodeURIComponent(roomId)}/${encodeURIComponent(reply.eventId)}">In reply to</a>`;
const userLink = `<a href="https://matrix.to/#/${encodeURIComponent(reply.userId)}">${sanitizeText(reply.userId)}</a>`;
const fallback = `<mx-reply><blockquote>${replyToLink}${userLink}<br />${reply.formattedBody || sanitizeText(reply.body)}</blockquote></mx-reply>`;
content.formatted_body = fallback + content.formatted_body;
}
return content;
}
async sendInput(roomId, options) {
const input = this.getInput(roomId);
input.isSending = true;
this.roomIdToInput.set(roomId, input);
@@ -266,7 +285,35 @@ class RoomsInput extends EventEmitter {
}
if (this.getMessage(roomId).trim() !== '') {
const content = this.getContent(roomId, options, input.message, input.replyTo);
const rawMessage = input.message;
let content = {
body: rawMessage,
msgtype: msgType ?? 'm.text',
};
// Apply formatting if relevant
let formattedBody = settings.isMarkdown
? getFormattedBody(rawMessage)
: sanitizeText(rawMessage);
formattedBody = formatUserPill(room, formattedBody);
formattedBody = formatEmoji(this.matrixClient, room, this.roomList, formattedBody);
content.body = findAndReplace(
content.body,
MXID_REGEX,
(match) => room.currentState.userIdsToDisplayNames[match[0]],
(match) => `@${room.currentState.userIdsToDisplayNames[match[0]]}`,
);
if (formattedBody !== sanitizeText(rawMessage)) {
// Formatting was applied, and we need to switch to custom HTML
content.format = 'org.matrix.custom.html';
content.formatted_body = formattedBody;
}
if (typeof input.replyTo !== 'undefined') {
content = bindReplyToContent(roomId, input.replyTo, content);
}
this.matrixClient.sendMessage(roomId, content);
}
@@ -395,7 +442,7 @@ class RoomsInput extends EventEmitter {
input.attachment.uploadingPromise = uploadingPromise;
this.roomIdToInput.set(roomId, input);
const { content_uri: url } = await uploadingPromise;
const url = await uploadingPromise;
delete input.attachment.uploadingPromise;
this.roomIdToInput.set(roomId, input);
@@ -409,13 +456,55 @@ class RoomsInput extends EventEmitter {
}
async sendEditedMessage(roomId, mEvent, editedBody) {
const content = this.getContent(
roomId,
{ msgType: mEvent.getWireContent().msgtype },
editedBody,
null,
mEvent,
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,
'm.new_content': {
body: editedBody,
msgtype,
},
'm.relates_to': {
event_id: mEvent.getId(),
rel_type: 'm.replace',
},
};
// Apply formatting if relevant
let formattedBody = settings.isMarkdown
? getFormattedBody(editedBody)
: sanitizeText(editedBody);
formattedBody = formatUserPill(room, formattedBody);
formattedBody = formatEmoji(this.matrixClient, room, this.roomList, formattedBody);
content.body = findAndReplace(
content.body,
MXID_REGEX,
(match) => room.currentState.userIdsToDisplayNames[match[0]],
(match) => `@${room.currentState.userIdsToDisplayNames[match[0]]}`,
);
if (formattedBody !== sanitizeText(editedBody)) {
content.formatted_body = ` * ${formattedBody}`;
content.format = 'org.matrix.custom.html';
content['m.new_content'].formatted_body = formattedBody;
content['m.new_content'].format = 'org.matrix.custom.html';
}
if (isReply) {
const evBody = mEvent.getContent().body;
const replyHead = evBody.slice(0, evBody.indexOf('\n\n'));
const evFBody = mEvent.getContent().formatted_body;
const fReplyHead = evFBody.slice(0, evFBody.indexOf('</mx-reply>'));
content.format = 'org.matrix.custom.html';
content.formatted_body = `${fReplyHead}</mx-reply>${(content.formatted_body || content.body)}`;
content.body = `${replyHead}\n\n${content.body}`;
}
this.matrixClient.sendMessage(roomId, content);
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
const cons = {
version: '2.2.2',
version: '2.1.3',
secretKey: {
ACCESS_TOKEN: 'cinny_access_token',
DEVICE_ID: 'cinny_device_id',
-1
View File
@@ -375,7 +375,6 @@ class Navigation extends EventEmitter {
action.userId,
action.eventId,
action.body,
action.formattedBody,
);
},
[cons.actions.navigation.OPEN_SEARCH]: () => {
+4 -12
View File
@@ -1,13 +1,5 @@
/* eslint-disable import/first */
import React from 'react';
import ReactDom from 'react-dom';
import { enableMapSet } from 'immer';
import '@fontsource/inter/variable.css';
import 'folds/dist/style.css';
import { lightTheme, configClass, config, varsClass } from 'folds';
enableMapSet();
import './font';
import './index.scss';
@@ -15,9 +7,9 @@ import settings from './client/state/settings';
import App from './app/pages/App';
document.body.classList.add(lightTheme, configClass, varsClass);
document.body.style.fontFamily = config.font.Inter;
settings.applyTheme();
ReactDom.render(<App />, document.getElementById('root'));
ReactDom.render(
<App />,
document.getElementById('root'),
);
-6
View File
@@ -1,6 +0,0 @@
export enum AccountDataEvent {
PushRules = 'm.push_rules',
Direct = 'm.direct',
IgnoredUserList = 'm.ignored_user_list',
CinnySpaces = 'in.cinny.spaces',
}
-59
View File
@@ -1,59 +0,0 @@
export enum Membership {
Invite = 'invite',
Knock = 'knock',
Join = 'join',
Leave = 'leave',
Ban = 'ban',
}
export enum StateEvent {
RoomCanonicalAlias = 'm.room.canonical_alias',
RoomCreate = 'm.room.create',
RoomJoinRules = 'm.room.join_rules',
RoomMember = 'm.room.member',
RoomThirdPartyInvite = 'm.room.third_party_invite',
RoomPowerLevels = 'm.room.power_levels',
RoomName = 'm.room.name',
RoomTopic = 'm.room.topic',
RoomAvatar = 'm.room.avatar',
RoomPinnedEvents = 'm.room.pinned_events',
RoomEncryption = 'm.room.encryption',
RoomHistoryVisibility = 'm.room.history_visibility',
RoomGuestAccess = 'm.room.guest_access',
RoomServerAcl = 'm.room.server_acl',
RoomTombstone = 'm.room.tombstone',
SpaceChild = 'm.space.child',
SpaceParent = 'm.space.parent',
}
export enum RoomType {
Space = 'm.space',
}
export enum NotificationType {
Default = 'default',
AllMessages = 'all_messages',
MentionsAndKeywords = 'mentions_and_keywords',
Mute = 'mute',
}
export type RoomToParents = Map<string, Set<string>>;
export type RoomToUnread = Map<
string,
{
total: number;
highlight: number;
from: Set<string> | null;
}
>;
export type UnreadInfo = {
roomId: string;
total: number;
highlight: number;
};
export type MuteChanges = {
added: string[];
removed: string[];
};
-24
View File
@@ -204,27 +204,3 @@ export function scaleDownImage(imageFile, width, height) {
img.src = imgURL;
});
}
/**
* @param {sigil} string sigil to search for (for example '@', '#' or '$')
* @param {flags} string regex flags
* @param {prefix} string prefix appended at the beginning of the regex
* @returns {RegExp}
*/
export function idRegex(sigil, flags, prefix) {
const servername = '(?:[a-zA-Z0-9-.]*[a-zA-Z0-9]+|\\[\\S+?\\])(?::\\d+)?';
return new RegExp(`${prefix}(${sigil}\\S+:${servername})`, flags);
}
const matrixToRegex = /^https?:\/\/matrix.to\/#\/(\S+:\S+)/;
/**
* Parses a matrix.to URL into an matrix id.
* This function can later be extended to support matrix: URIs
* @param {string} uri The URI to parse
* @returns {string|null} The id or null if the URI does not match
*/
export function parseIdUri(uri) {
const res = decodeURIComponent(uri).match(matrixToRegex);
if (!res) return null;
return res[1];
}
+30 -456
View File
@@ -1,84 +1,25 @@
/* eslint-disable no-param-reassign */
/* eslint-disable no-use-before-define */
import SimpleMarkdown from '@khanacademy/simple-markdown';
import { idRegex, parseIdUri } from './common';
const {
defaultRules, parserFor, outputFor, anyScopeRegex, blockRegex, inlineRegex,
sanitizeText, sanitizeUrl,
defaultRules, parserFor, outputFor, anyScopeRegex, blockRegex, inlineRegex, htmlTag, sanitizeText,
} = SimpleMarkdown;
function htmlTag(tagName, content, attributes, isClosed) {
let s = '';
Object.entries(attributes || {}).forEach(([k, v]) => {
if (v !== undefined) {
s += ` ${sanitizeText(k)}`;
if (v !== null) s += `="${sanitizeText(v)}"`;
}
});
s = `<${tagName}${s}>`;
if (isClosed === false) {
return s;
}
return `${s}${content}</${tagName}>`;
}
function mathHtml(wrap, node) {
return htmlTag(wrap, htmlTag('code', sanitizeText(node.content)), { 'data-mx-maths': node.content });
}
const emojiRegex = /^:([\w-]+):/;
const plainRules = {
const rules = {
...defaultRules,
Array: {
...defaultRules.Array,
plain: defaultRules.Array.html,
plain: (arr, output, state) => arr.map((node) => output(node, state)).join(''),
},
userMention: {
order: defaultRules.em.order - 0.9,
match: inlineRegex(idRegex('@', undefined, '^')),
parse: (capture, _, state) => ({
type: 'mention',
content: state.userNames[capture[1]] ? `@${state.userNames[capture[1]]}` : capture[1],
id: capture[1],
}),
},
roomMention: {
order: defaultRules.em.order - 0.8,
match: inlineRegex(idRegex('#', undefined, '^')),
parse: (capture) => ({ type: 'mention', content: capture[1], id: capture[1] }),
},
mention: {
plain: (node, _, state) => (state.kind === 'edit' ? node.id : node.content),
html: (node) => htmlTag('a', sanitizeText(node.content), {
href: `https://matrix.to/#/${encodeURIComponent(node.id)}`,
}),
},
emoji: {
order: defaultRules.em.order - 0.1,
match: (source, state) => {
if (!state.inline) return null;
const capture = emojiRegex.exec(source);
if (!capture) return null;
const emoji = state.emojis.get(capture[1]);
if (emoji) return capture;
return null;
},
parse: (capture, _, state) => ({ content: capture[1], emoji: state.emojis.get(capture[1]) }),
plain: ({ emoji }) => (emoji.mxc
? `:${emoji.shortcode}:`
: emoji.unicode),
html: ({ emoji }) => (emoji.mxc
? htmlTag('img', null, {
'data-mx-emoticon': null,
src: emoji.mxc,
alt: `:${emoji.shortcode}:`,
title: `:${emoji.shortcode}:`,
height: 32,
}, false)
: emoji.unicode),
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,
@@ -93,186 +34,6 @@ const plainRules = {
...defaultRules.escape,
plain: (node, output, state) => `\\${output(node.content, state)}`,
},
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, _, state) => (state.kind === 'edit'
? node.content.replace(/(\*|_|!\[|\[|\|\||\$\$?)/g, '\\$1')
: node.content),
},
};
const markdownRules = {
...defaultRules,
...plainRules,
heading: {
...defaultRules.heading,
match: blockRegex(/^ *(#{1,6})([^\n:]*?(?: [^\n]*?)?)#* *(?:\n *)*\n/),
plain: (node, output, state) => {
const out = output(node.content, state);
if (state.kind === 'edit' || state.kind === 'notification' || node.level > 2) {
return `${'#'.repeat(node.level)} ${out}\n\n`;
}
return `${out}\n${(node.level === 1 ? '=' : '-').repeat(out.length)}\n\n`;
},
},
hr: {
...defaultRules.hr,
plain: () => '---\n\n',
},
codeBlock: {
...defaultRules.codeBlock,
plain: (node) => `\`\`\`${node.lang || ''}\n${node.content}\n\`\`\`\n`,
html: (node) => htmlTag('pre', htmlTag('code', sanitizeText(node.content), {
class: node.lang ? `language-${node.lang}` : undefined,
})),
},
fence: {
...defaultRules.fence,
match: blockRegex(/^ *(`{3,}|~{3,}) *(?:(\S+) *)?\n([\s\S]+?)\n?\1 *(?:\n *)*\n/),
},
blockQuote: {
...defaultRules.blockQuote,
plain: (node, output, state) => `> ${output(node.content, state).trim().replace(/\n/g, '\n> ')}\n\n`,
},
list: {
...defaultRules.list,
plain: (node, output, state) => {
const oldList = state._list;
state._list = true;
let items = node.items.map((item, i) => {
const prefix = node.ordered ? `${node.start + i}. ` : '* ';
return prefix + output(item, state).replace(/\n/g, `\n${' '.repeat(prefix.length)}`);
}).join('\n');
state._list = oldList;
if (!state._list) {
items += '\n\n';
}
return items;
},
},
def: undefined,
table: {
...defaultRules.table,
plain: (node, output, state) => {
const header = node.header.map((content) => output(content, state));
const colWidth = node.align.map((align) => {
switch (align) {
case 'left':
case 'right':
return 2;
case 'center':
return 3;
default:
return 1;
}
});
header.forEach((s, i) => {
if (s.length > colWidth[i])colWidth[i] = s.length;
});
const cells = node.cells.map((row) => row.map((content, i) => {
const s = output(content, state);
if (colWidth[i] === undefined || s.length > colWidth[i]) {
colWidth[i] = s.length;
}
return s;
}));
function pad(s, i) {
switch (node.align[i]) {
case 'right':
return s.padStart(colWidth[i]);
case 'center':
return s
.padStart(s.length + Math.floor((colWidth[i] - s.length) / 2))
.padEnd(colWidth[i]);
default:
return s.padEnd(colWidth[i]);
}
}
const line = colWidth.map((len, i) => {
switch (node.align[i]) {
case 'left':
return `:${'-'.repeat(len - 1)}`;
case 'center':
return `:${'-'.repeat(len - 2)}:`;
case 'right':
return `${'-'.repeat(len - 1)}:`;
default:
return '-'.repeat(len);
}
});
const table = [
header.map(pad),
line,
...cells.map((row) => row.map(pad))];
return table.map((row) => `| ${row.join(' | ')} |\n`).join('');
},
},
displayMath: {
order: defaultRules.table.order + 0.1,
match: blockRegex(/^ *\$\$ *\n?([\s\S]+?)\n?\$\$ *(?:\n *)*\n/),
parse: (capture) => ({ content: capture[1] }),
plain: (node) => (node.content.includes('\n')
? `$$\n${node.content}\n$$\n`
: `$$${node.content}$$\n`),
html: (node) => mathHtml('div', node),
},
shrug: {
order: defaultRules.escape.order - 0.1,
match: inlineRegex(/^¯\\_\(ツ\)_\/¯/),
parse: (capture) => ({ type: 'text', content: capture[0] }),
},
tableSeparator: {
...defaultRules.tableSeparator,
plain: () => ' | ',
},
link: {
...defaultRules.link,
plain: (node, output, state) => {
const out = output(node.content, state);
const target = sanitizeUrl(node.target) || '';
if (out !== target || node.title) {
return `[${out}](${target}${node.title ? ` "${node.title}"` : ''})`;
}
return out;
},
html: (node, output, state) => {
const out = output(node.content, state);
const target = sanitizeUrl(node.target) || '';
if (out !== target || node.title) {
return htmlTag('a', out, {
href: target,
title: node.title,
});
}
return target;
},
},
image: {
...defaultRules.image,
plain: (node) => `![${node.alt}](${sanitizeUrl(node.target) || ''}${node.title ? ` "${node.title}"` : ''})`,
html: (node) => htmlTag('img', '', {
src: sanitizeUrl(node.target) || '',
alt: node.alt,
title: node.title,
}, false),
},
reflink: undefined,
refimage: undefined,
em: {
...defaultRules.em,
plain: (node, output, state) => `_${output(node.content, state)}_`,
@@ -289,227 +50,40 @@ const markdownRules = {
...defaultRules.del,
plain: (node, output, state) => `~~${output(node.content, state)}~~`,
},
inlineCode: {
...defaultRules.inlineCode,
match: inlineRegex(/^(`+)([^\n]*?[^`\n])\1(?!`)/),
plain: (node) => `\`${node.content}\``,
},
spoiler: {
order: defaultRules.inlineCode.order + 0.1,
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, output, state) => {
const warning = `spoiler${node.reason ? `: ${node.reason}` : ''}`;
switch (state.kind) {
case 'edit':
return `||${output(node.content, state)}||${node.reason ? `(${node.reason})` : ''}`;
case 'notification':
return `<${warning}>`;
default:
return `[${warning}](${output(node.content, state)})`;
}
},
html: (node, output, state) => htmlTag(
'span',
output(node.content, state),
{ 'data-mx-spoiler': node.reason || null },
),
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.2,
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,
},
};
function mapElement(el) {
switch (el.tagName) {
case 'MX-REPLY':
return [];
const parser = parserFor(rules);
case 'P':
return [{ type: 'paragraph', content: mapChildren(el) }];
case 'BR':
return [{ type: 'br' }];
const plainOutput = outputFor(rules, 'plain');
const htmlOutput = outputFor(rules, 'html');
case 'H1':
case 'H2':
case 'H3':
case 'H4':
case 'H5':
case 'H6':
return [{ type: 'heading', level: Number(el.tagName[1]), content: mapChildren(el) }];
case 'HR':
return [{ type: 'hr' }];
case 'PRE': {
let lang;
if (el.firstChild) {
Array.from(el.firstChild.classList).some((c) => {
const langPrefix = 'language-';
if (c.startsWith(langPrefix)) {
lang = c.slice(langPrefix.length);
return true;
}
return false;
});
}
return [{ type: 'codeBlock', lang, content: el.innerText }];
}
case 'BLOCKQUOTE':
return [{ type: 'blockQuote', content: mapChildren(el) }];
case 'UL':
return [{ type: 'list', items: Array.from(el.childNodes).map(mapNode) }];
case 'OL':
return [{
type: 'list',
ordered: true,
start: Number(el.getAttribute('start')),
items: Array.from(el.childNodes).map(mapNode),
}];
case 'TABLE': {
const headerEl = Array.from(el.querySelector('thead > tr').childNodes);
const align = headerEl.map((childE) => childE.style['text-align']);
return [{
type: 'table',
header: headerEl.map(mapChildren),
align,
cells: Array.from(el.querySelectorAll('tbody > tr')).map((rowEl) => Array.from(rowEl.childNodes).map((childEl, i) => {
if (align[i] === undefined) align[i] = childEl.style['text-align'];
return mapChildren(childEl);
})),
}];
}
case 'A': {
const href = el.getAttribute('href');
const id = parseIdUri(href);
if (id) return [{ type: 'mention', content: el.innerText, id }];
return [{
type: 'link',
target: el.getAttribute('href'),
title: el.getAttribute('title'),
content: mapChildren(el),
}];
}
case 'IMG': {
const src = el.getAttribute('src');
let title = el.getAttribute('title');
if (el.hasAttribute('data-mx-emoticon')) {
if (title.length > 2 && title.startsWith(':') && title.endsWith(':')) {
title = title.slice(1, -1);
}
return [{
type: 'emoji',
content: title,
emoji: {
mxc: src,
shortcode: title,
},
}];
}
return [{
type: 'image',
alt: el.getAttribute('alt'),
target: src,
title,
}];
}
case 'EM':
case 'I':
return [{ type: 'em', content: mapChildren(el) }];
case 'STRONG':
case 'B':
return [{ type: 'strong', content: mapChildren(el) }];
case 'U':
return [{ type: 'u', content: mapChildren(el) }];
case 'DEL':
case 'STRIKE':
return [{ type: 'del', content: mapChildren(el) }];
case 'CODE':
return [{ type: 'inlineCode', content: el.innerText }];
case 'DIV':
if (el.hasAttribute('data-mx-maths')) {
return [{ type: 'displayMath', content: el.getAttribute('data-mx-maths') }];
}
return mapChildren(el);
case 'SPAN':
if (el.hasAttribute('data-mx-spoiler')) {
return [{ type: 'spoiler', reason: el.getAttribute('data-mx-spoiler'), content: mapChildren(el) }];
}
if (el.hasAttribute('data-mx-maths')) {
return [{ type: 'inlineMath', content: el.getAttribute('data-mx-maths') }];
}
return mapChildren(el);
default:
return mapChildren(el);
}
}
function mapNode(n) {
switch (n.nodeType) {
case Node.TEXT_NODE:
return [{ type: 'text', content: n.textContent }];
case Node.ELEMENT_NODE:
return mapElement(n);
default:
return [];
}
}
function mapChildren(n) {
return Array.from(n.childNodes).reduce((ast, childN) => {
ast.push(...mapNode(childN));
return ast;
}, []);
}
function render(content, state, plainOut, htmlOut) {
let c = content;
if (content.length === 1 && content[0].type === 'paragraph') {
c = c[0].content;
}
const plainStr = plainOut(c, state).trim();
if (state.onlyPlain) return { plain: plainStr };
const htmlStr = htmlOut(c, state);
const plainHtml = htmlStr.replace(/<br>/g, '\n').replace(/<\/p><p>/g, '\n\n').replace(/<\/?p>/g, '');
const onlyPlain = sanitizeText(plainStr) === plainHtml;
return {
onlyPlain,
plain: plainStr,
html: htmlStr,
};
}
const plainParser = parserFor(plainRules);
const plainPlainOut = outputFor(plainRules, 'plain');
const plainHtmlOut = outputFor(plainRules, 'html');
const mdParser = parserFor(markdownRules);
const mdPlainOut = outputFor(markdownRules, 'plain');
const mdHtmlOut = outputFor(markdownRules, 'html');
export function plain(source, state) {
return render(plainParser(source, state), state, plainPlainOut, plainHtmlOut);
}
export function markdown(source, state) {
return render(mdParser(source, state), state, mdPlainOut, mdHtmlOut);
}
export function html(source, state) {
const el = document.createElement('template');
el.innerHTML = source;
return render(mapChildren(el.content), state, mdPlainOut, mdHtmlOut);
}
export {
parser, plainOutput, htmlOutput,
};
-10
View File
@@ -79,16 +79,6 @@ export function parseReply(rawBody) {
};
}
export function trimHTMLReply(html) {
if (!html) return html;
const suffix = '</mx-reply>';
const i = html.indexOf(suffix);
if (i < 0) {
return html;
}
return html.slice(i + suffix.length);
}
export function hasDMWith(userId) {
const mx = initMatrix.matrixClient;
const directIds = [...initMatrix.roomList.directs];
-15
View File
@@ -1,15 +0,0 @@
{
"compilerOptions": {
"sourceMap": true,
"jsx": "react",
"target": "ES6",
"allowJs": true,
"strict": true,
"esModuleInterop": true,
"moduleResolution": "Node",
"outDir": "dist",
"skipLibCheck": true
},
"exclude": ["node_modules", "dist"],
"include": ["src"]
}
-46
View File
@@ -1,46 +0,0 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { wasm } from '@rollup/plugin-wasm';
import { viteStaticCopy } from 'vite-plugin-static-copy';
import { vanillaExtractPlugin } from "@vanilla-extract/vite-plugin";
const copyFiles = {
targets: [
{
src: 'node_modules/@matrix-org/olm/olm.wasm',
dest: '',
},
{
src: '_redirects',
dest: '',
},
{
src: 'config.json',
dest: '',
},
{
src: 'public/res/android',
dest: 'public/',
}
],
}
export default defineConfig({
appType: 'spa',
publicDir: false,
server: {
port: 8080,
host: true,
},
plugins: [
viteStaticCopy(copyFiles),
vanillaExtractPlugin(),
wasm(),
react(),
],
build: {
outDir: 'dist',
sourcemap: true,
copyPublicDir: false,
},
});
+66
View File
@@ -0,0 +1,66 @@
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const webpack = require('webpack');
module.exports = {
entry: {
polyfill: 'babel-polyfill',
main: './src/index.jsx'
},
resolve: {
extensions: ['.js', '.jsx'],
fallback: {
'crypto': require.resolve('crypto-browserify'),
'path': require.resolve('path-browserify'),
'fs': require.resolve('browserify-fs'),
'stream': require.resolve('stream-browserify'),
'util': require.resolve('util/'),
'assert': require.resolve('assert/'),
'url': require.resolve('url/'),
'buffer': require.resolve('buffer'),
}
},
node: {
global: true,
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
},
{
test: /\.html$/,
use: ['html-loader'],
},
{
test: /\.(png|jpe?g|gif|otf|ttf|woff|woff2|ogg)$/,
type: 'asset/resource',
},
{
test: /\.svg$/,
type: 'asset/inline',
}
],
},
plugins: [
new HtmlWebpackPlugin({ template: './public/index.html' }),
new CopyPlugin({
patterns: [
{ from: 'node_modules/@matrix-org/olm/olm.wasm' },
{ from: '_redirects' },
{ from: 'config.json' },
{ from: 'public/res/android'}
],
}),
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
}),
],
};
+27
View File
@@ -0,0 +1,27 @@
const path = require('path');
const common = require('./webpack.common');
const { merge } = require('webpack-merge');
module.exports = merge(common, {
mode: 'development',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js',
publicPath: '/',
},
devServer: {
historyApiFallback: true,
},
module: {
rules: [
{
test: /\.s?css$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
],
},
],
},
});
+39
View File
@@ -0,0 +1,39 @@
const path = require('path');
const common = require('./webpack.common');
const { merge } = require('webpack-merge');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = merge(common, {
mode: 'production',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].bundle.js',
},
optimization: {
minimize: true,
minimizer: [
'...',
new CssMinimizerPlugin(),
],
},
module: {
rules: [
{
test: /\.s?css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
],
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].bundle.css',
}),
],
});