Compare commits

...
32 Commits
Author SHA1 Message Date
Krishan 80d9a2ca7d Release v2.2.0 2022-09-17 19:04:13 +05:30
ginnyTheCat cbd1bf35c6 Only escape when editing (#852)
* Only escape when editing

* Base edit change detection on rendered content
2022-09-17 16:55:26 +05:30
Ajay Bura c1be57b205 Add clear cache btn in loading screen 2022-09-17 15:48:45 +05:30
morguldir 4848bef0dd Add Clear cache and reload button (#793)
Inspired by: https://github.com/matrix-org/matrix-react-sdk/blob/3c5c2bef6dbac51ce6e1864056523815ca4c38d9/src/components/views/elements/ErrorBoundary.tsx#L61-L68

Signed-off-by: morguldir <morguldir@protonmail.com>

Signed-off-by: morguldir <morguldir@protonmail.com>
2022-09-17 13:21:22 +05:30
ginnyTheCat a8f374dd43 Parsing HTML to Markdown AST (#847)
* Force mentions to have a space after the #

* Use types for rendering

* Parse HTML

* Add code block support

* Add table support

* Allow starting heading without a space

* Escape relevant plaintext areas

* Resolve many crashes

* Use better matrix id regex

* Don't match . after id

* Don't parse mentions as links

* Add emote support

* Only emit HTML link if necessary

* Implement review changes
2022-09-16 21:21:53 +05:30
renovate[bot] d43e41e1ba Lock file maintenance (#846)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-09-14 19:03:59 +05:30
dependabot[bot] 437ac4c59b Bump css-minimizer-webpack-plugin from 4.0.0 to 4.1.0 (#843)
Bumps [css-minimizer-webpack-plugin](https://github.com/webpack-contrib/css-minimizer-webpack-plugin) from 4.0.0 to 4.1.0.
- [Release notes](https://github.com/webpack-contrib/css-minimizer-webpack-plugin/releases)
- [Changelog](https://github.com/webpack-contrib/css-minimizer-webpack-plugin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/webpack-contrib/css-minimizer-webpack-plugin/compare/v4.0.0...v4.1.0)

---
updated-dependencies:
- dependency-name: css-minimizer-webpack-plugin
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-14 16:53:47 +05:30
renovate[bot] de218409ab Update dependency matrix-js-sdk to v19.5.0 (#845)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-09-14 16:51:02 +05:30
dependabot[bot] 060ed859d4 Bump blurhash from 1.1.5 to 2.0.0 (#842)
Bumps [blurhash](https://github.com/woltapp/blurhash) from 1.1.5 to 2.0.0.
- [Release notes](https://github.com/woltapp/blurhash/releases)
- [Commits](https://github.com/woltapp/blurhash/commits)

---
updated-dependencies:
- dependency-name: blurhash
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-14 16:48:42 +05:30
dependabot[bot] 0783c43169 Bump webpack-dev-server from 4.10.1 to 4.11.0 (#841)
Bumps [webpack-dev-server](https://github.com/webpack/webpack-dev-server) from 4.10.1 to 4.11.0.
- [Release notes](https://github.com/webpack/webpack-dev-server/releases)
- [Changelog](https://github.com/webpack/webpack-dev-server/blob/master/CHANGELOG.md)
- [Commits](https://github.com/webpack/webpack-dev-server/compare/v4.10.1...v4.11.0)

---
updated-dependencies:
- dependency-name: webpack-dev-server
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-14 16:46:11 +05:30
dependabot[bot] b5a317e021 Bump eslint from 8.23.0 to 8.23.1 (#840)
Bumps [eslint](https://github.com/eslint/eslint) from 8.23.0 to 8.23.1.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.23.0...v8.23.1)

---
updated-dependencies:
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-09-14 16:44:47 +05:30
ginnyTheCat 15c1f6dadf Allow rendering messages as plaintext (#805)
* Parse room input from user id and emoji

* Add more plain outputs

* Add reply support

* Always include formatted reply

* Add room mention parser

* Allow single linebreak after codeblock

* Remove margin from math display blocks

* Escape shrug

* Rewrite HTML tag function

* Normalize def keys

* Fix embedding replies into replies

* Don't add margin to file name

* Collapse spaces in HTML message body

* Don't crash with no plaintext rendering

* Add blockquote support

* Remove ref support

* Fix image html rendering

* Remove debug output

* Remove duplicate default option value

* Add table plain rendering support

* Correctly handle paragraph padding when mixed with block content

* Simplify links if possible

* Make blockquote plain rendering better

* Don't error when emojis are matching but not found

* Allow plain only messages with newlines

* Set user id as user mention fallback

* Fix mixed up variable name

* Replace replaceAll with replace
2022-09-14 14:30:06 +05:30
dependabot[bot]andAjay Bura efda9991f2 Bump sass from 1.54.5 to 1.54.9 (#837)
Bumps [sass](https://github.com/sass/dart-sass) from 1.54.5 to 1.54.9.
- [Release notes](https://github.com/sass/dart-sass/releases)
- [Changelog](https://github.com/sass/dart-sass/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sass/dart-sass/compare/1.54.5...1.54.9)

---
updated-dependencies:
- dependency-name: sass
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ajay Bura <32841439+ajbura@users.noreply.github.com>
2022-09-11 18:59:31 +05:30
dependabot[bot]andAjay Bura 9fb651a04e Bump @babel/core from 7.18.13 to 7.19.0 (#824)
Bumps [@babel/core](https://github.com/babel/babel/tree/HEAD/packages/babel-core) from 7.18.13 to 7.19.0.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.19.0/packages/babel-core)

---
updated-dependencies:
- dependency-name: "@babel/core"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ajay Bura <32841439+ajbura@users.noreply.github.com>
2022-09-11 18:59:16 +05:30
dependabot[bot]andAjay Bura 55c652a02a Bump webpack-merge from 5.7.3 to 5.8.0 (#822)
Bumps [webpack-merge](https://github.com/survivejs/webpack-merge) from 5.7.3 to 5.8.0.
- [Release notes](https://github.com/survivejs/webpack-merge/releases)
- [Changelog](https://github.com/survivejs/webpack-merge/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/survivejs/webpack-merge/compare/v5.7.3...v5.8.0)

---
updated-dependencies:
- dependency-name: webpack-merge
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ajay Bura <32841439+ajbura@users.noreply.github.com>
2022-09-11 18:58:33 +05:30
dependabot[bot]andAjay Bura 2be706fb3f Bump eslint-plugin-react from 7.31.1 to 7.31.8 (#838)
Bumps [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) from 7.31.1 to 7.31.8.
- [Release notes](https://github.com/jsx-eslint/eslint-plugin-react/releases)
- [Changelog](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jsx-eslint/eslint-plugin-react/compare/v7.31.1...v7.31.8)

---
updated-dependencies:
- dependency-name: eslint-plugin-react
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ajay Bura <32841439+ajbura@users.noreply.github.com>
2022-09-11 18:57:15 +05:30
dependabot[bot]andAjay Bura 3e2cc8bfae Bump @babel/preset-env from 7.18.10 to 7.19.0 (#825)
Bumps [@babel/preset-env](https://github.com/babel/babel/tree/HEAD/packages/babel-preset-env) from 7.18.10 to 7.19.0.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.19.0/packages/babel-preset-env)

---
updated-dependencies:
- dependency-name: "@babel/preset-env"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ajay Bura <32841439+ajbura@users.noreply.github.com>
2022-09-11 18:54:24 +05:30
dependabot[bot]andAjay Bura a6c339e13a Bump html-webpack-plugin from 5.3.1 to 5.5.0 (#829)
Bumps [html-webpack-plugin](https://github.com/jantimon/html-webpack-plugin) from 5.3.1 to 5.5.0.
- [Release notes](https://github.com/jantimon/html-webpack-plugin/releases)
- [Changelog](https://github.com/jantimon/html-webpack-plugin/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jantimon/html-webpack-plugin/compare/v5.3.1...v5.5.0)

---
updated-dependencies:
- dependency-name: html-webpack-plugin
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ajay Bura <32841439+ajbura@users.noreply.github.com>
2022-09-11 18:53:03 +05:30
ginnyTheCat b0174f3acc Delete notifications after messages have been read or deleted (#830)
* Delete read notifications

* Delete notifications for deleted messages

* Correctly remove notification
2022-09-11 18:51:59 +05:30
ginnyTheCat a343d9999e Handle messages with invalid body (#833) 2022-09-11 18:51:05 +05:30
ginnyTheCat 0a2cca6e40 Change UI label (#832) 2022-09-11 16:44:39 +05:30
Ajay Bura bca00f46a9 Add plain text command 2022-09-11 12:18:32 +05:30
Ajay Bura 5848c02d50 Remove markdown icon from input 2022-09-11 09:19:22 +05:30
Ajay Bura 29ddcfa1f9 Update command strings 2022-09-11 08:27:59 +05:30
Krishan 831bb83f4e Update and simplify actions (#831)
* Replace action with one we use already

* Simplify PR actions

* fix name
2022-09-07 13:46:44 +05:30
Ajay Bura b8a8babc88 Fix emojiboard icon background 2022-09-07 13:24:26 +05:30
Ajay Bura 4a35aa7272 Fix crash in manage device 2022-09-07 13:14:15 +05:30
Ajay Bura 2ded7d9b1f Fix crash with unknown mime type 2022-09-07 08:40:10 +05:30
Ajay Bura 19f674cf5f Fix unwanted changes 2022-09-06 14:25:13 +05:30
Ajay Bura 790bf5eac3 Fix wrong notification count 2022-09-06 14:22:56 +05:30
renovate[bot]andKrishan e1adc6a3bc Configure Renovate (#819)
* Add renovate.json

* Add renovate config

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Krishan <33421343+kfiven@users.noreply.github.com>
2022-09-05 19:43:11 +05:30
Krishan bcedab5113 Add lockfile changes action (#818) 2022-09-05 19:26:28 +05:30
34 changed files with 1320 additions and 1040 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base"
],
"labels": [ "Dependencies" ],
"packageRules": [
{
"matchUpdateTypes": [ "lockFileMaintenance" ]
}
],
"lockFileMaintenance": { "enabled": true },
"dependencyDashboard": true,
"dependencyDashboardApproval": true
}
+12 -12
View File
@@ -6,6 +6,7 @@ on:
jobs:
build-pull-request:
name: 'Build pull request'
runs-on: ubuntu-latest
env:
PR_NUMBER: ${{github.event.number}}
@@ -16,23 +17,22 @@ jobs:
uses: actions/setup-node@v3.4.1
with:
node-version: 17.9.0
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build app
run: npm ci && npm run build
run: npm run build
- name: Upload artifact
uses: actions/upload-artifact@v3.1.0
with:
name: previewbuild
name: preview
path: dist
retention-days: 1
- name: Get PR info
uses: actions/github-script@v6.2.0
with:
script: |
var fs = require('fs');
fs.writeFileSync('${{github.workspace}}/pr.json', JSON.stringify(context.payload.pull_request));
- name: Upload PR Info
- name: Save pr number
run: echo ${PR_NUMBER} > ./pr.txt
- name: Upload pr number
uses: actions/upload-artifact@v3.1.0
with:
name: pr.json
path: pr.json
retention-days: 1
name: pr
path: ./pr.txt
retention-days: 1
+24 -52
View File
@@ -1,68 +1,40 @@
name: Upload Preview Build to Netlify
name: Deploy PR to Netlify
on:
workflow_run:
workflows: ["Build pull request"]
types:
- completed
types: [completed]
jobs:
get-build-and-deploy:
deploy-pull-request:
name: 'Deploy pull request'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
runs-on: ubuntu-latest
if: >
${{ github.event.workflow_run.conclusion == 'success' }}
if: ${{ github.event.workflow_run.conclusion == 'success' }}
steps:
# There's a 'download artifact' action but it hasn't been updated for the
# workflow_run action (https://github.com/actions/download-artifact/issues/60)
# so instead we get this mess:
- name: Download pr number
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 "::set-output name=id::$(<pr.txt)"
- name: Download artifact
uses: actions/github-script@v6.2.0
uses: dawidd6/action-download-artifact@7847792dd435a50521b8e3bd3576dae7459d1fa8
with:
script: |
var artifacts = await github.rest.actions.listWorkflowRunArtifacts({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: ${{github.event.workflow_run.id }},
});
var matchArtifact = artifacts.data.artifacts.filter((artifact) => {
return artifact.name == "previewbuild"
})[0];
var download = await github.rest.actions.downloadArtifact({
owner: context.repo.owner,
repo: context.repo.repo,
artifact_id: matchArtifact.id,
archive_format: 'zip',
});
var fs = require('fs');
fs.writeFileSync('${{github.workspace}}/previewbuild.zip', Buffer.from(download.data));
var prInfoArtifact = artifacts.data.artifacts.filter((artifact) => {
return artifact.name == "pr.json"
})[0];
var download = await github.rest.actions.downloadArtifact({
owner: context.repo.owner,
repo: context.repo.repo,
artifact_id: prInfoArtifact.id,
archive_format: 'zip',
});
var fs = require('fs');
fs.writeFileSync('${{github.workspace}}/pr.json.zip', Buffer.from(download.data));
- name: Extract Artifacts
run: unzip -d dist previewbuild.zip && rm previewbuild.zip && unzip pr.json.zip && rm pr.json.zip
- name: Read PR Info
id: readctx
uses: actions/github-script@v6.2.0
with:
script: |
var fs = require('fs');
var pr = JSON.parse(fs.readFileSync('${{github.workspace}}/pr.json'));
console.log(`::set-output name=prnumber::${pr.number}`);
workflow: ${{ github.event.workflow.id }}
run_id: ${{ github.event.workflow_run.id }}
name: preview
path: dist
- name: Deploy to Netlify
id: netlify
uses: nwtgck/actions-netlify@b7c1504e00c6b8a249d1848cc1b522a4865eed99
with:
publish-dir: dist
deploy-message: "Deploy from GitHub Actions"
deploy-message: "Deploy PR ${{ steps.pr.outputs.id }}"
alias: ${{ steps.pr.outputs.id }}
# These don't work because we're in workflow_run
enable-pull-request-comment: false
enable-commit-comment: false
@@ -75,7 +47,7 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
pull-request-number: ${{ steps.readctx.outputs.prnumber }}
pull-request-number: ${{ steps.pr.outputs.id }}
description-message: |
Preview: ${{ steps.netlify.outputs.deploy-url }}
⚠️ Exercise caution. Use test accounts. ⚠️
⚠️ Exercise caution. Use test accounts. ⚠️
-2
View File
@@ -9,8 +9,6 @@ on:
jobs:
docker-build:
runs-on: ubuntu-latest
env:
PR_NUMBER: ${{github.event.number}}
steps:
- name: Checkout repository
uses: actions/checkout@v3.0.2
+26
View File
@@ -0,0 +1,26 @@
name: NPM Lockfile Changes
on:
pull_request:
paths:
- 'package-lock.json'
jobs:
lockfile_changes:
runs-on: ubuntu-latest
# Permission overwrite is required for Dependabot PRs, see "Common issues" below.
permissions:
contents: read
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v3.0.2
- name: NPM Lockfile Changes
uses: codepunkt/npm-lockfile-changes@b40543471c36394409466fdb277a73a0856d7891
with:
token: ${{ secrets.GITHUB_TOKEN }}
# Optional inputs, can be deleted safely if you are happy with default values.
collapsibleThreshold: 25
failOnDowngrade: false
path: package-lock.json
updateComment: true
+17 -9
View File
@@ -7,10 +7,8 @@ on:
jobs:
deploy-to-netlify:
name: 'Deploy'
name: 'Deploy to Netlify'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v3.0.2
@@ -18,12 +16,22 @@ jobs:
uses: actions/setup-node@v3.4.1
with:
node-version: 17.9.0
- name: Build and deploy to Netlify
uses: jsmrcaga/action-netlify-deploy@53de32e559b0b3833615b9788c7a090cd2fddb03
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build app
run: npm run build
- name: Deploy to Netlify
uses: nwtgck/actions-netlify@b7c1504e00c6b8a249d1848cc1b522a4865eed99
with:
install_command: "npm ci"
publish-dir: dist
deploy-message: "Dev deploy ${{ github.sha }}"
enable-commit-comment: false
github-token: ${{ secrets.GITHUB_TOKEN }}
production-deploy: true
github-deployment-environment: nightly
github-deployment-description: 'Nightly deployment on each commit to dev branch'
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE2_ID }}
BUILD_DIRECTORY: "dist"
NETLIFY_DEPLOY_MESSAGE: "Dev deploy v${{ github.ref }}"
NETLIFY_DEPLOY_TO_PROD: true
timeout-minutes: 1
+22 -29
View File
@@ -5,8 +5,8 @@ on:
types: [published]
jobs:
create-release-tar:
name: 'Create release tar'
deploy-and-tarball:
name: 'Netlify deploy and tarball'
runs-on: ubuntu-latest
steps:
- name: Checkout repository
@@ -15,10 +15,25 @@ jobs:
uses: actions/setup-node@v3.4.1
with:
node-version: 17.9.0
- name: Build
run: |
npm ci
npm run build
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build app
run: npm run build
- name: Deploy to Netlify
uses: nwtgck/actions-netlify@b7c1504e00c6b8a249d1848cc1b522a4865eed99
with:
publish-dir: dist
deploy-message: "Prod deploy ${{ github.ref_name }}"
enable-commit-comment: false
github-token: ${{ secrets.GITHUB_TOKEN }}
production-deploy: true
github-deployment-environment: stable
github-deployment-description: 'Stable deployment on each release'
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
timeout-minutes: 1
- name: Get version from tag
id: vars
run: echo ::set-output name=tag::${GITHUB_REF#refs/*/}
@@ -41,29 +56,7 @@ jobs:
cinny-${{ steps.vars.outputs.tag }}.tar.gz
cinny-${{ steps.vars.outputs.tag }}.tar.gz.asc
deploy-to-netlify:
name: 'Deploy to Netlify'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v3.0.2
- name: Setup node
uses: actions/setup-node@v3.4.1
with:
node-version: 17.9.0
- name: Build and deploy to Netlify
uses: jsmrcaga/action-netlify-deploy@53de32e559b0b3833615b9788c7a090cd2fddb03
with:
install_command: "npm ci"
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
BUILD_DIRECTORY: "dist"
NETLIFY_DEPLOY_MESSAGE: "Prod deploy v${{ github.ref }}"
NETLIFY_DEPLOY_TO_PROD: true
push-to-dockerhub:
publish-image:
name: Push Docker image to Docker Hub, ghcr
runs-on: ubuntu-latest
permissions:
+478 -644
View File
File diff suppressed because it is too large. Load diff
+12 -12
View File
@@ -1,6 +1,6 @@
{
"name": "cinny",
"version": "2.1.3",
"version": "2.2.0",
"description": "Yet another matrix client",
"main": "index.js",
"engines": {
@@ -21,7 +21,7 @@
"@matrix-org/olm": "3.2.12",
"@tippyjs/react": "4.2.6",
"babel-polyfill": "6.26.0",
"blurhash": "1.1.5",
"blurhash": "2.0.0",
"browser-encrypt-attachment": "0.3.0",
"dateformat": "5.0.3",
"emojibase-data": "7.0.1",
@@ -32,7 +32,7 @@
"katex": "0.16.2",
"linkify-html": "4.0.0-beta.5",
"linkifyjs": "4.0.0-beta.5",
"matrix-js-sdk": "19.4.0",
"matrix-js-sdk": "19.5.0",
"prop-types": "15.8.1",
"react": "17.0.2",
"react-autosize-textarea": "7.1.0",
@@ -47,8 +47,8 @@
"twemoji": "14.0.2"
},
"devDependencies": {
"@babel/core": "7.18.13",
"@babel/preset-env": "7.18.10",
"@babel/core": "7.19.0",
"@babel/preset-env": "7.19.0",
"@babel/preset-react": "7.18.6",
"assert": "2.0.0",
"babel-loader": "8.2.5",
@@ -58,18 +58,18 @@
"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",
"css-minimizer-webpack-plugin": "4.1.0",
"eslint": "8.23.1",
"eslint-config-airbnb": "19.0.4",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-jsx-a11y": "6.6.1",
"eslint-plugin-react": "7.31.1",
"eslint-plugin-react": "7.31.8",
"eslint-plugin-react-hooks": "4.6.0",
"html-loader": "4.1.0",
"html-webpack-plugin": "5.3.1",
"html-webpack-plugin": "5.5.0",
"mini-css-extract-plugin": "2.6.1",
"path-browserify": "1.0.1",
"sass": "1.54.5",
"sass": "1.54.9",
"sass-loader": "13.0.2",
"stream-browserify": "3.0.0",
"style-loader": "3.3.1",
@@ -77,7 +77,7 @@
"util": "0.12.4",
"webpack": "5.74.0",
"webpack-cli": "4.10.0",
"webpack-dev-server": "4.10.1",
"webpack-merge": "5.7.3"
"webpack-dev-server": "4.11.0",
"webpack-merge": "5.8.0"
}
}
+1
View File
@@ -1,5 +1,6 @@
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
@@ -0,0 +1,3 @@
.katex-display {
margin: 0 !important;
}
+19 -13
View File
@@ -8,7 +8,9 @@ import './Message.scss';
import { twemojify } from '../../../util/twemojify';
import initMatrix from '../../../client/initMatrix';
import { getUsername, getUsernameOfRoomMember, parseReply } from '../../../util/matrixUtil';
import {
getUsername, getUsernameOfRoomMember, parseReply, trimHTMLReply,
} from '../../../util/matrixUtil';
import colorMXID from '../../../util/colorMXID';
import { getEventCords } from '../../../util/common';
import { redactEvent, sendReaction } from '../../../client/action/roomTimeline';
@@ -38,6 +40,7 @@ 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 (
@@ -248,7 +251,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>{content}</p>);
content = (<p className="message__body-plain">{content}</p>);
}
return (
@@ -297,12 +300,12 @@ function MessageEdit({ body, onSave, onCancel }) {
if (e.key === 'Enter' && e.shiftKey === false) {
e.preventDefault();
onSave(editInputRef.current.value);
onSave(editInputRef.current.value, body);
}
};
return (
<form className="message__edit" onSubmit={(e) => { e.preventDefault(); onSave(editInputRef.current.value); }}>
<form className="message__edit" onSubmit={(e) => { e.preventDefault(); onSave(editInputRef.current.value, body); }}>
<Input
forwardRef={editInputRef}
onKeyDown={handleKeyDown}
@@ -729,36 +732,37 @@ 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);
}, [body]);
replyTo(senderId, mEvent.getId(), body, customHTML);
}, [body, customHTML]);
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(' ')}>
{
@@ -799,9 +803,11 @@ function Message({
)}
{isEdit && (
<MessageEdit
body={body}
onSave={(newBody) => {
if (newBody !== body) {
body={(customHTML
? html(customHTML, { kind: 'edit', onlyPlain: true }).plain
: plain(body, { kind: 'edit', onlyPlain: true }).plain)}
onSave={(newBody, oldBody) => {
if (newBody !== oldBody) {
initMatrix.roomsInput.sendEditedMessage(roomId, mEvent, newBody);
}
cancelEdit();
+3 -3
View File
@@ -163,7 +163,7 @@
.message__body {
word-break: break-word;
& > .text > * {
& > .text > .message__body-plain {
white-space: pre-wrap;
}
@@ -174,8 +174,8 @@
white-space: initial !important;
}
& p:not(:last-child) {
margin-bottom: var(--sp-normal);
& > .text > p + p {
margin-top: var(--sp-normal);
}
& span[data-mx-pill] {
@@ -38,7 +38,7 @@
@extend .cp-fx__column;
}
&__nav-twemoji {
background: inherit;
background-color: var(--bg-surface);
position: sticky;
bottom: -70%;
z-index: 999;
@@ -21,7 +21,7 @@ import ChevronRightIC from '../../../../public/res/ic/outlined/chevron-right.svg
function DrawerBreadcrumb({ spaceId }) {
const [, forceUpdate] = useState({});
const scrollRef = useRef(null);
const { roomList, notifications } = initMatrix;
const { roomList, notifications, accountData } = initMatrix;
const mx = initMatrix.matrixClient;
const spacePath = navigation.selectedSpacePath;
@@ -49,9 +49,9 @@ function DrawerBreadcrumb({ spaceId }) {
}, [spaceId]);
function getHomeNotiExcept(childId) {
const orphans = roomList.getOrphans();
const childIndex = orphans.indexOf(childId);
if (childId !== -1) orphans.splice(childIndex, 1);
const orphans = roomList.getOrphans()
.filter((id) => (id !== childId))
.filter((id) => !accountData.spaceShortcut.has(id));
let noti = null;
@@ -57,7 +57,7 @@ export function HomeSpaceOptions({ spaceId, afterOptionSelect }) {
iconSrc={HashGlobeIC}
onClick={() => { afterOptionSelect(); openPublicRooms(); }}
>
Join public room
Explore public rooms
</MenuItem>
)}
{ !spaceId && (
@@ -16,7 +16,6 @@ import { confirmDialog } from '../../molecules/confirm-dialog/ConfirmDialog';
import './ProfileEditor.scss';
// TODO Fix bug that prevents 'Save' button from enabling up until second changed.
function ProfileEditor({ userId }) {
const [isEditing, setIsEditing] = useState(false);
const mx = initMatrix.matrixClient;
@@ -96,7 +95,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)}</Text>
<Text variant="h2" primary weight="medium">{twemojify(username) ?? userId}</Text>
<IconButton
src={PencilIC}
size="extra-small"
@@ -111,7 +110,7 @@ function ProfileEditor({ userId }) {
return (
<div className="profile-editor">
<ImageUpload
text={username}
text={username ?? userId}
bgColor={colorMXID(userId)}
imageSrc={avatarSrc}
onUpload={handleAvatarUpload}
+12 -12
View File
@@ -30,7 +30,6 @@ 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';
@@ -44,7 +43,6 @@ 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);
@@ -63,11 +61,9 @@ 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);
};
@@ -147,9 +143,11 @@ function RoomViewInput({
textAreaRef.current.focus();
}
function setUpReply(userId, eventId, body) {
function setUpReply(userId, eventId, body, formattedBody) {
setReplyTo({ userId, eventId, body });
roomsInput.setReplyTo(roomId, { userId, eventId, body });
roomsInput.setReplyTo(roomId, {
userId, eventId, body, formattedBody,
});
focusInput();
}
@@ -185,7 +183,10 @@ function RoomViewInput({
};
}, [roomId]);
const sendBody = async (body, msgType = 'm.text') => {
const sendBody = async (body, options) => {
const opt = options ?? {};
if (!opt.msgType) opt.msgType = 'm.text';
if (typeof opt.autoMarkdown !== 'boolean') opt.autoMarkdown = true;
if (roomsInput.isSending(roomId)) return;
sendIsTyping(false);
@@ -195,7 +196,7 @@ function RoomViewInput({
}
textAreaRef.current.disabled = true;
textAreaRef.current.style.cursor = 'not-allowed';
await roomsInput.sendInput(roomId, msgType);
await roomsInput.sendInput(roomId, opt);
textAreaRef.current.disabled = false;
textAreaRef.current.style.cursor = 'unset';
focusInput();
@@ -213,8 +214,8 @@ function RoomViewInput({
confirmDialog('Invalid Command', `"${cmdName}" is not a valid command.`, 'Alright');
return;
}
if (['me', 'shrug'].includes(cmdName)) {
commands[cmdName].exe(roomId, cmdData, (message, msgType) => sendBody(message, msgType));
if (['me', 'shrug', 'plain'].includes(cmdName)) {
commands[cmdName].exe(roomId, cmdData, sendBody);
return;
}
commands[cmdName].exe(roomId, cmdData);
@@ -230,7 +231,7 @@ function RoomViewInput({
return;
}
if (msgBody === '' && attachment === null) return;
sendBody(msgBody, 'm.text');
sendBody(msgBody);
};
const handleSendSticker = async (data) => {
@@ -379,7 +380,6 @@ function RoomViewInput({
/>
</Text>
</ScrollView>
{isMarkdown && <RawIcon size="extra-small" src={MarkdownIC} />}
</div>
<div ref={rightOptionsRef} className="room-input__option-container">
<IconButton
+15 -6
View File
@@ -38,7 +38,7 @@ const commands = {
exe: (roomId, data, onSuccess) => {
const body = data.trim();
if (body === '') return;
onSuccess(body, 'm.emote');
onSuccess(body, { msgType: 'm.emote' });
},
},
shrug: {
@@ -46,9 +46,18 @@ const commands = {
description: 'Send ¯\\_(ツ)_/¯ as message',
exe: (roomId, data, onSuccess) => onSuccess(
`¯\\_(ツ)_/¯${data.trim() !== '' ? ` ${data}` : ''}`,
'm.text',
{ msgType: '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',
@@ -57,7 +66,7 @@ const commands = {
},
startdm: {
name: 'startdm',
description: 'Start DM with user. Example: /startdm userId1 userId2',
description: 'Start direct message with user. Example: /startdm userId1',
exe: async (roomId, data) => {
const mx = initMatrix.matrixClient;
const rawIds = data.split(' ');
@@ -78,7 +87,7 @@ const commands = {
},
join: {
name: 'join',
description: 'Join room with alias. Example: /join alias1 alias2',
description: 'Join room with address. Example: /join address1 address2',
exe: (roomId, data) => {
const rawIds = data.split(' ');
const roomIds = rawIds.filter((id) => id.match(ROOM_ID_ALIAS_REG));
@@ -159,7 +168,7 @@ const commands = {
},
myroomnick: {
name: 'myroomnick',
description: 'Change my room nick',
description: 'Change nick in current room.',
exe: (roomId, data) => {
const nick = data.trim();
if (nick === '') return;
@@ -168,7 +177,7 @@ const commands = {
},
myroomavatar: {
name: 'myroomavatar',
description: 'Change my room avatar. Example /myroomavatar mxc://xyzabc',
description: 'Change profile picture in current room. Example /myroomavatar mxc://xyzabc',
exe: (roomId, data) => {
if (data.match(MXC_REG)) {
roomActions.setMyRoomAvatar(roomId, data);
+9 -7
View File
@@ -180,13 +180,15 @@ function DeviceManage() {
}
content={(
<>
<Text variant="b3">
Last activity
<span style={{ color: 'var(--tc-surface-normal)' }}>
{dateFormat(new Date(lastTS), ' hh:MM TT, dd/mm/yyyy')}
</span>
{lastIP ? ` at ${lastIP}` : ''}
</Text>
{lastTS && (
<Text variant="b3">
Last activity
<span style={{ color: 'var(--tc-surface-normal)' }}>
{dateFormat(new Date(lastTS), ' hh:MM TT, dd/mm/yyyy')}
</span>
{lastIP ? ` at ${lastIP}` : ''}
</Text>
)}
{isCurrentDevice && (
<Text style={{ marginTop: 'var(--sp-ultra-tight)' }} variant="b3">
{`Session Key: ${initMatrix.matrixClient.getDeviceEd25519Key().match(/.{1,4}/g).join(' ')}`}
+2 -2
View File
@@ -9,7 +9,6 @@ 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';
@@ -239,6 +238,7 @@ 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')) {
logout();
initMatrix.logout();
}
};
+18 -4
View File
@@ -7,18 +7,21 @@ 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');
@@ -74,9 +77,20 @@ function Client() {
if (isLoading) {
return (
<div className="loading-display">
<button className="loading__logout" onClick={logout} type="button">
<Text variant="b3">Logout</Text>
</button>
<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>
<Spinner />
<Text className="loading__message" variant="b2">{loadingMsg}</Text>
+4 -4
View File
@@ -45,12 +45,12 @@
position: absolute;
bottom: var(--sp-normal);
}
.loading__logout {
.loading__menu {
position: absolute;
bottom: var(--sp-extra-tight);
top: var(--sp-extra-tight);
right: var(--sp-extra-tight);
cursor: pointer;
.text {
color: var(--tc-link);
.context-menu__item .text {
margin: 0 !important;
}
}
-16
View File
@@ -1,16 +0,0 @@
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;
+2 -1
View File
@@ -139,12 +139,13 @@ export function openViewSource(event) {
});
}
export function replyTo(userId, eventId, body) {
export function replyTo(userId, eventId, body, formattedBody) {
appDispatcher.dispatch({
type: cons.actions.navigation.CLICK_REPLY_TO,
userId,
eventId,
body,
formattedBody,
});
}
+21 -2
View File
@@ -98,13 +98,32 @@ class InitMatrix extends EventEmitter {
}
listenEvents() {
this.matrixClient.on('Session.logged_out', () => {
this.matrixClient.on('Session.logged_out', async () => {
this.matrixClient.stopClient();
this.matrixClient.clearStores();
await 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();
+41 -4
View File
@@ -10,6 +10,7 @@ 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();
@@ -43,6 +44,8 @@ class Notifications extends EventEmitter {
this.roomList = roomList;
this.roomIdToNoti = new Map();
this.roomIdToPopupNotis = new Map();
this.eventIdToPopupNoti = new Map();
// this._initNoti();
this._listenEvents();
@@ -114,8 +117,7 @@ class Notifications extends EventEmitter {
}
getTotalNoti(roomId) {
const { total, highlight } = this.getNoti(roomId);
if (highlight > total) return highlight;
const { total } = this.getNoti(roomId);
return total;
}
@@ -181,7 +183,7 @@ class Notifications extends EventEmitter {
};
const noti = this.getNoti(roomId);
const addT = total - noti.total;
const addT = (highlight > total ? highlight : total) - noti.total;
const addH = highlight - noti.highlight;
if (addT < 0 || addH < 0) return;
@@ -256,20 +258,51 @@ 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: mEvent.getContent().body,
body: body.plain,
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');
@@ -286,6 +319,8 @@ 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;
@@ -356,6 +391,8 @@ class Notifications extends EventEmitter {
if (readerUserId !== this.matrixClient.getUserId()) return;
this.deleteNoti(room.roomId);
this._deletePopupRoomNotis(room.roomId);
}
});
+77 -166
View File
@@ -6,11 +6,9 @@ import { getBlobSafeMimeType } from '../../util/mimetypes';
import { sanitizeText } from '../../util/sanitize';
import cons from './cons';
import settings from './settings';
import { htmlOutput, parser } from '../../util/markdown';
import { markdown, plain } 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');
@@ -100,91 +98,6 @@ 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();
@@ -274,8 +187,76 @@ class RoomsInput extends EventEmitter {
return this.roomIdToInput.get(roomId)?.isSending || false;
}
async sendInput(roomId, msgType) {
getContent(roomId, options, message, reply, edit) {
const msgType = options?.msgType || 'm.text';
const autoMarkdown = options?.autoMarkdown ?? true;
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);
@@ -285,35 +266,7 @@ class RoomsInput extends EventEmitter {
}
if (this.getMessage(roomId).trim() !== '') {
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);
}
const content = this.getContent(roomId, options, input.message, input.replyTo);
this.matrixClient.sendMessage(roomId, content);
}
@@ -456,55 +409,13 @@ class RoomsInput extends EventEmitter {
}
async sendEditedMessage(roomId, mEvent, editedBody) {
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]]}`,
const content = this.getContent(
roomId,
{ msgType: mEvent.getWireContent().msgtype },
editedBody,
null,
mEvent,
);
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.1.3',
version: '2.2.0',
secretKey: {
ACCESS_TOKEN: 'cinny_access_token',
DEVICE_ID: 'cinny_device_id',
+1
View File
@@ -375,6 +375,7 @@ class Navigation extends EventEmitter {
action.userId,
action.eventId,
action.body,
action.formattedBody,
);
},
[cons.actions.navigation.OPEN_SEARCH]: () => {
+24
View File
@@ -204,3 +204,27 @@ 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];
}
+442 -30
View File
@@ -1,25 +1,83 @@
/* eslint-disable no-use-before-define */
import SimpleMarkdown from '@khanacademy/simple-markdown';
import { idRegex, parseIdUri } from './common';
const {
defaultRules, parserFor, outputFor, anyScopeRegex, blockRegex, inlineRegex, htmlTag, sanitizeText,
defaultRules, parserFor, outputFor, anyScopeRegex, blockRegex, inlineRegex,
sanitizeText, sanitizeUrl,
} = 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 rules = {
...defaultRules,
const emojiRegex = /^:([\w-]+):/;
const plainRules = {
Array: {
...defaultRules.Array,
plain: (arr, output, state) => arr.map((node) => output(node, state)).join(''),
plain: defaultRules.Array.html,
},
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),
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),
},
newline: {
...defaultRules.newline,
@@ -30,10 +88,178 @@ const rules = {
plain: (node, output, state) => `${output(node.content, state)}\n\n`,
html: (node, output, state) => htmlTag('p', 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\`\`\``,
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) => `${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')}\n`,
},
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] }),
},
escape: {
...defaultRules.escape,
plain: (node, output, state) => `\\${output(node.content, state)}`,
},
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)}_`,
@@ -50,40 +276,226 @@ const rules = {
...defaultRules.del,
plain: (node, output, state) => `~~${output(node.content, state)}~~`,
},
inlineCode: {
...defaultRules.inlineCode,
plain: (node) => `\`${node.content}\``,
},
spoiler: {
order: defaultRules.em.order - 0.5,
order: defaultRules.inlineCode.order + 0.1,
match: inlineRegex(/^\|\|([\s\S]+?)\|\|(?:\(([\s\S]+?)\))?/),
parse: (capture, parse, state) => ({
content: parse(capture[1], state),
reason: capture[2],
}),
plain: (node) => `[spoiler${node.reason ? `: ${node.reason}` : ''}](mxc://somewhere)`,
html: (node, output, state) => `<span data-mx-spoiler${node.reason ? `="${sanitizeText(node.reason)}"` : ''}>${output(node.content, state)}</span>`,
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 },
),
},
inlineMath: {
order: defaultRules.del.order + 0.5,
order: defaultRules.del.order + 0.2,
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,
},
};
const parser = parserFor(rules);
function mapElement(el) {
switch (el.tagName) {
case 'MX-REPLY':
return [];
const plainOutput = outputFor(rules, 'plain');
const htmlOutput = outputFor(rules, 'html');
case 'P':
return [{ type: 'paragraph', content: mapChildren(el) }];
case 'BR':
return [{ type: 'br' }];
export {
parser, plainOutput, htmlOutput,
};
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: mapChildren(el) }];
case 'OL':
return [{
type: 'list',
ordered: true,
start: Number(el.getAttribute('start')),
items: mapChildren(el),
}];
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);
}
+10
View File
@@ -79,6 +79,16 @@ 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];
+1
View File
@@ -26,6 +26,7 @@ export const ALLOWED_BLOB_MIMETYPES = [
];
export function getBlobSafeMimeType(mimetype) {
if (typeof mimetype !== 'string') return 'application/octet-stream';
const [type] = mimetype.split(';');
if (!ALLOWED_BLOB_MIMETYPES.includes(type)) {
return 'application/octet-stream';