Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96c650d394 | ||
|
|
478957803d | ||
|
|
0181cb26d2 | ||
|
|
2ddb3595c7 | ||
|
|
76e49d1bd0 | ||
|
|
91f1ee748e | ||
|
|
9bddf64510 | ||
|
|
2200ae143e | ||
|
|
80d9a2ca7d | ||
|
|
cbd1bf35c6 | ||
|
|
c1be57b205 | ||
|
|
4848bef0dd | ||
|
|
a8f374dd43 | ||
|
|
d43e41e1ba | ||
|
|
437ac4c59b | ||
|
|
de218409ab | ||
|
|
060ed859d4 | ||
|
|
0783c43169 | ||
|
|
b5a317e021 | ||
|
|
15c1f6dadf | ||
|
|
efda9991f2 | ||
|
|
9fb651a04e | ||
|
|
55c652a02a | ||
|
|
2be706fb3f | ||
|
|
3e2cc8bfae | ||
|
|
a6c339e13a | ||
|
|
b0174f3acc | ||
|
|
a343d9999e | ||
|
|
0a2cca6e40 | ||
|
|
bca00f46a9 | ||
|
|
5848c02d50 | ||
|
|
29ddcfa1f9 | ||
|
|
831bb83f4e | ||
|
|
b8a8babc88 | ||
|
|
4a35aa7272 | ||
|
|
2ded7d9b1f | ||
|
|
19f674cf5f | ||
|
|
790bf5eac3 | ||
|
|
e1adc6a3bc | ||
|
|
bcedab5113 |
No files matched your search
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:base",
|
||||
":dependencyDashboardApproval"
|
||||
],
|
||||
"labels": [ "Dependencies" ],
|
||||
"packageRules": [
|
||||
{
|
||||
"matchUpdateTypes": [ "lockFileMaintenance" ]
|
||||
}
|
||||
],
|
||||
"lockFileMaintenance": { "enabled": true },
|
||||
"dependencyDashboard": true
|
||||
}
|
||||
@@ -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
|
||||
@@ -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. ⚠️
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
+1
-1
@@ -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/19.2.0/index.html)
|
||||
- [Matrix JavaScript SDK documentation](https://matrix-org.github.io/matrix-js-sdk/index.html)
|
||||
Generated
+574
-740
File diff suppressed because it is too large.
Load diff
+15
-15
@@ -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",
|
||||
@@ -30,9 +30,9 @@
|
||||
"formik": "2.2.9",
|
||||
"html-react-parser": "3.0.4",
|
||||
"katex": "0.16.2",
|
||||
"linkify-html": "4.0.0-beta.5",
|
||||
"linkifyjs": "4.0.0-beta.5",
|
||||
"matrix-js-sdk": "19.4.0",
|
||||
"linkify-html": "4.0.0",
|
||||
"linkifyjs": "4.0.0",
|
||||
"matrix-js-sdk": "19.5.0",
|
||||
"prop-types": "15.8.1",
|
||||
"react": "17.0.2",
|
||||
"react-autosize-textarea": "7.1.0",
|
||||
@@ -42,13 +42,13 @@
|
||||
"react-dom": "17.0.2",
|
||||
"react-google-recaptcha": "2.1.0",
|
||||
"react-modal": "3.15.1",
|
||||
"sanitize-html": "2.7.1",
|
||||
"sanitize-html": "2.7.2",
|
||||
"tippy.js": "6.3.7",
|
||||
"twemoji": "14.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "7.18.13",
|
||||
"@babel/preset-env": "7.18.10",
|
||||
"@babel/core": "7.19.1",
|
||||
"@babel/preset-env": "7.19.1",
|
||||
"@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,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';
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
.katex-display {
|
||||
margin: 0 !important;
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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(' ')}`}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
@@ -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,5 +1,5 @@
|
||||
const cons = {
|
||||
version: '2.1.3',
|
||||
version: '2.2.0',
|
||||
secretKey: {
|
||||
ACCESS_TOKEN: 'cinny_access_token',
|
||||
DEVICE_ID: 'cinny_device_id',
|
||||
|
||||
@@ -375,6 +375,7 @@ class Navigation extends EventEmitter {
|
||||
action.userId,
|
||||
action.eventId,
|
||||
action.body,
|
||||
action.formattedBody,
|
||||
);
|
||||
},
|
||||
[cons.actions.navigation.OPEN_SEARCH]: () => {
|
||||
|
||||
@@ -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
@@ -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.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);
|
||||
}
|
||||
@@ -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];
|
||||
|
||||
@@ -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';
|
||||
|
||||
Reference in new issue
Block a user