Compare commits
171 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5844209bee | ||
|
|
ff334c1c3d | ||
|
|
4374a89535 | ||
|
|
31dcad6220 | ||
|
|
a58cffe12b | ||
|
|
de7724dfcf | ||
|
|
4edc4bad02 | ||
|
|
2444a60a3e | ||
|
|
ae88480d0a | ||
|
|
2ed3f877c3 | ||
|
|
09d85d6c31 | ||
|
|
999bb7aca1 | ||
|
|
b84f975f83 | ||
|
|
b12228ee95 | ||
|
|
5460e4922b | ||
|
|
7b4f684a25 | ||
|
|
56b754153a | ||
|
|
f5d68fcc22 | ||
|
|
42e6e6355d | ||
|
|
8e4475bb56 | ||
|
|
d5766b58fe | ||
|
|
b524778039 | ||
|
|
45c2a22340 | ||
|
|
1b01f3e8ba | ||
|
|
2760f4cab9 | ||
|
|
f3e57715a3 | ||
|
|
5cef90fad9 | ||
|
|
0764143d2c | ||
|
|
e0e84f3756 | ||
|
|
69268187c2 | ||
|
|
02437a6a20 | ||
|
|
3c5afaf33a | ||
|
|
396bf50239 | ||
|
|
24d35a5817 | ||
|
|
b8d9c4bdd6 | ||
|
|
35f0e400ad | ||
|
|
00d5553bcb | ||
|
|
a142630ff9 | ||
|
|
492a149c7f | ||
|
|
c110e64341 | ||
|
|
0e51e19cab | ||
|
|
35b0b1ea42 | ||
|
|
cca8b5f2b2 | ||
|
|
48265c4227 | ||
|
|
c38efdfbce | ||
|
|
d8833a310d | ||
|
|
5824d7c716 | ||
|
|
6e191d3c79 | ||
|
|
21164a9b61 | ||
|
|
4923b17ad6 | ||
|
|
c75e903619 | ||
|
|
042cbc4453 | ||
|
|
03cc25eec0 | ||
|
|
f2c31d29a2 | ||
|
|
5482f8e72e | ||
|
|
96df140153 | ||
|
|
4dfce32730 | ||
|
|
388f606ad2 | ||
|
|
09444f9e08 | ||
|
|
c6a8fb1117 | ||
|
|
043012e809 | ||
|
|
5c9ee1a988 | ||
|
|
22b7f6dd7d | ||
|
|
bdba0332e1 | ||
|
|
16be69c104 | ||
|
|
830d05e217 | ||
|
|
7e7bee8f48 | ||
|
|
ac1797344c | ||
|
|
b4ce8a7cab | ||
|
|
e68c56b334 | ||
|
|
cabfdd47b5 | ||
|
|
cfe893f358 | ||
|
|
581211f13e | ||
|
|
8ed78d48fb | ||
|
|
96222de5bc | ||
|
|
681287c46a | ||
|
|
9cb5c70d51 | ||
|
|
c62050445b | ||
|
|
a8f5a6c2f4 | ||
|
|
e54bb2e423 | ||
|
|
5058136737 | ||
|
|
74dc76e22e | ||
|
|
44161c4157 | ||
|
|
e8d04c0603 | ||
|
|
96415a8d2a | ||
|
|
2157f9a322 | ||
|
|
b387370aaf | ||
|
|
3110505b21 | ||
|
|
da536c8c3f | ||
|
|
98a378ad8a | ||
|
|
ab73225f00 | ||
|
|
cc4c222975 | ||
|
|
a32c8bf228 | ||
|
|
e6d6b0349e | ||
|
|
e2228a18c1 | ||
|
|
e046c59f7c | ||
|
|
fbe27d69c0 | ||
|
|
021a2c0e2e | ||
|
|
c243b6104c | ||
|
|
a1a822c5b6 | ||
|
|
c4abe39375 | ||
|
|
c52c4f7d32 | ||
|
|
653ddd9f11 | ||
|
|
e854b88394 | ||
|
|
66478143df | ||
|
|
4b461f87ff | ||
|
|
fc2b5744f4 | ||
|
|
65ad070878 | ||
|
|
f1668999a5 | ||
|
|
9db81d1913 | ||
|
|
7c795b800d | ||
|
|
e058a9ae6c | ||
|
|
4f09e6bbb5 | ||
|
|
60e022035f | ||
|
|
7a3e8dba92 | ||
|
|
c4615bd256 | ||
|
|
b6157707db | ||
|
|
09a0a2d7da | ||
|
|
9db4b3a9c2 | ||
|
|
6987332ba8 | ||
|
|
4c76a7fd18 | ||
|
|
2b7d825694 | ||
|
|
07bfa0cf10 | ||
|
|
e15b16b19b | ||
|
|
76d60b0958 | ||
|
|
97d02fd7c8 | ||
|
|
5817186129 | ||
|
|
2d6dd3b0b2 | ||
|
|
cd5d8e1c20 | ||
|
|
fe2332ee87 | ||
|
|
215537a261 | ||
|
|
ec65b98874 | ||
|
|
f1c4a38a49 | ||
|
|
5259f11679 | ||
|
|
565a6563e1 | ||
|
|
8267990e6f | ||
|
|
e8020acabf | ||
|
|
e5b980fbc7 | ||
|
|
b803ce99e3 | ||
|
|
3ae1e58ff2 | ||
|
|
ce347a0ff4 | ||
|
|
d3f97ef93e | ||
|
|
53cd08f0da | ||
|
|
da5ebf7ab3 | ||
|
|
ca3535b1a5 | ||
|
|
2c1e51a8b8 | ||
|
|
71b2859440 | ||
|
|
1d799185d6 | ||
|
|
b97f410731 | ||
|
|
a18c2e5be1 | ||
|
|
3025133d18 | ||
|
|
743e916d12 | ||
|
|
8c5a1d15cb | ||
|
|
372d4d5c34 | ||
|
|
b0796f72d3 | ||
|
|
689adde8ae | ||
|
|
983d533452 | ||
|
|
ef2733df48 | ||
|
|
20db27fa7e | ||
|
|
bb88eb7154 | ||
|
|
2a1bf4a42a | ||
|
|
2889a72b81 | ||
|
|
9ecb233763 | ||
|
|
1db0a9eaa8 | ||
|
|
687ad8d0f0 | ||
|
|
c3f564605f | ||
|
|
c854c7f9d2 | ||
|
|
3713125f57 | ||
|
|
9f9173c691 | ||
|
|
a98903a85b | ||
|
|
a2cbe79787 |
@@ -61,4 +61,12 @@ module.exports = {
|
|||||||
"@typescript-eslint/no-unused-vars": "error",
|
"@typescript-eslint/no-unused-vars": "error",
|
||||||
"@typescript-eslint/no-shadow": "error"
|
"@typescript-eslint/no-shadow": "error"
|
||||||
},
|
},
|
||||||
|
overrides: [
|
||||||
|
{
|
||||||
|
files: ['*.ts'],
|
||||||
|
rules: {
|
||||||
|
'no-undef': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
};
|
};
|
||||||
16
.github/dependabot.yml
vendored
16
.github/dependabot.yml
vendored
@@ -2,14 +2,14 @@
|
|||||||
|
|
||||||
version: 2
|
version: 2
|
||||||
updates:
|
updates:
|
||||||
- package-ecosystem: npm
|
# - package-ecosystem: npm
|
||||||
directory: /
|
# directory: /
|
||||||
schedule:
|
# schedule:
|
||||||
interval: weekly
|
# interval: weekly
|
||||||
day: "tuesday"
|
# day: "tuesday"
|
||||||
time: "01:00"
|
# time: "01:00"
|
||||||
timezone: "Asia/Kolkata"
|
# timezone: "Asia/Kolkata"
|
||||||
open-pull-requests-limit: 15
|
# open-pull-requests-limit: 15
|
||||||
|
|
||||||
- package-ecosystem: github-actions
|
- package-ecosystem: github-actions
|
||||||
directory: /
|
directory: /
|
||||||
|
|||||||
14
.github/workflows/build-pull-request.yml
vendored
14
.github/workflows/build-pull-request.yml
vendored
@@ -12,20 +12,20 @@ jobs:
|
|||||||
PR_NUMBER: ${{github.event.number}}
|
PR_NUMBER: ${{github.event.number}}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3.5.3
|
uses: actions/checkout@v4.2.0
|
||||||
- name: Setup node
|
- name: Setup node
|
||||||
uses: actions/setup-node@v3.8.1
|
uses: actions/setup-node@v4.2.0
|
||||||
with:
|
with:
|
||||||
node-version: 18.12.1
|
node-version: 20.12.2
|
||||||
cache: "npm"
|
cache: 'npm'
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
- name: Build app
|
- name: Build app
|
||||||
env:
|
env:
|
||||||
NODE_OPTIONS: "--max_old_space_size=4096"
|
NODE_OPTIONS: '--max_old_space_size=4096'
|
||||||
run: npm run build
|
run: npm run build
|
||||||
- name: Upload artifact
|
- name: Upload artifact
|
||||||
uses: actions/upload-artifact@v3.1.2
|
uses: actions/upload-artifact@v4.6.0
|
||||||
with:
|
with:
|
||||||
name: preview
|
name: preview
|
||||||
path: dist
|
path: dist
|
||||||
@@ -33,7 +33,7 @@ jobs:
|
|||||||
- name: Save pr number
|
- name: Save pr number
|
||||||
run: echo ${PR_NUMBER} > ./pr.txt
|
run: echo ${PR_NUMBER} > ./pr.txt
|
||||||
- name: Upload pr number
|
- name: Upload pr number
|
||||||
uses: actions/upload-artifact@v3.1.2
|
uses: actions/upload-artifact@v4.6.0
|
||||||
with:
|
with:
|
||||||
name: pr
|
name: pr
|
||||||
path: ./pr.txt
|
path: ./pr.txt
|
||||||
|
|||||||
2
.github/workflows/cla.yml
vendored
2
.github/workflows/cla.yml
vendored
@@ -12,7 +12,7 @@ jobs:
|
|||||||
- name: 'CLA Assistant'
|
- name: 'CLA Assistant'
|
||||||
if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
|
if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
|
||||||
# Beta Release
|
# Beta Release
|
||||||
uses: cla-assistant/github-action@v2.3.0
|
uses: cla-assistant/github-action@v2.6.1
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
# the below token should have repo scope and must be manually added by you in the repository's secret
|
# the below token should have repo scope and must be manually added by you in the repository's secret
|
||||||
|
|||||||
8
.github/workflows/deploy-pull-request.yml
vendored
8
.github/workflows/deploy-pull-request.yml
vendored
@@ -15,7 +15,7 @@ jobs:
|
|||||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||||
steps:
|
steps:
|
||||||
- name: Download pr number
|
- name: Download pr number
|
||||||
uses: dawidd6/action-download-artifact@246dbf436b23d7c49e21a7ab8204ca9ecd1fe615
|
uses: dawidd6/action-download-artifact@20319c5641d495c8a52e688b7dc5fada6c3a9fbc
|
||||||
with:
|
with:
|
||||||
workflow: ${{ github.event.workflow.id }}
|
workflow: ${{ github.event.workflow.id }}
|
||||||
run_id: ${{ github.event.workflow_run.id }}
|
run_id: ${{ github.event.workflow_run.id }}
|
||||||
@@ -24,7 +24,7 @@ jobs:
|
|||||||
id: pr
|
id: pr
|
||||||
run: echo "id=$(<pr.txt)" >> $GITHUB_OUTPUT
|
run: echo "id=$(<pr.txt)" >> $GITHUB_OUTPUT
|
||||||
- name: Download artifact
|
- name: Download artifact
|
||||||
uses: dawidd6/action-download-artifact@246dbf436b23d7c49e21a7ab8204ca9ecd1fe615
|
uses: dawidd6/action-download-artifact@20319c5641d495c8a52e688b7dc5fada6c3a9fbc
|
||||||
with:
|
with:
|
||||||
workflow: ${{ github.event.workflow.id }}
|
workflow: ${{ github.event.workflow.id }}
|
||||||
run_id: ${{ github.event.workflow_run.id }}
|
run_id: ${{ github.event.workflow_run.id }}
|
||||||
@@ -32,7 +32,7 @@ jobs:
|
|||||||
path: dist
|
path: dist
|
||||||
- name: Deploy to Netlify
|
- name: Deploy to Netlify
|
||||||
id: netlify
|
id: netlify
|
||||||
uses: nwtgck/actions-netlify@7a92f00dde8c92a5a9e8385ec2919775f7647352
|
uses: nwtgck/actions-netlify@4cbaf4c08f1a7bfa537d6113472ef4424e4eb654
|
||||||
with:
|
with:
|
||||||
publish-dir: dist
|
publish-dir: dist
|
||||||
deploy-message: "Deploy PR ${{ steps.pr.outputs.id }}"
|
deploy-message: "Deploy PR ${{ steps.pr.outputs.id }}"
|
||||||
@@ -45,7 +45,7 @@ jobs:
|
|||||||
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_PR_CINNY }}
|
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID_PR_CINNY }}
|
||||||
timeout-minutes: 1
|
timeout-minutes: 1
|
||||||
- name: Comment preview on PR
|
- name: Comment preview on PR
|
||||||
uses: thollander/actions-comment-pull-request@1d3973dc4b8e1399c0620d3f2b1aa5e795465308
|
uses: thollander/actions-comment-pull-request@fabd468d3a1a0b97feee5f6b9e499eab0dd903f6
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
with:
|
with:
|
||||||
|
|||||||
4
.github/workflows/docker-pr.yml
vendored
4
.github/workflows/docker-pr.yml
vendored
@@ -11,9 +11,9 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3.5.3
|
uses: actions/checkout@v4.2.0
|
||||||
- name: Build Docker image
|
- name: Build Docker image
|
||||||
uses: docker/build-push-action@v4.1.1
|
uses: docker/build-push-action@v6.13.0
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
push: false
|
push: false
|
||||||
|
|||||||
2
.github/workflows/lockfile.yml
vendored
2
.github/workflows/lockfile.yml
vendored
@@ -14,7 +14,7 @@ jobs:
|
|||||||
pull-requests: write
|
pull-requests: write
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v3.5.3
|
uses: actions/checkout@v4.2.0
|
||||||
- name: NPM Lockfile Changes
|
- name: NPM Lockfile Changes
|
||||||
uses: codepunkt/npm-lockfile-changes@b40543471c36394409466fdb277a73a0856d7891
|
uses: codepunkt/npm-lockfile-changes@b40543471c36394409466fdb277a73a0856d7891
|
||||||
with:
|
with:
|
||||||
|
|||||||
16
.github/workflows/netlify-dev.yml
vendored
16
.github/workflows/netlify-dev.yml
vendored
@@ -3,7 +3,7 @@ name: Deploy to Netlify (dev)
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- dev
|
- dev
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
deploy-to-netlify:
|
deploy-to-netlify:
|
||||||
@@ -11,23 +11,23 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3.5.3
|
uses: actions/checkout@v4.2.0
|
||||||
- name: Setup node
|
- name: Setup node
|
||||||
uses: actions/setup-node@v3.8.1
|
uses: actions/setup-node@v4.2.0
|
||||||
with:
|
with:
|
||||||
node-version: 18.12.1
|
node-version: 20.12.2
|
||||||
cache: "npm"
|
cache: 'npm'
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
- name: Build app
|
- name: Build app
|
||||||
env:
|
env:
|
||||||
NODE_OPTIONS: "--max_old_space_size=4096"
|
NODE_OPTIONS: '--max_old_space_size=4096'
|
||||||
run: npm run build
|
run: npm run build
|
||||||
- name: Deploy to Netlify
|
- name: Deploy to Netlify
|
||||||
uses: nwtgck/actions-netlify@7a92f00dde8c92a5a9e8385ec2919775f7647352
|
uses: nwtgck/actions-netlify@4cbaf4c08f1a7bfa537d6113472ef4424e4eb654
|
||||||
with:
|
with:
|
||||||
publish-dir: dist
|
publish-dir: dist
|
||||||
deploy-message: "Dev deploy ${{ github.sha }}"
|
deploy-message: 'Dev deploy ${{ github.sha }}'
|
||||||
enable-commit-comment: false
|
enable-commit-comment: false
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
production-deploy: true
|
production-deploy: true
|
||||||
|
|||||||
30
.github/workflows/prod-deploy.yml
vendored
30
.github/workflows/prod-deploy.yml
vendored
@@ -10,23 +10,23 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3.5.3
|
uses: actions/checkout@v4.2.0
|
||||||
- name: Setup node
|
- name: Setup node
|
||||||
uses: actions/setup-node@v3.8.1
|
uses: actions/setup-node@v4.2.0
|
||||||
with:
|
with:
|
||||||
node-version: 18.12.1
|
node-version: 20.12.2
|
||||||
cache: "npm"
|
cache: 'npm'
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
- name: Build app
|
- name: Build app
|
||||||
env:
|
env:
|
||||||
NODE_OPTIONS: "--max_old_space_size=4096"
|
NODE_OPTIONS: '--max_old_space_size=4096'
|
||||||
run: npm run build
|
run: npm run build
|
||||||
- name: Deploy to Netlify
|
- name: Deploy to Netlify
|
||||||
uses: nwtgck/actions-netlify@7a92f00dde8c92a5a9e8385ec2919775f7647352
|
uses: nwtgck/actions-netlify@4cbaf4c08f1a7bfa537d6113472ef4424e4eb654
|
||||||
with:
|
with:
|
||||||
publish-dir: dist
|
publish-dir: dist
|
||||||
deploy-message: "Prod deploy ${{ github.ref_name }}"
|
deploy-message: 'Prod deploy ${{ github.ref_name }}'
|
||||||
enable-commit-comment: false
|
enable-commit-comment: false
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
production-deploy: true
|
production-deploy: true
|
||||||
@@ -52,7 +52,7 @@ jobs:
|
|||||||
gpg --export | xxd -p
|
gpg --export | xxd -p
|
||||||
echo '${{ secrets.GNUPG_PASSPHRASE }}' | gpg --batch --yes --pinentry-mode loopback --passphrase-fd 0 --armor --detach-sign cinny-${{ steps.vars.outputs.tag }}.tar.gz
|
echo '${{ secrets.GNUPG_PASSPHRASE }}' | gpg --batch --yes --pinentry-mode loopback --passphrase-fd 0 --armor --detach-sign cinny-${{ steps.vars.outputs.tag }}.tar.gz
|
||||||
- name: Upload tagged release
|
- name: Upload tagged release
|
||||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844
|
uses: softprops/action-gh-release@c95fe1489396fe8a9eb87c0abf8aa5b2ef267fda
|
||||||
with:
|
with:
|
||||||
files: |
|
files: |
|
||||||
cinny-${{ steps.vars.outputs.tag }}.tar.gz
|
cinny-${{ steps.vars.outputs.tag }}.tar.gz
|
||||||
@@ -66,31 +66,31 @@ jobs:
|
|||||||
packages: write
|
packages: write
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3.5.3
|
uses: actions/checkout@v4.2.0
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v2.2.0
|
uses: docker/setup-qemu-action@v3.4.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v2.7.0
|
uses: docker/setup-buildx-action@v3.9.0
|
||||||
- name: Login to Docker Hub
|
- name: Login to Docker Hub
|
||||||
uses: docker/login-action@v2.2.0
|
uses: docker/login-action@v3.3.0
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
- name: Login to the Container registry
|
- name: Login to the Container registry
|
||||||
uses: docker/login-action@v2.2.0
|
uses: docker/login-action@v3.3.0
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
- name: Extract metadata (tags, labels) for Docker
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
id: meta
|
id: meta
|
||||||
uses: docker/metadata-action@v4.6.0
|
uses: docker/metadata-action@v5.6.1
|
||||||
with:
|
with:
|
||||||
images: |
|
images: |
|
||||||
${{ secrets.DOCKER_USERNAME }}/cinny
|
${{ secrets.DOCKER_USERNAME }}/cinny
|
||||||
ghcr.io/${{ github.repository }}
|
ghcr.io/${{ github.repository }}
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
uses: docker/build-push-action@v4.1.1
|
uses: docker/build-push-action@v6.13.0
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
platforms: linux/amd64,linux/arm64
|
platforms: linux/amd64,linux/arm64
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,3 +4,4 @@ node_modules
|
|||||||
devAssets
|
devAssets
|
||||||
|
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
.idea
|
||||||
1
.npmrc
1
.npmrc
@@ -1,3 +1,2 @@
|
|||||||
legacy-peer-deps=true
|
legacy-peer-deps=true
|
||||||
save-exact=true
|
save-exact=true
|
||||||
@matrix-org:registry=https://gitlab.matrix.org/api/v4/projects/27/packages/npm/
|
|
||||||
128
CODE_OF_CONDUCT.md
Normal file
128
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
# Contributor Covenant Code of Conduct
|
||||||
|
|
||||||
|
## Our Pledge
|
||||||
|
|
||||||
|
We as members, contributors, and leaders pledge to make participation in our
|
||||||
|
community a harassment-free experience for everyone, regardless of age, body
|
||||||
|
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||||
|
identity and expression, level of experience, education, socio-economic status,
|
||||||
|
nationality, personal appearance, race, religion, or sexual identity
|
||||||
|
and orientation.
|
||||||
|
|
||||||
|
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||||
|
diverse, inclusive, and healthy community.
|
||||||
|
|
||||||
|
## Our Standards
|
||||||
|
|
||||||
|
Examples of behavior that contributes to a positive environment for our
|
||||||
|
community include:
|
||||||
|
|
||||||
|
* Demonstrating empathy and kindness toward other people
|
||||||
|
* Being respectful of differing opinions, viewpoints, and experiences
|
||||||
|
* Giving and gracefully accepting constructive feedback
|
||||||
|
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||||
|
and learning from the experience
|
||||||
|
* Focusing on what is best not just for us as individuals, but for the
|
||||||
|
overall community
|
||||||
|
|
||||||
|
Examples of unacceptable behavior include:
|
||||||
|
|
||||||
|
* The use of sexualized language or imagery, and sexual attention or
|
||||||
|
advances of any kind
|
||||||
|
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||||
|
* Public or private harassment
|
||||||
|
* Publishing others' private information, such as a physical or email
|
||||||
|
address, without their explicit permission
|
||||||
|
* Other conduct which could reasonably be considered inappropriate in a
|
||||||
|
professional setting
|
||||||
|
|
||||||
|
## Enforcement Responsibilities
|
||||||
|
|
||||||
|
Community leaders are responsible for clarifying and enforcing our standards of
|
||||||
|
acceptable behavior and will take appropriate and fair corrective action in
|
||||||
|
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||||
|
or harmful.
|
||||||
|
|
||||||
|
Community leaders have the right and responsibility to remove, edit, or reject
|
||||||
|
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||||
|
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||||
|
decisions when appropriate.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies within all community spaces, and also applies when
|
||||||
|
an individual is officially representing the community in public spaces.
|
||||||
|
Examples of representing our community include using an official e-mail address,
|
||||||
|
posting via an official social media account, or acting as an appointed
|
||||||
|
representative at an online or offline event.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
|
reported to the community leaders responsible for enforcement at
|
||||||
|
cinnyapp@gmail.com.
|
||||||
|
All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
|
All community leaders are obligated to respect the privacy and security of the
|
||||||
|
reporter of any incident.
|
||||||
|
|
||||||
|
## Enforcement Guidelines
|
||||||
|
|
||||||
|
Community leaders will follow these Community Impact Guidelines in determining
|
||||||
|
the consequences for any action they deem in violation of this Code of Conduct:
|
||||||
|
|
||||||
|
### 1. Correction
|
||||||
|
|
||||||
|
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||||
|
unprofessional or unwelcome in the community.
|
||||||
|
|
||||||
|
**Consequence**: A private, written warning from community leaders, providing
|
||||||
|
clarity around the nature of the violation and an explanation of why the
|
||||||
|
behavior was inappropriate. A public apology may be requested.
|
||||||
|
|
||||||
|
### 2. Warning
|
||||||
|
|
||||||
|
**Community Impact**: A violation through a single incident or series
|
||||||
|
of actions.
|
||||||
|
|
||||||
|
**Consequence**: A warning with consequences for continued behavior. No
|
||||||
|
interaction with the people involved, including unsolicited interaction with
|
||||||
|
those enforcing the Code of Conduct, for a specified period of time. This
|
||||||
|
includes avoiding interactions in community spaces as well as external channels
|
||||||
|
like social media. Violating these terms may lead to a temporary or
|
||||||
|
permanent ban.
|
||||||
|
|
||||||
|
### 3. Temporary Ban
|
||||||
|
|
||||||
|
**Community Impact**: A serious violation of community standards, including
|
||||||
|
sustained inappropriate behavior.
|
||||||
|
|
||||||
|
**Consequence**: A temporary ban from any sort of interaction or public
|
||||||
|
communication with the community for a specified period of time. No public or
|
||||||
|
private interaction with the people involved, including unsolicited interaction
|
||||||
|
with those enforcing the Code of Conduct, is allowed during this period.
|
||||||
|
Violating these terms may lead to a permanent ban.
|
||||||
|
|
||||||
|
### 4. Permanent Ban
|
||||||
|
|
||||||
|
**Community Impact**: Demonstrating a pattern of violation of community
|
||||||
|
standards, including sustained inappropriate behavior, harassment of an
|
||||||
|
individual, or aggression toward or disparagement of classes of individuals.
|
||||||
|
|
||||||
|
**Consequence**: A permanent ban from any sort of public interaction within
|
||||||
|
the community.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||||
|
version 2.0, available at
|
||||||
|
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||||
|
|
||||||
|
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||||
|
enforcement ladder](https://github.com/mozilla/diversity).
|
||||||
|
|
||||||
|
[homepage]: https://www.contributor-covenant.org
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see the FAQ at
|
||||||
|
https://www.contributor-covenant.org/faq. Translations are available at
|
||||||
|
https://www.contributor-covenant.org/translations.
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
## Builder
|
## Builder
|
||||||
FROM node:18.12.1-alpine3.15 as builder
|
FROM node:20.12.2-alpine3.18 as builder
|
||||||
|
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
|
||||||
@@ -11,9 +11,10 @@ RUN npm run build
|
|||||||
|
|
||||||
|
|
||||||
## App
|
## App
|
||||||
FROM nginx:1.25.1-alpine
|
FROM nginx:1.27.4-alpine
|
||||||
|
|
||||||
COPY --from=builder /src/dist /app
|
COPY --from=builder /src/dist /app
|
||||||
|
COPY --from=builder /src/docker-nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
RUN rm -rf /usr/share/nginx/html \
|
RUN rm -rf /usr/share/nginx/html \
|
||||||
&& ln -s /app /usr/share/nginx/html
|
&& ln -s /app /usr/share/nginx/html
|
||||||
|
|||||||
70
README.md
70
README.md
@@ -19,22 +19,24 @@ A Matrix client focusing primarily on simple, elegant and secure interface. The
|
|||||||
<img align="center" src="https://raw.githubusercontent.com/cinnyapp/cinny-site/main/assets/preview2-light.png" height="380">
|
<img align="center" src="https://raw.githubusercontent.com/cinnyapp/cinny-site/main/assets/preview2-light.png" height="380">
|
||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
Web app is available at https://app.cinny.in and gets updated on each new release. The `dev` branch is continuously deployed at https://dev.cinny.in but keep in mind that it could have things broken.
|
* Web app is available at https://app.cinny.in and gets updated on each new release. The `dev` branch is continuously deployed at https://dev.cinny.in but keep in mind that it could have things broken.
|
||||||
|
|
||||||
You can also download our desktop app from [cinny-desktop repository](https://github.com/cinnyapp/cinny-desktop).
|
* You can also download our desktop app from [cinny-desktop repository](https://github.com/cinnyapp/cinny-desktop).
|
||||||
|
|
||||||
To host Cinny on your own, download tarball of the app from [GitHub release](https://github.com/cinnyapp/cinny/releases/latest).
|
* To host Cinny on your own, download tarball of the app from [GitHub release](https://github.com/cinnyapp/cinny/releases/latest).
|
||||||
You can serve the application with a webserver of your choice by simply copying `dist/` directory to the webroot.
|
You can serve the application with a webserver of your choice by simply copying `dist/` directory to the webroot.
|
||||||
To set default Homeserver on login and register page, place a customized [`config.json`](config.json) in webroot of your choice.
|
To set default Homeserver on login, register and Explore Community page, place a customized [`config.json`](config.json) in webroot of your choice.
|
||||||
|
You will also need to setup redirects to serve the assests. An example setting of redirects for netlify is done in [`netlify.toml`](netlify.toml). You can also set `hashRouter.enabled = true` in [`config.json`](config.json) if you have trouble setting redirects.
|
||||||
|
To deploy on subdirectory, you need to rebuild the app youself after updating the `base` path in [`build.config.ts`](build.config.ts). For example, if you want to deploy on `https://cinny.in/app`, then change `base: '/app'`.
|
||||||
|
|
||||||
Alternatively you can just pull the [DockerHub image](https://hub.docker.com/r/ajbura/cinny) by:
|
* Alternatively you can just pull the [DockerHub image](https://hub.docker.com/r/ajbura/cinny) by:
|
||||||
```
|
```
|
||||||
docker pull ajbura/cinny
|
docker pull ajbura/cinny
|
||||||
```
|
```
|
||||||
or [ghcr image](https://github.com/cinnyapp/cinny/pkgs/container/cinny) by:
|
or [ghcr image](https://github.com/cinnyapp/cinny/pkgs/container/cinny) by:
|
||||||
```
|
```
|
||||||
docker pull ghcr.io/cinnyapp/cinny:latest
|
docker pull ghcr.io/cinnyapp/cinny:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>PGP Public Key to verify tarball</summary>
|
<summary>PGP Public Key to verify tarball</summary>
|
||||||
@@ -51,16 +53,16 @@ Frn9ttCEzV55Y+so4X2e4ZnB+5gOnNw+ecifGVdj/+UyWnqvqqDvLrEjjK890nLb
|
|||||||
Pil4siecNMEpiwAN6WSmKpWaCwQAHEGDVeZCc/kT0iYfj5FBcsTVqWiO6eaxkUlm
|
Pil4siecNMEpiwAN6WSmKpWaCwQAHEGDVeZCc/kT0iYfj5FBcsTVqWiO6eaxkUlm
|
||||||
jnulqWqRrlB8CJQQvih/g//uSEBdzIibo+ro+3Jpe120U/XVUH62i9HoRQEm6ADG
|
jnulqWqRrlB8CJQQvih/g//uSEBdzIibo+ro+3Jpe120U/XVUH62i9HoRQEm6ADG
|
||||||
4zS5hIq4xyA8fL8AEQEAAbQdQ2lubnlBcHAgPGNpbm55YXBwQGdtYWlsLmNvbT6J
|
4zS5hIq4xyA8fL8AEQEAAbQdQ2lubnlBcHAgPGNpbm55YXBwQGdtYWlsLmNvbT6J
|
||||||
AdQEEwEIAD4WIQSRri2MHidaaZv+vvuUMwx6UK/M8wUCYnD+DQIbAwUJA8JnAAUL
|
AdQEEwEIAD4CGwMFCwkIBwIGFQoJCAsCBBYCAwECHgECF4AWIQSRri2MHidaaZv+
|
||||||
CQgHAgYVCgkICwIEFgIDAQIeAQIXgAAKCRCUMwx6UK/M88ApC/9HAdbum1lYBC0s
|
vvuUMwx6UK/M8wUCZqEDwAUJFvwIswAKCRCUMwx6UK/M877qC/4lxXOQIoWnLLkK
|
||||||
1k7GwP2A7B4sQtBWjy771BzybWlHeaeG+BGJwg4YiuowXZMm5dubFJFoI/CfeY07
|
YiRCTkGsH6NdxgeYr6wpXT4xuQ45ZxCytwHpOGQmO/5up5961TxWW8D1frRIJHjj
|
||||||
B5aK40/bmT6Xcfkp0VA74c1wUpubBUEJN7tH5HG/OGd9BKeq9E/HHtVaJLVT1k3w
|
AZGoRCL3EKEuY8nt3D99fpf3DvZrs1uoVAhiyn737hRlZAg+QsJheeGCmdSJ0hX5
|
||||||
Rhv9VuHO6nR30EEp7IDthftotl5S4lio3+W0pKk4TAKV8vjaCNp3y/lAHzoP1BU9
|
Yud8SE+9zxLS1+CEjMrsUd/RGre/phme+wNXfaHfREAC9ewolgVChPIbMxG2f+vs
|
||||||
bUSao+7GXVeArKBjuqxN+t1uuiaxPH4L0oe2pMVjTig04zGJM5fTVoly859MEcC/
|
K8Xv52BFng7ta9fgsl1XuOjpuaSbQv6g+4ONk/lxKF0SmnhEGM3dmIYPONxW47Yf
|
||||||
R7Taq9RWGfXFmgCXy8Dviz3eOD90vqpCzhX4+ypK0cp2X0UwhMH4dpKUzExmdbhl
|
atnIjRra/YhPTNwrNBGMmG4IFKaOsMbjW/eakjWTWOVKKJNBMoDdRcYYWIMCpLy8
|
||||||
eBO5GcHB4VxvloRBNf9/Lr7YOTgWejMUw+MlhZE2RE8unfW1LnM/cjL4dhXzO/XB
|
AQUrMtQEsHSnqCwrw818S5A6rrhcfVGk36RGm0nOy6LS5g5jmqaYsvbCcBGY9B2c
|
||||||
FUHHNq8d6d4e02rfWqw7mZo2/NVJgFRcvzw2rgx7w7CKtCNwF4lNjUetB2waZzDb
|
SUAVNm17oo7TtEajk8hcSXoZod1t++pyjcVKEmSn3nFK7v5m3V+cPhNTxZMK459P
|
||||||
fAE0kwhK4Iuwvy12JOBzL0Yy9MxANtwUryr/LQz9AmdT4Rwnp0S5AY0EYnD+DQEM
|
3x1Ucqj/kTqrxKw6s2Uknuk0ajmw0ljV+BQwgL6maguo9BKgCNW5AY0EYnD+DQEM
|
||||||
ANOu/d6ZMF8bW+Df9RDCUQKytbaZfa+ZbIHBus7whCD/SQMOhPKntv3HX7SmMCs+
|
ANOu/d6ZMF8bW+Df9RDCUQKytbaZfa+ZbIHBus7whCD/SQMOhPKntv3HX7SmMCs+
|
||||||
5i27kJMu4YN623JCS7hdCoXVO1R5kXCEcneW/rPBMDutaM472YvIWMIqK9Wwl5+0
|
5i27kJMu4YN623JCS7hdCoXVO1R5kXCEcneW/rPBMDutaM472YvIWMIqK9Wwl5+0
|
||||||
Piu2N+uTkKhe9uS2u7eN+Khef3d7xfjGRxoppM+xI9dZO+jhYiy8LuC0oBohTjJq
|
Piu2N+uTkKhe9uS2u7eN+Khef3d7xfjGRxoppM+xI9dZO+jhYiy8LuC0oBohTjJq
|
||||||
@@ -69,24 +71,24 @@ s1+eh00n/tVpi2Jj9pCm7S0csSXvXj8v2OTdK1jt4YjpzR0/rwh4+/xlOjDjZEqH
|
|||||||
vMPhpzpbgnwkxZ3X8BFne9dJ3maC5zQ3LAeCP5m1W0hXzagYhfyjo74slJgD1O8c
|
vMPhpzpbgnwkxZ3X8BFne9dJ3maC5zQ3LAeCP5m1W0hXzagYhfyjo74slJgD1O8c
|
||||||
LDf2Oxc5MyM8Y/UK497zfqSPfgT3NhQmhHzk83DjXw3I6Z3A3U+Jp61w0eBRI1nx
|
LDf2Oxc5MyM8Y/UK497zfqSPfgT3NhQmhHzk83DjXw3I6Z3A3U+Jp61w0eBRI1nx
|
||||||
H1UIG+gldcAKUTcfwL0lghoT3nmi9JAbvek0Smhz00Bbo8/dx8vwQRxDUxlt7Exx
|
H1UIG+gldcAKUTcfwL0lghoT3nmi9JAbvek0Smhz00Bbo8/dx8vwQRxDUxlt7Exx
|
||||||
NwARAQABiQG8BBgBCAAmFiEEka4tjB4nWmmb/r77lDMMelCvzPMFAmJw/g0CGwwF
|
NwARAQABiQG8BBgBCAAmAhsMFiEEka4tjB4nWmmb/r77lDMMelCvzPMFAmahA9IF
|
||||||
CQPCZwAACgkQlDMMelCvzPPT7Qv8CjXUEhphZFLwpBfaNOzRNfIXJST9aDit8zHW
|
CRb8CMUACgkQlDMMelCvzPPQgQv/d5/z+fxgKqgfhQX+V49X4WgTVxZ/CzztDoJ1
|
||||||
IMmfSpORVfpU71IyIB3o/DtTUPwCeb8nvNJs7aj1QT1ZUSsqFa3yY2S16V/g8+WN
|
XAq1dzTNEy8AFguXIo6eVXPSpMxec7ZreN3+UPQBnCf3eR5YxWNYOYKmk0G4E8D2
|
||||||
sHca6oDSc1J+A0eEpEL1HbG1b5OPBC0AeGvvMOoqrbqThBZVKg1Jc/0SD3cvKElv
|
KGUJept7TSA42/8N2ov6tToXFg4CgzKZj0fYLwgutly7K8eiWmSU6ptaO8aEQBHB
|
||||||
aHeCZCNNmfcZ2Ib4HYhhc8//ZtC9TeI+5J/YesctY1M12EoWMxMrc27Y3P5Pa0BI
|
gTGIOO3h6vJMGVycmoeRnHjv4wV84YWSVFSoJ7cY0he4Z9UznJBbE/KHZjrkXsPo
|
||||||
Uc3qxWggPq1vOFYsEshL0w99HyJvREJmQA7Fa0crV+rICxyrBxJeNnEvjH/0KCBU
|
N+Gg5lDuOP5xjKzM5SogV9lhxBAhMWAg3URUF15yruZBiA8uV1FOK8sal/9C1G7V
|
||||||
LCkEonLY1QwrxyeeV3VpxGE3zHHE3azOdAjTIoAdzX5f/qhbgYlM68GL2f8xdDkp
|
M6ygA6uOZqXlZtcdA94RoSsW2pZ9eLVPsxz2B3Zko7tu11MpNP/wYmfGTI3KxZBj
|
||||||
O0igSGHWhO4F8BfmE7IOTx1Bi7daczp8nCFxh73cKpKB0RUsd9xxrqYpovjmEAlo
|
n/eodvwjJSgHpGOFSmbNzvPJo3to5nNlp7wH1KxIMc6Uuu9hgfDfwkFZgV2bnFIa
|
||||||
w7aHpdzt64NQcsrbK10OSVDF3gFa9Vz20/NQvdUrp8jGmAb/8+nYqI94Jsc28H36
|
Q6gyF548Ub48z7Dz83+WwLgbX19ve4oZx+dqSdczP6ILHRQomtrzrkkP2LU52oI5
|
||||||
UeGsouhyuITLwEhScounZDqop+Dx
|
mxFo+ioe/ABCufSmyqFye0psX3Sp
|
||||||
=Zg+6
|
=WtqZ
|
||||||
-----END PGP PUBLIC KEY BLOCK-----
|
-----END PGP PUBLIC KEY BLOCK-----
|
||||||
```
|
```
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
## Local development
|
## Local development
|
||||||
> We recommend using a version manager as versions change very quickly. You will likely need to switch
|
> We recommend using a version manager as versions change very quickly. You will likely need to switch
|
||||||
between multiple Node.js versions based on the needs of different projects you're working on. [NVM on windows](https://github.com/coreybutler/nvm-windows#installation--upgrades) on Windows and [nvm](https://github.com/nvm-sh/nvm) on Linux/macOS are pretty good choices. Also recommended nodejs version Hydrogen LTS (v18).
|
between multiple Node.js versions based on the needs of different projects you're working on. [NVM on windows](https://github.com/coreybutler/nvm-windows#installation--upgrades) on Windows and [nvm](https://github.com/nvm-sh/nvm) on Linux/macOS are pretty good choices. Recommended nodejs version is Iron LTS (v20).
|
||||||
|
|
||||||
Execute the following commands to start a development server:
|
Execute the following commands to start a development server:
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
# Redirects from what the browser requests to what we serve
|
|
||||||
/login /
|
|
||||||
/register /
|
|
||||||
3
build.config.ts
Normal file
3
build.config.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export default {
|
||||||
|
base: '/',
|
||||||
|
};
|
||||||
31
config.json
31
config.json
@@ -1,7 +1,6 @@
|
|||||||
{
|
{
|
||||||
"defaultHomeserver": 3,
|
"defaultHomeserver": 2,
|
||||||
"homeserverList": [
|
"homeserverList": [
|
||||||
"0wnz.at",
|
|
||||||
"converser.eu",
|
"converser.eu",
|
||||||
"envs.net",
|
"envs.net",
|
||||||
"matrix.org",
|
"matrix.org",
|
||||||
@@ -9,5 +8,31 @@
|
|||||||
"mozilla.org",
|
"mozilla.org",
|
||||||
"xmr.se"
|
"xmr.se"
|
||||||
],
|
],
|
||||||
"allowCustomHomeservers": true
|
"allowCustomHomeservers": true,
|
||||||
|
|
||||||
|
"featuredCommunities": {
|
||||||
|
"openAsDefault": false,
|
||||||
|
"spaces": [
|
||||||
|
"#cinny-space:matrix.org",
|
||||||
|
"#community:matrix.org",
|
||||||
|
"#space:envs.net",
|
||||||
|
"#science-space:matrix.org",
|
||||||
|
"#libregaming-games:tchncs.de",
|
||||||
|
"#mathematics-on:matrix.org"
|
||||||
|
],
|
||||||
|
"rooms": [
|
||||||
|
"#cinny:matrix.org",
|
||||||
|
"#freesoftware:matrix.org",
|
||||||
|
"#pcapdroid:matrix.org",
|
||||||
|
"#gentoo:matrix.org",
|
||||||
|
"#PrivSec.dev:arcticfoxes.net",
|
||||||
|
"#disroot:aria-net.org"
|
||||||
|
],
|
||||||
|
"servers": ["envs.net", "matrix.org", "monero.social", "mozilla.org"]
|
||||||
|
},
|
||||||
|
|
||||||
|
"hashRouter": {
|
||||||
|
"enabled": false,
|
||||||
|
"basename": "/"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,9 +19,17 @@ server {
|
|||||||
|
|
||||||
location / {
|
location / {
|
||||||
root /opt/cinny/dist/;
|
root /opt/cinny/dist/;
|
||||||
index index.html;
|
|
||||||
}
|
rewrite ^/config.json$ /config.json break;
|
||||||
location ~* ^\/(login|register) {
|
rewrite ^/manifest.json$ /manifest.json break;
|
||||||
try_files $uri $uri/ /index.html;
|
|
||||||
|
rewrite ^.*/olm.wasm$ /olm.wasm break;
|
||||||
|
rewrite ^/sw.js$ /sw.js break;
|
||||||
|
rewrite ^/pdf.worker.min.js$ /pdf.worker.min.js break;
|
||||||
|
|
||||||
|
rewrite ^/public/(.*)$ /public/$1 break;
|
||||||
|
rewrite ^/assets/(.*)$ /assets/$1 break;
|
||||||
|
|
||||||
|
rewrite ^(.+)$ /index.html break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
20
docker-nginx.conf
Normal file
20
docker-nginx.conf
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
|
||||||
|
rewrite ^/config.json$ /config.json break;
|
||||||
|
rewrite ^/manifest.json$ /manifest.json break;
|
||||||
|
|
||||||
|
rewrite ^.*/olm.wasm$ /olm.wasm break;
|
||||||
|
rewrite ^/sw.js$ /sw.js break;
|
||||||
|
rewrite ^/pdf.worker.min.js$ /pdf.worker.min.js break;
|
||||||
|
|
||||||
|
rewrite ^/public/(.*)$ /public/$1 break;
|
||||||
|
rewrite ^/assets/(.*)$ /assets/$1 break;
|
||||||
|
|
||||||
|
rewrite ^(.+)$ /index.html break;
|
||||||
|
}
|
||||||
|
}
|
||||||
10
index.html
10
index.html
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
|
||||||
<title>Cinny</title>
|
<title>Cinny</title>
|
||||||
<meta name="name" content="Cinny" />
|
<meta name="name" content="Cinny" />
|
||||||
<meta name="author" content="Ajay Bura" />
|
<meta name="author" content="Ajay Bura" />
|
||||||
@@ -90,12 +90,6 @@
|
|||||||
window.global ||= window;
|
window.global ||= window;
|
||||||
</script>
|
</script>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
<audio id="notificationSound">
|
<script type="module" src="./src/index.tsx"></script>
|
||||||
<source src="./public/sound/notification.ogg" type="audio/ogg" />
|
|
||||||
</audio>
|
|
||||||
<audio id="inviteSound">
|
|
||||||
<source src="./public/sound/invite.ogg" type="audio/ogg" />
|
|
||||||
</audio>
|
|
||||||
<script type="module" src="./src/index.jsx"></script>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
41
netlify.toml
Normal file
41
netlify.toml
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
[[redirects]]
|
||||||
|
from = "/config.json"
|
||||||
|
to = "/config.json"
|
||||||
|
status = 200
|
||||||
|
|
||||||
|
[[redirects]]
|
||||||
|
from = "/manifest.json"
|
||||||
|
to = "/manifest.json"
|
||||||
|
status = 200
|
||||||
|
|
||||||
|
[[redirects]]
|
||||||
|
from = "/sw.js"
|
||||||
|
to = "/sw.js"
|
||||||
|
status = 200
|
||||||
|
|
||||||
|
[[redirects]]
|
||||||
|
from = "*/olm.wasm"
|
||||||
|
to = "/olm.wasm"
|
||||||
|
status = 200
|
||||||
|
force = true
|
||||||
|
|
||||||
|
[[redirects]]
|
||||||
|
from = "/pdf.worker.min.js"
|
||||||
|
to = "/pdf.worker.min.js"
|
||||||
|
status = 200
|
||||||
|
|
||||||
|
[[redirects]]
|
||||||
|
from = "/public/*"
|
||||||
|
to = "/public/:splat"
|
||||||
|
status = 200
|
||||||
|
|
||||||
|
[[redirects]]
|
||||||
|
from = "/assets/*"
|
||||||
|
to = "/assets/:splat"
|
||||||
|
status = 200
|
||||||
|
|
||||||
|
[[redirects]]
|
||||||
|
from = "/*"
|
||||||
|
to = "/index.html"
|
||||||
|
status = 200
|
||||||
|
force = true
|
||||||
9277
package-lock.json
generated
9277
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
65
package.json
65
package.json
@@ -1,8 +1,9 @@
|
|||||||
{
|
{
|
||||||
"name": "cinny",
|
"name": "cinny",
|
||||||
"version": "3.1.0",
|
"version": "4.3.2",
|
||||||
"description": "Yet another matrix client",
|
"description": "Yet another matrix client",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
|
"type": "module",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.0.0"
|
"node": ">=16.0.0"
|
||||||
},
|
},
|
||||||
@@ -19,10 +20,14 @@
|
|||||||
"author": "Ajay Bura",
|
"author": "Ajay Bura",
|
||||||
"license": "AGPL-3.0-only",
|
"license": "AGPL-3.0-only",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@atlaskit/pragmatic-drag-and-drop": "1.1.6",
|
||||||
|
"@atlaskit/pragmatic-drag-and-drop-auto-scroll": "1.3.0",
|
||||||
|
"@atlaskit/pragmatic-drag-and-drop-hitbox": "1.0.3",
|
||||||
"@fontsource/inter": "4.5.14",
|
"@fontsource/inter": "4.5.14",
|
||||||
"@khanacademy/simple-markdown": "0.8.6",
|
"@matrix-org/olm": "3.2.15",
|
||||||
"@matrix-org/olm": "3.2.14",
|
"@tanstack/react-query": "5.24.1",
|
||||||
"@tanstack/react-virtual": "3.0.0-beta.54",
|
"@tanstack/react-query-devtools": "5.24.1",
|
||||||
|
"@tanstack/react-virtual": "3.2.0",
|
||||||
"@tippyjs/react": "4.2.6",
|
"@tippyjs/react": "4.2.6",
|
||||||
"@vanilla-extract/css": "1.9.3",
|
"@vanilla-extract/css": "1.9.3",
|
||||||
"@vanilla-extract/recipes": "0.3.0",
|
"@vanilla-extract/recipes": "0.3.0",
|
||||||
@@ -34,44 +39,44 @@
|
|||||||
"dateformat": "5.0.3",
|
"dateformat": "5.0.3",
|
||||||
"dayjs": "1.11.10",
|
"dayjs": "1.11.10",
|
||||||
"domhandler": "5.0.3",
|
"domhandler": "5.0.3",
|
||||||
"emojibase": "6.1.0",
|
"emojibase": "15.3.1",
|
||||||
"emojibase-data": "7.0.1",
|
"emojibase-data": "15.3.2",
|
||||||
"file-saver": "2.0.5",
|
"file-saver": "2.0.5",
|
||||||
"flux": "4.0.3",
|
"flux": "4.0.3",
|
||||||
"focus-trap-react": "10.0.2",
|
"focus-trap-react": "10.0.2",
|
||||||
"folds": "1.5.0",
|
"folds": "2.1.0",
|
||||||
"formik": "2.2.9",
|
"formik": "2.4.6",
|
||||||
"html-dom-parser": "4.0.0",
|
"html-dom-parser": "4.0.0",
|
||||||
"html-react-parser": "4.2.0",
|
"html-react-parser": "4.2.0",
|
||||||
|
"i18next": "23.12.2",
|
||||||
|
"i18next-browser-languagedetector": "8.0.0",
|
||||||
|
"i18next-http-backend": "2.5.2",
|
||||||
"immer": "9.0.16",
|
"immer": "9.0.16",
|
||||||
"is-hotkey": "0.2.0",
|
"is-hotkey": "0.2.0",
|
||||||
"jotai": "1.12.0",
|
"jotai": "2.6.0",
|
||||||
"katex": "0.16.4",
|
"linkify-react": "4.1.3",
|
||||||
"linkify-html": "4.0.2",
|
"linkifyjs": "4.1.3",
|
||||||
"linkify-react": "4.1.1",
|
"matrix-js-sdk": "35.0.0",
|
||||||
"linkifyjs": "4.0.2",
|
|
||||||
"matrix-js-sdk": "24.1.0",
|
|
||||||
"millify": "6.1.0",
|
"millify": "6.1.0",
|
||||||
"pdfjs-dist": "3.10.111",
|
"pdfjs-dist": "4.2.67",
|
||||||
"prismjs": "1.29.0",
|
"prismjs": "1.29.0",
|
||||||
"prop-types": "15.8.1",
|
"prop-types": "15.8.1",
|
||||||
"react": "17.0.2",
|
"react": "18.2.0",
|
||||||
"react-aria": "3.29.1",
|
"react-aria": "3.29.1",
|
||||||
"react-autosize-textarea": "7.1.0",
|
"react-autosize-textarea": "7.1.0",
|
||||||
"react-blurhash": "0.2.0",
|
"react-blurhash": "0.2.0",
|
||||||
"react-dnd": "15.1.2",
|
"react-dom": "18.2.0",
|
||||||
"react-dnd-html5-backend": "15.1.3",
|
"react-error-boundary": "4.0.13",
|
||||||
"react-dom": "17.0.2",
|
|
||||||
"react-error-boundary": "4.0.10",
|
|
||||||
"react-google-recaptcha": "2.1.0",
|
"react-google-recaptcha": "2.1.0",
|
||||||
|
"react-i18next": "15.0.0",
|
||||||
"react-modal": "3.16.1",
|
"react-modal": "3.16.1",
|
||||||
"react-range": "1.8.14",
|
"react-range": "1.8.14",
|
||||||
"sanitize-html": "2.8.0",
|
"react-router-dom": "6.20.0",
|
||||||
|
"sanitize-html": "2.12.1",
|
||||||
"slate": "0.94.1",
|
"slate": "0.94.1",
|
||||||
"slate-history": "0.93.0",
|
"slate-history": "0.93.0",
|
||||||
"slate-react": "0.98.4",
|
"slate-react": "0.98.4",
|
||||||
"tippy.js": "6.3.7",
|
"tippy.js": "6.3.7",
|
||||||
"twemoji": "14.0.2",
|
|
||||||
"ua-parser-js": "1.0.35"
|
"ua-parser-js": "1.0.35"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -81,26 +86,28 @@
|
|||||||
"@types/file-saver": "2.0.5",
|
"@types/file-saver": "2.0.5",
|
||||||
"@types/node": "18.11.18",
|
"@types/node": "18.11.18",
|
||||||
"@types/prismjs": "1.26.0",
|
"@types/prismjs": "1.26.0",
|
||||||
"@types/react": "18.0.26",
|
"@types/react": "18.2.39",
|
||||||
"@types/react-dom": "18.0.9",
|
"@types/react-dom": "18.2.17",
|
||||||
|
"@types/react-google-recaptcha": "2.1.8",
|
||||||
"@types/sanitize-html": "2.9.0",
|
"@types/sanitize-html": "2.9.0",
|
||||||
"@types/ua-parser-js": "0.7.36",
|
"@types/ua-parser-js": "0.7.36",
|
||||||
"@typescript-eslint/eslint-plugin": "5.46.1",
|
"@typescript-eslint/eslint-plugin": "5.46.1",
|
||||||
"@typescript-eslint/parser": "5.46.1",
|
"@typescript-eslint/parser": "5.46.1",
|
||||||
"@vitejs/plugin-react": "3.0.0",
|
"@vitejs/plugin-react": "4.2.0",
|
||||||
"buffer": "6.0.3",
|
"buffer": "6.0.3",
|
||||||
"eslint": "8.29.0",
|
"eslint": "8.29.0",
|
||||||
"eslint-config-airbnb": "19.0.4",
|
"eslint-config-airbnb": "19.0.4",
|
||||||
"eslint-config-prettier": "8.5.0",
|
"eslint-config-prettier": "8.5.0",
|
||||||
"eslint-plugin-import": "2.26.0",
|
"eslint-plugin-import": "2.29.1",
|
||||||
"eslint-plugin-jsx-a11y": "6.6.1",
|
"eslint-plugin-jsx-a11y": "6.6.1",
|
||||||
"eslint-plugin-react": "7.31.11",
|
"eslint-plugin-react": "7.31.11",
|
||||||
"eslint-plugin-react-hooks": "4.6.0",
|
"eslint-plugin-react-hooks": "4.6.0",
|
||||||
"mini-svg-data-uri": "1.4.4",
|
|
||||||
"prettier": "2.8.1",
|
"prettier": "2.8.1",
|
||||||
"sass": "1.56.2",
|
"sass": "1.56.2",
|
||||||
"typescript": "4.9.4",
|
"typescript": "4.9.4",
|
||||||
"vite": "4.3.9",
|
"vite": "5.0.13",
|
||||||
"vite-plugin-static-copy": "0.13.0"
|
"vite-plugin-pwa": "0.20.5",
|
||||||
|
"vite-plugin-static-copy": "1.0.4",
|
||||||
|
"vite-plugin-top-level-await": "1.4.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
BIN
public/font/Twemoji.Mozilla.v15.1.0.ttf
Normal file
BIN
public/font/Twemoji.Mozilla.v15.1.0.ttf
Normal file
Binary file not shown.
BIN
public/font/Twemoji.Mozilla.v15.1.0.woff2
Normal file
BIN
public/font/Twemoji.Mozilla.v15.1.0.woff2
Normal file
Binary file not shown.
7
public/locales/de.json
Normal file
7
public/locales/de.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"Organisms": {
|
||||||
|
"RoomCommon": {
|
||||||
|
"changed_room_name": " hat den Raum Name geändert"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
7
public/locales/en.json
Normal file
7
public/locales/en.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"Organisms": {
|
||||||
|
"RoomCommon": {
|
||||||
|
"changed_room_name": " changed room name"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,52 +6,52 @@
|
|||||||
"lang": "en-US",
|
"lang": "en-US",
|
||||||
"display": "standalone",
|
"display": "standalone",
|
||||||
"orientation": "portrait",
|
"orientation": "portrait",
|
||||||
"start_url": "/",
|
"start_url": "./",
|
||||||
"background_color": "#fff",
|
"background_color": "#fff",
|
||||||
"theme_color": "#fff",
|
"theme_color": "#fff",
|
||||||
"icons": [
|
"icons": [
|
||||||
{
|
{
|
||||||
"src": "/public/android/android-chrome-36x36.png",
|
"src": "./public/android/android-chrome-36x36.png",
|
||||||
"sizes": "36x36",
|
"sizes": "36x36",
|
||||||
"type": "image/png"
|
"type": "image/png"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "/public/android/android-chrome-48x48.png",
|
"src": "./public/android/android-chrome-48x48.png",
|
||||||
"sizes": "48x48",
|
"sizes": "48x48",
|
||||||
"type": "image/png"
|
"type": "image/png"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "/public/android/android-chrome-72x72.png",
|
"src": "./public/android/android-chrome-72x72.png",
|
||||||
"sizes": "72x72",
|
"sizes": "72x72",
|
||||||
"type": "image/png"
|
"type": "image/png"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "/public/android/android-chrome-96x96.png",
|
"src": "./public/android/android-chrome-96x96.png",
|
||||||
"sizes": "96x96",
|
"sizes": "96x96",
|
||||||
"type": "image/png"
|
"type": "image/png"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "/public/android/android-chrome-144x144.png",
|
"src": "./public/android/android-chrome-144x144.png",
|
||||||
"sizes": "144x144",
|
"sizes": "144x144",
|
||||||
"type": "image/png"
|
"type": "image/png"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "/public/android/android-chrome-192x192.png",
|
"src": "./public/android/android-chrome-192x192.png",
|
||||||
"sizes": "192x192",
|
"sizes": "192x192",
|
||||||
"type": "image/png"
|
"type": "image/png"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "/public/android/android-chrome-256x256.png",
|
"src": "./public/android/android-chrome-256x256.png",
|
||||||
"sizes": "256x256",
|
"sizes": "256x256",
|
||||||
"type": "image/png"
|
"type": "image/png"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "/public/android/android-chrome-384x384.png",
|
"src": "./public/android/android-chrome-384x384.png",
|
||||||
"sizes": "384x384",
|
"sizes": "384x384",
|
||||||
"type": "image/png"
|
"type": "image/png"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "/public/android/android-chrome-512x512.png",
|
"src": "./public/android/android-chrome-512x512.png",
|
||||||
"sizes": "512x512",
|
"sizes": "512x512",
|
||||||
"type": "image/png"
|
"type": "image/png"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,13 @@ import React from 'react';
|
|||||||
import PropTypes from 'prop-types';
|
import PropTypes from 'prop-types';
|
||||||
import './Avatar.scss';
|
import './Avatar.scss';
|
||||||
|
|
||||||
import { twemojify } from '../../../util/twemojify';
|
|
||||||
|
|
||||||
import Text from '../text/Text';
|
import Text from '../text/Text';
|
||||||
import RawIcon from '../system-icons/RawIcon';
|
import RawIcon from '../system-icons/RawIcon';
|
||||||
|
|
||||||
import ImageBrokenSVG from '../../../../public/res/svg/image-broken.svg';
|
import ImageBrokenSVG from '../../../../public/res/svg/image-broken.svg';
|
||||||
import { avatarInitials } from '../../../util/common';
|
import { avatarInitials } from '../../../util/common';
|
||||||
|
|
||||||
const Avatar = React.forwardRef(({
|
const Avatar = React.forwardRef(({ text, bgColor, iconSrc, iconColor, imageSrc, size }, ref) => {
|
||||||
text, bgColor, iconSrc, iconColor, imageSrc, size,
|
|
||||||
}, ref) => {
|
|
||||||
let textSize = 's1';
|
let textSize = 's1';
|
||||||
if (size === 'large') textSize = 'h1';
|
if (size === 'large') textSize = 'h1';
|
||||||
if (size === 'small') textSize = 'b1';
|
if (size === 'small') textSize = 'b1';
|
||||||
@@ -20,34 +16,34 @@ const Avatar = React.forwardRef(({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={ref} className={`avatar-container avatar-container__${size} noselect`}>
|
<div ref={ref} className={`avatar-container avatar-container__${size} noselect`}>
|
||||||
{
|
{imageSrc !== null ? (
|
||||||
imageSrc !== null
|
<img
|
||||||
? (
|
draggable="false"
|
||||||
<img
|
src={imageSrc}
|
||||||
draggable="false"
|
onLoad={(e) => {
|
||||||
src={imageSrc}
|
e.target.style.backgroundColor = 'transparent';
|
||||||
onLoad={(e) => { e.target.style.backgroundColor = 'transparent'; }}
|
}}
|
||||||
onError={(e) => { e.target.src = ImageBrokenSVG; }}
|
onError={(e) => {
|
||||||
alt=""
|
e.target.src = ImageBrokenSVG;
|
||||||
/>
|
}}
|
||||||
)
|
alt=""
|
||||||
: (
|
/>
|
||||||
<span
|
) : (
|
||||||
style={{ backgroundColor: iconSrc === null ? bgColor : 'transparent' }}
|
<span
|
||||||
className={`avatar__border${iconSrc !== null ? '--active' : ''}`}
|
style={{ backgroundColor: iconSrc === null ? bgColor : 'transparent' }}
|
||||||
>
|
className={`avatar__border${iconSrc !== null ? '--active' : ''}`}
|
||||||
{
|
>
|
||||||
iconSrc !== null
|
{iconSrc !== null ? (
|
||||||
? <RawIcon size={size} src={iconSrc} color={iconColor} />
|
<RawIcon size={size} src={iconSrc} color={iconColor} />
|
||||||
: text !== null && (
|
) : (
|
||||||
<Text variant={textSize} primary>
|
text !== null && (
|
||||||
{twemojify(avatarInitials(text))}
|
<Text variant={textSize} primary>
|
||||||
</Text>
|
{avatarInitials(text)}
|
||||||
)
|
</Text>
|
||||||
}
|
)
|
||||||
</span>
|
)}
|
||||||
)
|
</span>
|
||||||
}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -22,8 +22,7 @@
|
|||||||
height: 16px;
|
height: 16px;
|
||||||
background-color: var(--tc-surface-low);
|
background-color: var(--tc-surface-low);
|
||||||
border-radius: calc(var(--bo-radius) / 2);
|
border-radius: calc(var(--bo-radius) / 2);
|
||||||
transition: transform 200ms ease-in-out,
|
transition: transform 200ms ease-in-out, opacity 200ms ease-in-out;
|
||||||
opacity 200ms ease-in-out;
|
|
||||||
opacity: 0.6;
|
opacity: 0.6;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,7 +35,7 @@
|
|||||||
@include dir.prop(transform, var(--ltr), var(--rtl));
|
@include dir.prop(transform, var(--ltr), var(--rtl));
|
||||||
|
|
||||||
transform: translateX(calc(125%));
|
transform: translateX(calc(125%));
|
||||||
background-color: white;
|
background-color: var(--bg-surface);
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
import React, { useEffect, useRef } from 'react';
|
|
||||||
import PropTypes from 'prop-types';
|
|
||||||
import './Math.scss';
|
|
||||||
|
|
||||||
import katex from 'katex';
|
|
||||||
import 'katex/dist/katex.min.css';
|
|
||||||
|
|
||||||
import 'katex/dist/contrib/copy-tex';
|
|
||||||
|
|
||||||
const Math = React.memo(({
|
|
||||||
content, throwOnError, errorColor, displayMode,
|
|
||||||
}) => {
|
|
||||||
const ref = useRef(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
katex.render(content, ref.current, { throwOnError, errorColor, displayMode });
|
|
||||||
}, [content, throwOnError, errorColor, displayMode]);
|
|
||||||
|
|
||||||
return <span ref={ref} />;
|
|
||||||
});
|
|
||||||
Math.defaultProps = {
|
|
||||||
throwOnError: null,
|
|
||||||
errorColor: null,
|
|
||||||
displayMode: null,
|
|
||||||
};
|
|
||||||
Math.propTypes = {
|
|
||||||
content: PropTypes.string.isRequired,
|
|
||||||
throwOnError: PropTypes.bool,
|
|
||||||
errorColor: PropTypes.string,
|
|
||||||
displayMode: PropTypes.bool,
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Math;
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
.katex-display {
|
|
||||||
margin: 0 !important;
|
|
||||||
}
|
|
||||||
@@ -41,8 +41,9 @@ TabItem.propTypes = {
|
|||||||
function Tabs({ items, defaultSelected, onSelect }) {
|
function Tabs({ items, defaultSelected, onSelect }) {
|
||||||
const [selectedItem, setSelectedItem] = useState(items[defaultSelected]);
|
const [selectedItem, setSelectedItem] = useState(items[defaultSelected]);
|
||||||
|
|
||||||
const handleTabSelection = (item, index) => {
|
const handleTabSelection = (item, index, target) => {
|
||||||
if (selectedItem === item) return;
|
if (selectedItem === item) return;
|
||||||
|
target.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
|
||||||
setSelectedItem(item);
|
setSelectedItem(item);
|
||||||
onSelect(item, index);
|
onSelect(item, index);
|
||||||
};
|
};
|
||||||
@@ -57,7 +58,7 @@ function Tabs({ items, defaultSelected, onSelect }) {
|
|||||||
selected={selectedItem.text === item.text}
|
selected={selectedItem.text === item.text}
|
||||||
iconSrc={item.iconSrc}
|
iconSrc={item.iconSrc}
|
||||||
disabled={item.disabled}
|
disabled={item.disabled}
|
||||||
onClick={() => handleTabSelection(item, index)}
|
onClick={(e) => handleTabSelection(item, index, e.currentTarget)}
|
||||||
>
|
>
|
||||||
{item.text}
|
{item.text}
|
||||||
</TabItem>
|
</TabItem>
|
||||||
|
|||||||
73
src/app/components/ActionUIA.tsx
Normal file
73
src/app/components/ActionUIA.tsx
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import React, { ReactNode } from 'react';
|
||||||
|
import { AuthDict, AuthType, IAuthData, UIAFlow } from 'matrix-js-sdk';
|
||||||
|
import { getUIAFlowForStages } from '../utils/matrix-uia';
|
||||||
|
import { useSupportedUIAFlows, useUIACompleted, useUIAFlow } from '../hooks/useUIAFlows';
|
||||||
|
import { UIAFlowOverlay } from './UIAFlowOverlay';
|
||||||
|
import { PasswordStage, SSOStage } from './uia-stages';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
|
||||||
|
export const SUPPORTED_IN_APP_UIA_STAGES = [AuthType.Password, AuthType.Sso];
|
||||||
|
|
||||||
|
export const pickUIAFlow = (uiaFlows: UIAFlow[]): UIAFlow | undefined => {
|
||||||
|
const passwordFlow = getUIAFlowForStages(uiaFlows, [AuthType.Password]);
|
||||||
|
if (passwordFlow) return passwordFlow;
|
||||||
|
return getUIAFlowForStages(uiaFlows, [AuthType.Sso]);
|
||||||
|
};
|
||||||
|
|
||||||
|
type ActionUIAProps = {
|
||||||
|
authData: IAuthData;
|
||||||
|
ongoingFlow: UIAFlow;
|
||||||
|
action: (authDict: AuthDict) => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
};
|
||||||
|
export function ActionUIA({ authData, ongoingFlow, action, onCancel }: ActionUIAProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const completed = useUIACompleted(authData);
|
||||||
|
const { getStageToComplete } = useUIAFlow(authData, ongoingFlow);
|
||||||
|
|
||||||
|
const stageToComplete = getStageToComplete();
|
||||||
|
|
||||||
|
if (!stageToComplete) return null;
|
||||||
|
return (
|
||||||
|
<UIAFlowOverlay
|
||||||
|
currentStep={completed.length + 1}
|
||||||
|
stepCount={ongoingFlow.stages.length}
|
||||||
|
onCancel={onCancel}
|
||||||
|
>
|
||||||
|
{stageToComplete.type === AuthType.Password && (
|
||||||
|
<PasswordStage
|
||||||
|
userId={mx.getUserId()!}
|
||||||
|
stageData={stageToComplete}
|
||||||
|
onCancel={onCancel}
|
||||||
|
submitAuthDict={action}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{stageToComplete.type === AuthType.Sso && stageToComplete.session && (
|
||||||
|
<SSOStage
|
||||||
|
ssoRedirectURL={mx.getFallbackAuthUrl(AuthType.Sso, stageToComplete.session)}
|
||||||
|
stageData={stageToComplete}
|
||||||
|
onCancel={onCancel}
|
||||||
|
submitAuthDict={action}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</UIAFlowOverlay>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type ActionUIAFlowsLoaderProps = {
|
||||||
|
authData: IAuthData;
|
||||||
|
unsupported: () => ReactNode;
|
||||||
|
children: (ongoingFlow: UIAFlow) => ReactNode;
|
||||||
|
};
|
||||||
|
export function ActionUIAFlowsLoader({
|
||||||
|
authData,
|
||||||
|
unsupported,
|
||||||
|
children,
|
||||||
|
}: ActionUIAFlowsLoaderProps) {
|
||||||
|
const supportedFlows = useSupportedUIAFlows(authData.flows ?? [], SUPPORTED_IN_APP_UIA_STAGES);
|
||||||
|
const ongoingFlow = supportedFlows.length > 0 ? supportedFlows[0] : undefined;
|
||||||
|
|
||||||
|
if (!ongoingFlow) return unsupported();
|
||||||
|
|
||||||
|
return children(ongoingFlow);
|
||||||
|
}
|
||||||
64
src/app/components/AuthFlowsLoader.tsx
Normal file
64
src/app/components/AuthFlowsLoader.tsx
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import { ReactNode, useCallback, useEffect, useMemo } from 'react';
|
||||||
|
import { MatrixError, createClient } from 'matrix-js-sdk';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { useAutoDiscoveryInfo } from '../hooks/useAutoDiscoveryInfo';
|
||||||
|
import { promiseFulfilledResult, promiseRejectedResult } from '../utils/common';
|
||||||
|
import {
|
||||||
|
AuthFlows,
|
||||||
|
RegisterFlowStatus,
|
||||||
|
RegisterFlowsResponse,
|
||||||
|
parseRegisterErrResp,
|
||||||
|
} from '../hooks/useAuthFlows';
|
||||||
|
|
||||||
|
type AuthFlowsLoaderProps = {
|
||||||
|
fallback?: () => ReactNode;
|
||||||
|
error?: (err: unknown) => ReactNode;
|
||||||
|
children: (authFlows: AuthFlows) => ReactNode;
|
||||||
|
};
|
||||||
|
export function AuthFlowsLoader({ fallback, error, children }: AuthFlowsLoaderProps) {
|
||||||
|
const autoDiscoveryInfo = useAutoDiscoveryInfo();
|
||||||
|
const baseUrl = autoDiscoveryInfo['m.homeserver'].base_url;
|
||||||
|
|
||||||
|
const mx = useMemo(() => createClient({ baseUrl }), [baseUrl]);
|
||||||
|
|
||||||
|
const [state, load] = useAsyncCallback(
|
||||||
|
useCallback(async () => {
|
||||||
|
const result = await Promise.allSettled([mx.loginFlows(), mx.registerRequest({})]);
|
||||||
|
const loginFlows = promiseFulfilledResult(result[0]);
|
||||||
|
const registerResp = promiseRejectedResult(result[1]) as MatrixError | undefined;
|
||||||
|
let registerFlows: RegisterFlowsResponse = { status: RegisterFlowStatus.InvalidRequest };
|
||||||
|
|
||||||
|
if (typeof registerResp === 'object' && registerResp.httpStatus) {
|
||||||
|
registerFlows = parseRegisterErrResp(registerResp);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!loginFlows) {
|
||||||
|
throw new Error('Missing auth flow!');
|
||||||
|
}
|
||||||
|
if ('errcode' in loginFlows) {
|
||||||
|
throw new Error('Failed to load auth flow!');
|
||||||
|
}
|
||||||
|
|
||||||
|
const authFlows: AuthFlows = {
|
||||||
|
loginFlows,
|
||||||
|
registerFlows,
|
||||||
|
};
|
||||||
|
|
||||||
|
return authFlows;
|
||||||
|
}, [mx])
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
if (state.status === AsyncStatus.Idle || state.status === AsyncStatus.Loading) {
|
||||||
|
return fallback?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.status === AsyncStatus.Error) {
|
||||||
|
return error?.(state.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return children(state.data);
|
||||||
|
}
|
||||||
86
src/app/components/BackRouteHandler.tsx
Normal file
86
src/app/components/BackRouteHandler.tsx
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
import { ReactNode, useCallback } from 'react';
|
||||||
|
import { matchPath, useLocation, useNavigate } from 'react-router-dom';
|
||||||
|
import {
|
||||||
|
getDirectPath,
|
||||||
|
getExplorePath,
|
||||||
|
getHomePath,
|
||||||
|
getInboxPath,
|
||||||
|
getSpacePath,
|
||||||
|
} from '../pages/pathUtils';
|
||||||
|
import { DIRECT_PATH, EXPLORE_PATH, HOME_PATH, INBOX_PATH, SPACE_PATH } from '../pages/paths';
|
||||||
|
|
||||||
|
type BackRouteHandlerProps = {
|
||||||
|
children: (onBack: () => void) => ReactNode;
|
||||||
|
};
|
||||||
|
export function BackRouteHandler({ children }: BackRouteHandlerProps) {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const location = useLocation();
|
||||||
|
|
||||||
|
const goBack = useCallback(() => {
|
||||||
|
if (
|
||||||
|
matchPath(
|
||||||
|
{
|
||||||
|
path: HOME_PATH,
|
||||||
|
caseSensitive: true,
|
||||||
|
end: false,
|
||||||
|
},
|
||||||
|
location.pathname
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
navigate(getHomePath());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
matchPath(
|
||||||
|
{
|
||||||
|
path: DIRECT_PATH,
|
||||||
|
caseSensitive: true,
|
||||||
|
end: false,
|
||||||
|
},
|
||||||
|
location.pathname
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
navigate(getDirectPath());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const spaceMatch = matchPath(
|
||||||
|
{
|
||||||
|
path: SPACE_PATH,
|
||||||
|
caseSensitive: true,
|
||||||
|
end: false,
|
||||||
|
},
|
||||||
|
location.pathname
|
||||||
|
);
|
||||||
|
if (spaceMatch?.params.spaceIdOrAlias) {
|
||||||
|
navigate(getSpacePath(spaceMatch.params.spaceIdOrAlias));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
matchPath(
|
||||||
|
{
|
||||||
|
path: EXPLORE_PATH,
|
||||||
|
caseSensitive: true,
|
||||||
|
end: false,
|
||||||
|
},
|
||||||
|
location.pathname
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
navigate(getExplorePath());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
matchPath(
|
||||||
|
{
|
||||||
|
path: INBOX_PATH,
|
||||||
|
caseSensitive: true,
|
||||||
|
end: false,
|
||||||
|
},
|
||||||
|
location.pathname
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
navigate(getInboxPath());
|
||||||
|
}
|
||||||
|
}, [navigate, location]);
|
||||||
|
|
||||||
|
return children(goBack);
|
||||||
|
}
|
||||||
281
src/app/components/BackupRestore.tsx
Normal file
281
src/app/components/BackupRestore.tsx
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
import React, { MouseEventHandler, useCallback, useState } from 'react';
|
||||||
|
import { useAtom } from 'jotai';
|
||||||
|
import { CryptoApi, KeyBackupInfo } from 'matrix-js-sdk/lib/crypto-api';
|
||||||
|
import {
|
||||||
|
Badge,
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
color,
|
||||||
|
config,
|
||||||
|
Icon,
|
||||||
|
IconButton,
|
||||||
|
Icons,
|
||||||
|
Menu,
|
||||||
|
percent,
|
||||||
|
PopOut,
|
||||||
|
ProgressBar,
|
||||||
|
RectCords,
|
||||||
|
Spinner,
|
||||||
|
Text,
|
||||||
|
} from 'folds';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import { BackupProgressStatus, backupRestoreProgressAtom } from '../state/backupRestore';
|
||||||
|
import { InfoCard } from './info-card';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import {
|
||||||
|
useKeyBackupInfo,
|
||||||
|
useKeyBackupStatus,
|
||||||
|
useKeyBackupSync,
|
||||||
|
useKeyBackupTrust,
|
||||||
|
} from '../hooks/useKeyBackup';
|
||||||
|
import { stopPropagation } from '../utils/keyboard';
|
||||||
|
import { useRestoreBackupOnVerification } from '../hooks/useRestoreBackupOnVerification';
|
||||||
|
|
||||||
|
type BackupStatusProps = {
|
||||||
|
enabled: boolean;
|
||||||
|
};
|
||||||
|
function BackupStatus({ enabled }: BackupStatusProps) {
|
||||||
|
return (
|
||||||
|
<Box as="span" gap="100" alignItems="Center">
|
||||||
|
<Badge variant={enabled ? 'Success' : 'Critical'} fill="Solid" size="200" radii="Pill" />
|
||||||
|
<Text
|
||||||
|
as="span"
|
||||||
|
size="L400"
|
||||||
|
style={{ color: enabled ? color.Success.Main : color.Critical.Main }}
|
||||||
|
>
|
||||||
|
{enabled ? 'Connected' : 'Disconnected'}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
type BackupSyncingProps = {
|
||||||
|
count: number;
|
||||||
|
};
|
||||||
|
function BackupSyncing({ count }: BackupSyncingProps) {
|
||||||
|
return (
|
||||||
|
<Box as="span" gap="100" alignItems="Center">
|
||||||
|
<Spinner size="50" variant="Primary" fill="Soft" />
|
||||||
|
<Text as="span" size="L400" style={{ color: color.Primary.Main }}>
|
||||||
|
Syncing ({count})
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function BackupProgressFetching() {
|
||||||
|
return (
|
||||||
|
<Box grow="Yes" gap="200" alignItems="Center">
|
||||||
|
<Badge variant="Secondary" fill="Solid" radii="300">
|
||||||
|
<Text size="L400">Restoring: 0%</Text>
|
||||||
|
</Badge>
|
||||||
|
<Box grow="Yes" direction="Column">
|
||||||
|
<ProgressBar variant="Secondary" size="300" min={0} max={1} value={0} />
|
||||||
|
</Box>
|
||||||
|
<Spinner size="50" variant="Secondary" fill="Soft" />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type BackupProgressProps = {
|
||||||
|
total: number;
|
||||||
|
downloaded: number;
|
||||||
|
};
|
||||||
|
function BackupProgress({ total, downloaded }: BackupProgressProps) {
|
||||||
|
return (
|
||||||
|
<Box grow="Yes" gap="200" alignItems="Center">
|
||||||
|
<Badge variant="Secondary" fill="Solid" radii="300">
|
||||||
|
<Text size="L400">Restoring: {`${Math.round(percent(0, total, downloaded))}%`}</Text>
|
||||||
|
</Badge>
|
||||||
|
<Box grow="Yes" direction="Column">
|
||||||
|
<ProgressBar variant="Secondary" size="300" min={0} max={total} value={downloaded} />
|
||||||
|
</Box>
|
||||||
|
<Badge variant="Secondary" fill="Soft" radii="Pill">
|
||||||
|
<Text size="L400">
|
||||||
|
{downloaded} / {total}
|
||||||
|
</Text>
|
||||||
|
</Badge>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type BackupTrustInfoProps = {
|
||||||
|
crypto: CryptoApi;
|
||||||
|
backupInfo: KeyBackupInfo;
|
||||||
|
};
|
||||||
|
function BackupTrustInfo({ crypto, backupInfo }: BackupTrustInfoProps) {
|
||||||
|
const trust = useKeyBackupTrust(crypto, backupInfo);
|
||||||
|
|
||||||
|
if (!trust) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box direction="Column">
|
||||||
|
{trust.matchesDecryptionKey ? (
|
||||||
|
<Text size="T200" style={{ color: color.Success.Main }}>
|
||||||
|
<b>Backup has trusted decryption key.</b>
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
|
<b>Backup does not have trusted decryption key!</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{trust.trusted ? (
|
||||||
|
<Text size="T200" style={{ color: color.Success.Main }}>
|
||||||
|
<b>Backup has trusted by signature.</b>
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
|
<b>Backup does not have trusted signature!</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type BackupRestoreTileProps = {
|
||||||
|
crypto: CryptoApi;
|
||||||
|
};
|
||||||
|
export function BackupRestoreTile({ crypto }: BackupRestoreTileProps) {
|
||||||
|
const [restoreProgress, setRestoreProgress] = useAtom(backupRestoreProgressAtom);
|
||||||
|
const restoring =
|
||||||
|
restoreProgress.status === BackupProgressStatus.Fetching ||
|
||||||
|
restoreProgress.status === BackupProgressStatus.Loading;
|
||||||
|
|
||||||
|
const backupEnabled = useKeyBackupStatus(crypto);
|
||||||
|
const backupInfo = useKeyBackupInfo(crypto);
|
||||||
|
const [remainingSession, syncFailure] = useKeyBackupSync();
|
||||||
|
|
||||||
|
const [menuCords, setMenuCords] = useState<RectCords>();
|
||||||
|
|
||||||
|
const handleMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
||||||
|
setMenuCords(evt.currentTarget.getBoundingClientRect());
|
||||||
|
};
|
||||||
|
|
||||||
|
const [restoreState, restoreBackup] = useAsyncCallback<void, Error, []>(
|
||||||
|
useCallback(async () => {
|
||||||
|
await crypto.restoreKeyBackup({
|
||||||
|
progressCallback(progress) {
|
||||||
|
setRestoreProgress(progress);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}, [crypto, setRestoreProgress])
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleRestore = () => {
|
||||||
|
setMenuCords(undefined);
|
||||||
|
restoreBackup();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<InfoCard
|
||||||
|
variant="Surface"
|
||||||
|
title="Encryption Backup"
|
||||||
|
after={
|
||||||
|
<Box alignItems="Center" gap="200">
|
||||||
|
{remainingSession === 0 ? (
|
||||||
|
<BackupStatus enabled={backupEnabled} />
|
||||||
|
) : (
|
||||||
|
<BackupSyncing count={remainingSession} />
|
||||||
|
)}
|
||||||
|
<IconButton
|
||||||
|
aria-pressed={!!menuCords}
|
||||||
|
size="300"
|
||||||
|
variant="Surface"
|
||||||
|
radii="300"
|
||||||
|
onClick={handleMenu}
|
||||||
|
>
|
||||||
|
<Icon size="100" src={Icons.VerticalDots} />
|
||||||
|
</IconButton>
|
||||||
|
<PopOut
|
||||||
|
anchor={menuCords}
|
||||||
|
offset={5}
|
||||||
|
position="Bottom"
|
||||||
|
align="End"
|
||||||
|
content={
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
onDeactivate: () => setMenuCords(undefined),
|
||||||
|
clickOutsideDeactivates: true,
|
||||||
|
isKeyForward: (evt: KeyboardEvent) =>
|
||||||
|
evt.key === 'ArrowDown' || evt.key === 'ArrowRight',
|
||||||
|
isKeyBackward: (evt: KeyboardEvent) =>
|
||||||
|
evt.key === 'ArrowUp' || evt.key === 'ArrowLeft',
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Menu
|
||||||
|
style={{
|
||||||
|
padding: config.space.S100,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box direction="Column" gap="100">
|
||||||
|
<Box direction="Column" gap="200">
|
||||||
|
<InfoCard
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
title="Backup Details"
|
||||||
|
description={
|
||||||
|
<>
|
||||||
|
<span>Version: {backupInfo?.version ?? 'NIL'}</span>
|
||||||
|
<br />
|
||||||
|
<span>Keys: {backupInfo?.count ?? 'NIL'}</span>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
variant="Success"
|
||||||
|
radii="300"
|
||||||
|
aria-disabled={restoreState.status === AsyncStatus.Loading || restoring}
|
||||||
|
onClick={
|
||||||
|
restoreState.status === AsyncStatus.Loading || restoring
|
||||||
|
? undefined
|
||||||
|
: handleRestore
|
||||||
|
}
|
||||||
|
before={<Icon size="100" src={Icons.Download} />}
|
||||||
|
>
|
||||||
|
<Text size="B300">Restore Backup</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Menu>
|
||||||
|
</FocusTrap>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{syncFailure && (
|
||||||
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
|
<b>{syncFailure}</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{!backupEnabled && backupInfo === null && (
|
||||||
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
|
<b>No backup present on server!</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{!syncFailure && !backupEnabled && backupInfo && (
|
||||||
|
<BackupTrustInfo crypto={crypto} backupInfo={backupInfo} />
|
||||||
|
)}
|
||||||
|
{restoreState.status === AsyncStatus.Loading && !restoring && <BackupProgressFetching />}
|
||||||
|
{restoreProgress.status === BackupProgressStatus.Fetching && <BackupProgressFetching />}
|
||||||
|
{restoreProgress.status === BackupProgressStatus.Loading && (
|
||||||
|
<BackupProgress
|
||||||
|
total={restoreProgress.data.total}
|
||||||
|
downloaded={restoreProgress.data.downloaded}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{restoreState.status === AsyncStatus.Error && (
|
||||||
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
|
<b>{restoreState.error.message}</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</InfoCard>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AutoRestoreBackupOnVerification() {
|
||||||
|
useRestoreBackupOnVerification();
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
36
src/app/components/CapabilitiesAndMediaConfigLoader.tsx
Normal file
36
src/app/components/CapabilitiesAndMediaConfigLoader.tsx
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { ReactNode, useCallback, useEffect } from 'react';
|
||||||
|
import { Capabilities } from 'matrix-js-sdk';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
import { MediaConfig } from '../hooks/useMediaConfig';
|
||||||
|
import { promiseFulfilledResult } from '../utils/common';
|
||||||
|
|
||||||
|
type CapabilitiesAndMediaConfigLoaderProps = {
|
||||||
|
children: (capabilities?: Capabilities, mediaConfig?: MediaConfig) => ReactNode;
|
||||||
|
};
|
||||||
|
export function CapabilitiesAndMediaConfigLoader({
|
||||||
|
children,
|
||||||
|
}: CapabilitiesAndMediaConfigLoaderProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const [state, load] = useAsyncCallback<
|
||||||
|
[Capabilities | undefined, MediaConfig | undefined],
|
||||||
|
unknown,
|
||||||
|
[]
|
||||||
|
>(
|
||||||
|
useCallback(async () => {
|
||||||
|
const result = await Promise.allSettled([mx.getCapabilities(), mx.getMediaConfig()]);
|
||||||
|
const capabilities = promiseFulfilledResult(result[0]);
|
||||||
|
const mediaConfig = promiseFulfilledResult(result[1]);
|
||||||
|
return [capabilities, mediaConfig];
|
||||||
|
}, [mx])
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
const [capabilities, mediaConfig] =
|
||||||
|
state.status === AsyncStatus.Success ? state.data : [undefined, undefined];
|
||||||
|
return children(capabilities, mediaConfig);
|
||||||
|
}
|
||||||
19
src/app/components/CapabilitiesLoader.tsx
Normal file
19
src/app/components/CapabilitiesLoader.tsx
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { ReactNode, useCallback, useEffect } from 'react';
|
||||||
|
import { Capabilities } from 'matrix-js-sdk';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
|
||||||
|
type CapabilitiesLoaderProps = {
|
||||||
|
children: (capabilities: Capabilities | undefined) => ReactNode;
|
||||||
|
};
|
||||||
|
export function CapabilitiesLoader({ children }: CapabilitiesLoaderProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const [state, load] = useAsyncCallback(useCallback(() => mx.getCapabilities(), [mx]));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
return children(state.status === AsyncStatus.Success ? state.data : undefined);
|
||||||
|
}
|
||||||
38
src/app/components/ClientConfigLoader.tsx
Normal file
38
src/app/components/ClientConfigLoader.tsx
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { ReactNode, useCallback, useEffect, useState } from 'react';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { ClientConfig } from '../hooks/useClientConfig';
|
||||||
|
import { trimTrailingSlash } from '../utils/common';
|
||||||
|
|
||||||
|
const getClientConfig = async (): Promise<ClientConfig> => {
|
||||||
|
const url = `${trimTrailingSlash(import.meta.env.BASE_URL)}/config.json`;
|
||||||
|
const config = await fetch(url, { method: 'GET' });
|
||||||
|
return config.json();
|
||||||
|
};
|
||||||
|
|
||||||
|
type ClientConfigLoaderProps = {
|
||||||
|
fallback?: () => ReactNode;
|
||||||
|
error?: (err: unknown, retry: () => void, ignore: () => void) => ReactNode;
|
||||||
|
children: (config: ClientConfig) => ReactNode;
|
||||||
|
};
|
||||||
|
export function ClientConfigLoader({ fallback, error, children }: ClientConfigLoaderProps) {
|
||||||
|
const [state, load] = useAsyncCallback(getClientConfig);
|
||||||
|
const [ignoreError, setIgnoreError] = useState(false);
|
||||||
|
|
||||||
|
const ignoreCallback = useCallback(() => setIgnoreError(true), []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
if (state.status === AsyncStatus.Idle || state.status === AsyncStatus.Loading) {
|
||||||
|
return fallback?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ignoreError && state.status === AsyncStatus.Error) {
|
||||||
|
return error?.(state.error, load, ignoreCallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
const config: ClientConfig = state.status === AsyncStatus.Success ? state.data : {};
|
||||||
|
|
||||||
|
return children(config);
|
||||||
|
}
|
||||||
35
src/app/components/ConfirmPasswordMatch.tsx
Normal file
35
src/app/components/ConfirmPasswordMatch.tsx
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { ReactNode, RefObject, useCallback, useRef, useState } from 'react';
|
||||||
|
import { useDebounce } from '../hooks/useDebounce';
|
||||||
|
|
||||||
|
type ConfirmPasswordMatchProps = {
|
||||||
|
initialValue: boolean;
|
||||||
|
children: (
|
||||||
|
match: boolean,
|
||||||
|
doMatch: () => void,
|
||||||
|
passRef: RefObject<HTMLInputElement>,
|
||||||
|
confPassRef: RefObject<HTMLInputElement>
|
||||||
|
) => ReactNode;
|
||||||
|
};
|
||||||
|
export function ConfirmPasswordMatch({ initialValue, children }: ConfirmPasswordMatchProps) {
|
||||||
|
const [match, setMatch] = useState(initialValue);
|
||||||
|
const passRef = useRef<HTMLInputElement>(null);
|
||||||
|
const confPassRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const doMatch = useDebounce(
|
||||||
|
useCallback(() => {
|
||||||
|
const pass = passRef.current?.value;
|
||||||
|
const confPass = confPassRef.current?.value;
|
||||||
|
if (!confPass) {
|
||||||
|
setMatch(initialValue);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setMatch(pass === confPass);
|
||||||
|
}, [initialValue]),
|
||||||
|
{
|
||||||
|
wait: 500,
|
||||||
|
immediate: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return children(match, doMatch, passRef, confPassRef);
|
||||||
|
}
|
||||||
318
src/app/components/DeviceVerification.tsx
Normal file
318
src/app/components/DeviceVerification.tsx
Normal file
@@ -0,0 +1,318 @@
|
|||||||
|
import {
|
||||||
|
ShowSasCallbacks,
|
||||||
|
VerificationPhase,
|
||||||
|
VerificationRequest,
|
||||||
|
Verifier,
|
||||||
|
} from 'matrix-js-sdk/lib/crypto-api';
|
||||||
|
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
|
||||||
|
import { VerificationMethod } from 'matrix-js-sdk/lib/types';
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
|
config,
|
||||||
|
Dialog,
|
||||||
|
Header,
|
||||||
|
Icon,
|
||||||
|
IconButton,
|
||||||
|
Icons,
|
||||||
|
Overlay,
|
||||||
|
OverlayBackdrop,
|
||||||
|
OverlayCenter,
|
||||||
|
Spinner,
|
||||||
|
Text,
|
||||||
|
} from 'folds';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import {
|
||||||
|
useVerificationRequestPhase,
|
||||||
|
useVerificationRequestReceived,
|
||||||
|
useVerifierCancel,
|
||||||
|
useVerifierShowSas,
|
||||||
|
} from '../hooks/useVerificationRequest';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { ContainerColor } from '../styles/ContainerColor.css';
|
||||||
|
|
||||||
|
const DialogHeaderStyles: CSSProperties = {
|
||||||
|
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
|
||||||
|
borderBottomWidth: config.borderWidth.B300,
|
||||||
|
};
|
||||||
|
|
||||||
|
type WaitingMessageProps = {
|
||||||
|
message: string;
|
||||||
|
};
|
||||||
|
function WaitingMessage({ message }: WaitingMessageProps) {
|
||||||
|
return (
|
||||||
|
<Box alignItems="Center" gap="200">
|
||||||
|
<Spinner variant="Secondary" size="200" />
|
||||||
|
<Text size="T300">{message}</Text>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type VerificationUnexpectedProps = { message: string; onClose: () => void };
|
||||||
|
function VerificationUnexpected({ message, onClose }: VerificationUnexpectedProps) {
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<Text>{message}</Text>
|
||||||
|
<Button variant="Secondary" fill="Soft" onClick={onClose}>
|
||||||
|
<Text size="B400">Close</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function VerificationWaitAccept() {
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<Text>Please accept the request from other device.</Text>
|
||||||
|
<WaitingMessage message="Waiting for request to be accepted..." />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type VerificationAcceptProps = {
|
||||||
|
onAccept: () => Promise<void>;
|
||||||
|
};
|
||||||
|
function VerificationAccept({ onAccept }: VerificationAcceptProps) {
|
||||||
|
const [acceptState, accept] = useAsyncCallback(onAccept);
|
||||||
|
|
||||||
|
const accepting = acceptState.status === AsyncStatus.Loading;
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<Text>Click accept to start the verification process.</Text>
|
||||||
|
<Button
|
||||||
|
variant="Primary"
|
||||||
|
fill="Solid"
|
||||||
|
onClick={accept}
|
||||||
|
before={accepting && <Spinner size="100" variant="Primary" fill="Solid" />}
|
||||||
|
disabled={accepting}
|
||||||
|
>
|
||||||
|
<Text size="B400">Accept</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function VerificationWaitStart() {
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<Text>Verification request has been accepted.</Text>
|
||||||
|
<WaitingMessage message="Waiting for the response from other device..." />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type VerificationStartProps = {
|
||||||
|
onStart: () => Promise<void>;
|
||||||
|
};
|
||||||
|
function AutoVerificationStart({ onStart }: VerificationStartProps) {
|
||||||
|
useEffect(() => {
|
||||||
|
onStart();
|
||||||
|
}, [onStart]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<WaitingMessage message="Starting verification using emoji comparison..." />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CompareEmoji({ sasData }: { sasData: ShowSasCallbacks }) {
|
||||||
|
const [confirmState, confirm] = useAsyncCallback(useCallback(() => sasData.confirm(), [sasData]));
|
||||||
|
|
||||||
|
const confirming =
|
||||||
|
confirmState.status === AsyncStatus.Loading || confirmState.status === AsyncStatus.Success;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<Text>Confirm the emoji below are displayed on both devices, in the same order:</Text>
|
||||||
|
<Box
|
||||||
|
className={ContainerColor({ variant: 'SurfaceVariant' })}
|
||||||
|
style={{
|
||||||
|
borderRadius: config.radii.R400,
|
||||||
|
padding: config.space.S500,
|
||||||
|
}}
|
||||||
|
gap="700"
|
||||||
|
wrap="Wrap"
|
||||||
|
justifyContent="Center"
|
||||||
|
>
|
||||||
|
{sasData.sas.emoji?.map(([emoji, name], index) => (
|
||||||
|
<Box
|
||||||
|
// eslint-disable-next-line react/no-array-index-key
|
||||||
|
key={`${emoji}${name}${index}`}
|
||||||
|
direction="Column"
|
||||||
|
gap="100"
|
||||||
|
justifyContent="Center"
|
||||||
|
alignItems="Center"
|
||||||
|
>
|
||||||
|
<Text size="H1">{emoji}</Text>
|
||||||
|
<Text size="T200">{name}</Text>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
<Box direction="Column" gap="200">
|
||||||
|
<Button
|
||||||
|
variant="Primary"
|
||||||
|
fill="Soft"
|
||||||
|
onClick={confirm}
|
||||||
|
disabled={confirming}
|
||||||
|
before={confirming && <Spinner size="100" variant="Primary" />}
|
||||||
|
>
|
||||||
|
<Text size="B400">They Match</Text>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="Primary"
|
||||||
|
fill="Soft"
|
||||||
|
onClick={() => sasData.mismatch()}
|
||||||
|
disabled={confirming}
|
||||||
|
>
|
||||||
|
<Text size="B400">Do not Match</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type SasVerificationProps = {
|
||||||
|
verifier: Verifier;
|
||||||
|
onCancel: () => void;
|
||||||
|
};
|
||||||
|
function SasVerification({ verifier, onCancel }: SasVerificationProps) {
|
||||||
|
const [sasData, setSasData] = useState<ShowSasCallbacks>();
|
||||||
|
|
||||||
|
useVerifierShowSas(verifier, setSasData);
|
||||||
|
useVerifierCancel(verifier, onCancel);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
verifier.verify();
|
||||||
|
}, [verifier]);
|
||||||
|
|
||||||
|
if (sasData) {
|
||||||
|
return <CompareEmoji sasData={sasData} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<WaitingMessage message="Starting verification using emoji comparison..." />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type VerificationDoneProps = {
|
||||||
|
onExit: () => void;
|
||||||
|
};
|
||||||
|
function VerificationDone({ onExit }: VerificationDoneProps) {
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<div>
|
||||||
|
<Text>Your device is verified.</Text>
|
||||||
|
</div>
|
||||||
|
<Button variant="Primary" fill="Solid" onClick={onExit}>
|
||||||
|
<Text size="B400">Okay</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type VerificationCanceledProps = {
|
||||||
|
onClose: () => void;
|
||||||
|
};
|
||||||
|
function VerificationCanceled({ onClose }: VerificationCanceledProps) {
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<Text>Verification has been canceled.</Text>
|
||||||
|
<Button variant="Secondary" fill="Soft" onClick={onClose}>
|
||||||
|
<Text size="B400">Close</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeviceVerificationProps = {
|
||||||
|
request: VerificationRequest;
|
||||||
|
onExit: () => void;
|
||||||
|
};
|
||||||
|
export function DeviceVerification({ request, onExit }: DeviceVerificationProps) {
|
||||||
|
const phase = useVerificationRequestPhase(request);
|
||||||
|
|
||||||
|
const handleCancel = useCallback(() => {
|
||||||
|
if (request.phase !== VerificationPhase.Done && request.phase !== VerificationPhase.Cancelled) {
|
||||||
|
request.cancel();
|
||||||
|
}
|
||||||
|
onExit();
|
||||||
|
}, [request, onExit]);
|
||||||
|
|
||||||
|
const handleAccept = useCallback(() => request.accept(), [request]);
|
||||||
|
const handleStart = useCallback(async () => {
|
||||||
|
await request.startVerification(VerificationMethod.Sas);
|
||||||
|
}, [request]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Overlay open backdrop={<OverlayBackdrop />}>
|
||||||
|
<OverlayCenter>
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
clickOutsideDeactivates: false,
|
||||||
|
escapeDeactivates: false,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Dialog variant="Surface">
|
||||||
|
<Header style={DialogHeaderStyles} variant="Surface" size="500">
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Text size="H4">Device Verification</Text>
|
||||||
|
</Box>
|
||||||
|
<IconButton size="300" radii="300" onClick={handleCancel}>
|
||||||
|
<Icon src={Icons.Cross} />
|
||||||
|
</IconButton>
|
||||||
|
</Header>
|
||||||
|
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
|
||||||
|
{phase === VerificationPhase.Requested &&
|
||||||
|
(request.initiatedByMe ? (
|
||||||
|
<VerificationWaitAccept />
|
||||||
|
) : (
|
||||||
|
<VerificationAccept onAccept={handleAccept} />
|
||||||
|
))}
|
||||||
|
{phase === VerificationPhase.Ready &&
|
||||||
|
(request.initiatedByMe ? (
|
||||||
|
<AutoVerificationStart onStart={handleStart} />
|
||||||
|
) : (
|
||||||
|
<VerificationWaitStart />
|
||||||
|
))}
|
||||||
|
{phase === VerificationPhase.Started &&
|
||||||
|
(request.verifier ? (
|
||||||
|
<SasVerification verifier={request.verifier} onCancel={handleCancel} />
|
||||||
|
) : (
|
||||||
|
<VerificationUnexpected
|
||||||
|
message="Unexpected Error! Verification is started but verifier is missing."
|
||||||
|
onClose={handleCancel}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{phase === VerificationPhase.Done && <VerificationDone onExit={onExit} />}
|
||||||
|
{phase === VerificationPhase.Cancelled && (
|
||||||
|
<VerificationCanceled onClose={handleCancel} />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Dialog>
|
||||||
|
</FocusTrap>
|
||||||
|
</OverlayCenter>
|
||||||
|
</Overlay>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReceiveSelfDeviceVerification() {
|
||||||
|
const [request, setRequest] = useState<VerificationRequest>();
|
||||||
|
|
||||||
|
useVerificationRequestReceived(setRequest);
|
||||||
|
|
||||||
|
const handleExit = useCallback(() => {
|
||||||
|
setRequest(undefined);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!request) return null;
|
||||||
|
|
||||||
|
if (!request.isSelfVerification) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <DeviceVerification request={request} onExit={handleExit} />;
|
||||||
|
}
|
||||||
375
src/app/components/DeviceVerificationSetup.tsx
Normal file
375
src/app/components/DeviceVerificationSetup.tsx
Normal file
@@ -0,0 +1,375 @@
|
|||||||
|
import React, { FormEventHandler, forwardRef, useCallback, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
Header,
|
||||||
|
Box,
|
||||||
|
Text,
|
||||||
|
IconButton,
|
||||||
|
Icon,
|
||||||
|
Icons,
|
||||||
|
config,
|
||||||
|
Button,
|
||||||
|
Chip,
|
||||||
|
color,
|
||||||
|
Spinner,
|
||||||
|
} from 'folds';
|
||||||
|
import FileSaver from 'file-saver';
|
||||||
|
import to from 'await-to-js';
|
||||||
|
import { AuthDict, IAuthData, MatrixError, UIAuthCallback } from 'matrix-js-sdk';
|
||||||
|
import { PasswordInput } from './password-input';
|
||||||
|
import { ContainerColor } from '../styles/ContainerColor.css';
|
||||||
|
import { copyToClipboard } from '../utils/dom';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { clearSecretStorageKeys } from '../../client/state/secretStorageKeys';
|
||||||
|
import { ActionUIA, ActionUIAFlowsLoader } from './ActionUIA';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
import { useAlive } from '../hooks/useAlive';
|
||||||
|
import { UseStateProvider } from './UseStateProvider';
|
||||||
|
|
||||||
|
type UIACallback<T> = (
|
||||||
|
authDict: AuthDict | null
|
||||||
|
) => Promise<[IAuthData, undefined] | [undefined, T]>;
|
||||||
|
|
||||||
|
type PerformAction<T> = (authDict: AuthDict | null) => Promise<T>;
|
||||||
|
|
||||||
|
type UIAAction<T> = {
|
||||||
|
authData: IAuthData;
|
||||||
|
callback: UIACallback<T>;
|
||||||
|
cancelCallback: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
function makeUIAAction<T>(
|
||||||
|
authData: IAuthData,
|
||||||
|
performAction: PerformAction<T>,
|
||||||
|
resolve: (data: T) => void,
|
||||||
|
reject: (error?: any) => void
|
||||||
|
): UIAAction<T> {
|
||||||
|
const action: UIAAction<T> = {
|
||||||
|
authData,
|
||||||
|
callback: async (authDict) => {
|
||||||
|
const [error, data] = await to<T, MatrixError | Error>(performAction(authDict));
|
||||||
|
|
||||||
|
if (error instanceof MatrixError && error.httpStatus === 401) {
|
||||||
|
return [error.data as IAuthData, undefined];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
reject(error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve(data);
|
||||||
|
return [undefined, data];
|
||||||
|
},
|
||||||
|
cancelCallback: reject,
|
||||||
|
};
|
||||||
|
|
||||||
|
return action;
|
||||||
|
}
|
||||||
|
|
||||||
|
type SetupVerificationProps = {
|
||||||
|
onComplete: (recoveryKey: string) => void;
|
||||||
|
};
|
||||||
|
function SetupVerification({ onComplete }: SetupVerificationProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const alive = useAlive();
|
||||||
|
|
||||||
|
const [uiaAction, setUIAAction] = useState<UIAAction<void>>();
|
||||||
|
const [nextAuthData, setNextAuthData] = useState<IAuthData | null>(); // null means no next action.
|
||||||
|
|
||||||
|
const handleAction = useCallback(
|
||||||
|
async (authDict: AuthDict) => {
|
||||||
|
if (!uiaAction) {
|
||||||
|
throw new Error('Unexpected Error! UIA action is perform without data.');
|
||||||
|
}
|
||||||
|
if (alive()) {
|
||||||
|
setNextAuthData(null);
|
||||||
|
}
|
||||||
|
const [authData] = await uiaAction.callback(authDict);
|
||||||
|
|
||||||
|
if (alive() && authData) {
|
||||||
|
setNextAuthData(authData);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[uiaAction, alive]
|
||||||
|
);
|
||||||
|
|
||||||
|
const resetUIA = useCallback(() => {
|
||||||
|
if (!alive()) return;
|
||||||
|
setUIAAction(undefined);
|
||||||
|
setNextAuthData(undefined);
|
||||||
|
}, [alive]);
|
||||||
|
|
||||||
|
const authUploadDeviceSigningKeys: UIAuthCallback<void> = useCallback(
|
||||||
|
(makeRequest) =>
|
||||||
|
new Promise<void>((resolve, reject) => {
|
||||||
|
makeRequest(null)
|
||||||
|
.then(() => {
|
||||||
|
resolve();
|
||||||
|
resetUIA();
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
if (error instanceof MatrixError && error.httpStatus === 401) {
|
||||||
|
const authData = error.data as IAuthData;
|
||||||
|
const action = makeUIAAction(
|
||||||
|
authData,
|
||||||
|
makeRequest as PerformAction<void>,
|
||||||
|
resolve,
|
||||||
|
(err) => {
|
||||||
|
resetUIA();
|
||||||
|
reject(err);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (alive()) {
|
||||||
|
setUIAAction(action);
|
||||||
|
} else {
|
||||||
|
reject(new Error('Authentication failed! Failed to setup device verification.'));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
[alive, resetUIA]
|
||||||
|
);
|
||||||
|
|
||||||
|
const [setupState, setup] = useAsyncCallback<void, Error, [string | undefined]>(
|
||||||
|
useCallback(
|
||||||
|
async (passphrase) => {
|
||||||
|
const crypto = mx.getCrypto();
|
||||||
|
if (!crypto) throw new Error('Unexpected Error! Crypto module not found!');
|
||||||
|
|
||||||
|
const recoveryKeyData = await crypto.createRecoveryKeyFromPassphrase(passphrase);
|
||||||
|
if (!recoveryKeyData.encodedPrivateKey) {
|
||||||
|
throw new Error('Unexpected Error! Failed to create recovery key.');
|
||||||
|
}
|
||||||
|
clearSecretStorageKeys();
|
||||||
|
|
||||||
|
await crypto.bootstrapSecretStorage({
|
||||||
|
createSecretStorageKey: async () => recoveryKeyData,
|
||||||
|
setupNewSecretStorage: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await crypto.bootstrapCrossSigning({
|
||||||
|
authUploadDeviceSigningKeys,
|
||||||
|
setupNewCrossSigning: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await crypto.resetKeyBackup();
|
||||||
|
|
||||||
|
onComplete(recoveryKeyData.encodedPrivateKey);
|
||||||
|
},
|
||||||
|
[mx, onComplete, authUploadDeviceSigningKeys]
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const loading = setupState.status === AsyncStatus.Loading;
|
||||||
|
|
||||||
|
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
|
||||||
|
evt.preventDefault();
|
||||||
|
if (loading) return;
|
||||||
|
|
||||||
|
const target = evt.target as HTMLFormElement | undefined;
|
||||||
|
const passphraseInput = target?.passphraseInput as HTMLInputElement | undefined;
|
||||||
|
let passphrase: string | undefined;
|
||||||
|
if (passphraseInput && passphraseInput.value.length > 0) {
|
||||||
|
passphrase = passphraseInput.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
setup(passphrase);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box as="form" onSubmit={handleSubmit} direction="Column" gap="400">
|
||||||
|
<Text size="T300">
|
||||||
|
Generate a <b>Recovery Key</b> for verifying identity if you do not have access to other
|
||||||
|
devices. Additionally, setup a passphrase as a memorable alternative.
|
||||||
|
</Text>
|
||||||
|
<Box direction="Column" gap="100">
|
||||||
|
<Text size="L400">Passphrase (Optional)</Text>
|
||||||
|
<PasswordInput name="passphraseInput" size="400" readOnly={loading} />
|
||||||
|
</Box>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
before={loading && <Spinner size="200" variant="Primary" fill="Solid" />}
|
||||||
|
>
|
||||||
|
<Text size="B400">Continue</Text>
|
||||||
|
</Button>
|
||||||
|
{setupState.status === AsyncStatus.Error && (
|
||||||
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
|
<b>{setupState.error ? setupState.error.message : 'Unexpected Error!'}</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{nextAuthData !== null && uiaAction && (
|
||||||
|
<ActionUIAFlowsLoader
|
||||||
|
authData={nextAuthData ?? uiaAction.authData}
|
||||||
|
unsupported={() => (
|
||||||
|
<Text size="T200">
|
||||||
|
Authentication steps to perform this action are not supported by client.
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{(ongoingFlow) => (
|
||||||
|
<ActionUIA
|
||||||
|
authData={nextAuthData ?? uiaAction.authData}
|
||||||
|
ongoingFlow={ongoingFlow}
|
||||||
|
action={handleAction}
|
||||||
|
onCancel={uiaAction.cancelCallback}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</ActionUIAFlowsLoader>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type RecoveryKeyDisplayProps = {
|
||||||
|
recoveryKey: string;
|
||||||
|
};
|
||||||
|
function RecoveryKeyDisplay({ recoveryKey }: RecoveryKeyDisplayProps) {
|
||||||
|
const [show, setShow] = useState(false);
|
||||||
|
|
||||||
|
const handleCopy = () => {
|
||||||
|
copyToClipboard(recoveryKey);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDownload = () => {
|
||||||
|
const blob = new Blob([recoveryKey], {
|
||||||
|
type: 'text/plain;charset=us-ascii',
|
||||||
|
});
|
||||||
|
FileSaver.saveAs(blob, 'recovery-key.txt');
|
||||||
|
};
|
||||||
|
|
||||||
|
const safeToDisplayKey = show ? recoveryKey : recoveryKey.replace(/[^\s]/g, '*');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="400">
|
||||||
|
<Text size="T300">
|
||||||
|
Store the Recovery Key in a safe place for future use, as you will need it to verify your
|
||||||
|
identity if you do not have access to other devices.
|
||||||
|
</Text>
|
||||||
|
<Box direction="Column" gap="100">
|
||||||
|
<Text size="L400">Recovery Key</Text>
|
||||||
|
<Box
|
||||||
|
className={ContainerColor({ variant: 'SurfaceVariant' })}
|
||||||
|
style={{
|
||||||
|
padding: config.space.S300,
|
||||||
|
borderRadius: config.radii.R400,
|
||||||
|
}}
|
||||||
|
alignItems="Center"
|
||||||
|
justifyContent="Center"
|
||||||
|
gap="400"
|
||||||
|
>
|
||||||
|
<Text style={{ fontFamily: 'monospace' }} size="T200" priority="300">
|
||||||
|
{safeToDisplayKey}
|
||||||
|
</Text>
|
||||||
|
<Chip onClick={() => setShow(!show)} variant="Secondary" radii="Pill">
|
||||||
|
<Text size="B300">{show ? 'Hide' : 'Show'}</Text>
|
||||||
|
</Chip>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
<Box direction="Column" gap="200">
|
||||||
|
<Button onClick={handleCopy}>
|
||||||
|
<Text size="B400">Copy</Text>
|
||||||
|
</Button>
|
||||||
|
<Button onClick={handleDownload} fill="Soft">
|
||||||
|
<Text size="B400">Download</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeviceVerificationSetupProps = {
|
||||||
|
onCancel: () => void;
|
||||||
|
};
|
||||||
|
export const DeviceVerificationSetup = forwardRef<HTMLDivElement, DeviceVerificationSetupProps>(
|
||||||
|
({ onCancel }, ref) => {
|
||||||
|
const [recoveryKey, setRecoveryKey] = useState<string>();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog ref={ref}>
|
||||||
|
<Header
|
||||||
|
style={{
|
||||||
|
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
|
||||||
|
borderBottomWidth: config.borderWidth.B300,
|
||||||
|
}}
|
||||||
|
variant="Surface"
|
||||||
|
size="500"
|
||||||
|
>
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Text size="H4">Setup Device Verification</Text>
|
||||||
|
</Box>
|
||||||
|
<IconButton size="300" radii="300" onClick={onCancel}>
|
||||||
|
<Icon src={Icons.Cross} />
|
||||||
|
</IconButton>
|
||||||
|
</Header>
|
||||||
|
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
|
||||||
|
{recoveryKey ? (
|
||||||
|
<RecoveryKeyDisplay recoveryKey={recoveryKey} />
|
||||||
|
) : (
|
||||||
|
<SetupVerification onComplete={setRecoveryKey} />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
type DeviceVerificationResetProps = {
|
||||||
|
onCancel: () => void;
|
||||||
|
};
|
||||||
|
export const DeviceVerificationReset = forwardRef<HTMLDivElement, DeviceVerificationResetProps>(
|
||||||
|
({ onCancel }, ref) => {
|
||||||
|
const [reset, setReset] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog ref={ref}>
|
||||||
|
<Header
|
||||||
|
style={{
|
||||||
|
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
|
||||||
|
borderBottomWidth: config.borderWidth.B300,
|
||||||
|
}}
|
||||||
|
variant="Surface"
|
||||||
|
size="500"
|
||||||
|
>
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Text size="H4">Reset Device Verification</Text>
|
||||||
|
</Box>
|
||||||
|
<IconButton size="300" radii="300" onClick={onCancel}>
|
||||||
|
<Icon src={Icons.Cross} />
|
||||||
|
</IconButton>
|
||||||
|
</Header>
|
||||||
|
{reset ? (
|
||||||
|
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
|
||||||
|
<UseStateProvider initial={undefined}>
|
||||||
|
{(recoveryKey: string | undefined, setRecoveryKey) =>
|
||||||
|
recoveryKey ? (
|
||||||
|
<RecoveryKeyDisplay recoveryKey={recoveryKey} />
|
||||||
|
) : (
|
||||||
|
<SetupVerification onComplete={setRecoveryKey} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</UseStateProvider>
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
|
||||||
|
<Box direction="Column" gap="200">
|
||||||
|
<Text size="H1">✋🧑🚒🤚</Text>
|
||||||
|
<Text size="T300">Resetting device verification is permanent.</Text>
|
||||||
|
<Text size="T300">
|
||||||
|
Anyone you have verified with will see security alerts and your encryption backup
|
||||||
|
will be lost. You almost certainly do not want to do this, unless you have lost{' '}
|
||||||
|
<b>Recovery Key</b> or <b>Recovery Passphrase</b> and every device you can verify
|
||||||
|
from.
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Button variant="Critical" onClick={() => setReset(true)}>
|
||||||
|
<Text size="B400">Reset</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
24
src/app/components/DeviceVerificationStatus.ts
Normal file
24
src/app/components/DeviceVerificationStatus.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { ReactNode } from 'react';
|
||||||
|
import { CryptoApi } from 'matrix-js-sdk/lib/crypto-api';
|
||||||
|
import {
|
||||||
|
useDeviceVerificationStatus,
|
||||||
|
VerificationStatus,
|
||||||
|
} from '../hooks/useDeviceVerificationStatus';
|
||||||
|
|
||||||
|
type DeviceVerificationStatusProps = {
|
||||||
|
crypto?: CryptoApi;
|
||||||
|
userId: string;
|
||||||
|
deviceId: string;
|
||||||
|
children: (verificationStatus: VerificationStatus) => ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function DeviceVerificationStatus({
|
||||||
|
crypto,
|
||||||
|
userId,
|
||||||
|
deviceId,
|
||||||
|
children,
|
||||||
|
}: DeviceVerificationStatusProps) {
|
||||||
|
const status = useDeviceVerificationStatus(crypto, userId, deviceId);
|
||||||
|
|
||||||
|
return children(status);
|
||||||
|
}
|
||||||
89
src/app/components/LogoutDialog.tsx
Normal file
89
src/app/components/LogoutDialog.tsx
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import React, { forwardRef, useCallback } from 'react';
|
||||||
|
import { Dialog, Header, config, Box, Text, Button, Spinner, color } from 'folds';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { logoutClient } from '../../client/initMatrix';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
import { useCrossSigningActive } from '../hooks/useCrossSigning';
|
||||||
|
import { InfoCard } from './info-card';
|
||||||
|
import {
|
||||||
|
useDeviceVerificationStatus,
|
||||||
|
VerificationStatus,
|
||||||
|
} from '../hooks/useDeviceVerificationStatus';
|
||||||
|
|
||||||
|
type LogoutDialogProps = {
|
||||||
|
handleClose: () => void;
|
||||||
|
};
|
||||||
|
export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
|
||||||
|
({ handleClose }, ref) => {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const hasEncryptedRoom = !!mx.getRooms().find((room) => room.hasEncryptionStateEvent());
|
||||||
|
const crossSigningActive = useCrossSigningActive();
|
||||||
|
const verificationStatus = useDeviceVerificationStatus(
|
||||||
|
mx.getCrypto(),
|
||||||
|
mx.getSafeUserId(),
|
||||||
|
mx.getDeviceId() ?? undefined
|
||||||
|
);
|
||||||
|
|
||||||
|
const [logoutState, logout] = useAsyncCallback<void, Error, []>(
|
||||||
|
useCallback(async () => {
|
||||||
|
await logoutClient(mx);
|
||||||
|
}, [mx])
|
||||||
|
);
|
||||||
|
|
||||||
|
const ongoingLogout = logoutState.status === AsyncStatus.Loading;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog variant="Surface" ref={ref}>
|
||||||
|
<Header
|
||||||
|
style={{
|
||||||
|
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
|
||||||
|
borderBottomWidth: config.borderWidth.B300,
|
||||||
|
}}
|
||||||
|
variant="Surface"
|
||||||
|
size="500"
|
||||||
|
>
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Text size="H4">Logout</Text>
|
||||||
|
</Box>
|
||||||
|
</Header>
|
||||||
|
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
|
||||||
|
{hasEncryptedRoom &&
|
||||||
|
(crossSigningActive ? (
|
||||||
|
verificationStatus === VerificationStatus.Unverified && (
|
||||||
|
<InfoCard
|
||||||
|
variant="Critical"
|
||||||
|
title="Unverified Device"
|
||||||
|
description="Verify your device before logging out to save your encrypted messages."
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<InfoCard
|
||||||
|
variant="Critical"
|
||||||
|
title="Alert"
|
||||||
|
description="Enable device verification or export your encrypted data from settings to avoid losing access to your messages."
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<Text priority="400">You’re about to log out. Are you sure?</Text>
|
||||||
|
{logoutState.status === AsyncStatus.Error && (
|
||||||
|
<Text style={{ color: color.Critical.Main }} size="T300">
|
||||||
|
Failed to logout! {logoutState.error.message}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
<Box direction="Column" gap="200">
|
||||||
|
<Button
|
||||||
|
variant="Critical"
|
||||||
|
onClick={logout}
|
||||||
|
disabled={ongoingLogout}
|
||||||
|
before={ongoingLogout && <Spinner variant="Critical" fill="Solid" size="200" />}
|
||||||
|
>
|
||||||
|
<Text size="B400">Logout</Text>
|
||||||
|
</Button>
|
||||||
|
<Button variant="Secondary" fill="Soft" onClick={handleClose} disabled={ongoingLogout}>
|
||||||
|
<Text size="B400">Cancel</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
199
src/app/components/ManualVerification.tsx
Normal file
199
src/app/components/ManualVerification.tsx
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
import React, { MouseEventHandler, ReactNode, useCallback, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Text,
|
||||||
|
Chip,
|
||||||
|
Icon,
|
||||||
|
Icons,
|
||||||
|
RectCords,
|
||||||
|
PopOut,
|
||||||
|
Menu,
|
||||||
|
config,
|
||||||
|
MenuItem,
|
||||||
|
color,
|
||||||
|
} from 'folds';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import { stopPropagation } from '../utils/keyboard';
|
||||||
|
import { SettingTile } from './setting-tile';
|
||||||
|
import { SecretStorageKeyContent } from '../../types/matrix/accountData';
|
||||||
|
import { SecretStorageRecoveryKey, SecretStorageRecoveryPassphrase } from './SecretStorage';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { storePrivateKey } from '../../client/state/secretStorageKeys';
|
||||||
|
|
||||||
|
export enum ManualVerificationMethod {
|
||||||
|
RecoveryPassphrase = 'passphrase',
|
||||||
|
RecoveryKey = 'key',
|
||||||
|
}
|
||||||
|
type ManualVerificationMethodSwitcherProps = {
|
||||||
|
value: ManualVerificationMethod;
|
||||||
|
onChange: (value: ManualVerificationMethod) => void;
|
||||||
|
};
|
||||||
|
export function ManualVerificationMethodSwitcher({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: ManualVerificationMethodSwitcherProps) {
|
||||||
|
const [menuCords, setMenuCords] = useState<RectCords>();
|
||||||
|
|
||||||
|
const handleMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
||||||
|
setMenuCords(evt.currentTarget.getBoundingClientRect());
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSelect = (method: ManualVerificationMethod) => {
|
||||||
|
setMenuCords(undefined);
|
||||||
|
onChange(method);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Chip
|
||||||
|
type="button"
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
radii="Pill"
|
||||||
|
before={<Icon size="100" src={Icons.ChevronBottom} />}
|
||||||
|
onClick={handleMenu}
|
||||||
|
>
|
||||||
|
<Text as="span" size="B300">
|
||||||
|
{value === ManualVerificationMethod.RecoveryPassphrase && 'Recovery Passphrase'}
|
||||||
|
{value === ManualVerificationMethod.RecoveryKey && 'Recovery Key'}
|
||||||
|
</Text>
|
||||||
|
</Chip>
|
||||||
|
<PopOut
|
||||||
|
anchor={menuCords}
|
||||||
|
offset={5}
|
||||||
|
position="Bottom"
|
||||||
|
align="End"
|
||||||
|
content={
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
onDeactivate: () => setMenuCords(undefined),
|
||||||
|
clickOutsideDeactivates: true,
|
||||||
|
isKeyForward: (evt: KeyboardEvent) =>
|
||||||
|
evt.key === 'ArrowDown' || evt.key === 'ArrowRight',
|
||||||
|
isKeyBackward: (evt: KeyboardEvent) =>
|
||||||
|
evt.key === 'ArrowUp' || evt.key === 'ArrowLeft',
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Menu>
|
||||||
|
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
|
||||||
|
<MenuItem
|
||||||
|
size="300"
|
||||||
|
variant="Surface"
|
||||||
|
aria-selected={value === ManualVerificationMethod.RecoveryPassphrase}
|
||||||
|
radii="300"
|
||||||
|
onClick={() => handleSelect(ManualVerificationMethod.RecoveryPassphrase)}
|
||||||
|
>
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Text size="T300">Recovery Passphrase</Text>
|
||||||
|
</Box>
|
||||||
|
</MenuItem>
|
||||||
|
<MenuItem
|
||||||
|
size="300"
|
||||||
|
variant="Surface"
|
||||||
|
aria-selected={value === ManualVerificationMethod.RecoveryKey}
|
||||||
|
radii="300"
|
||||||
|
onClick={() => handleSelect(ManualVerificationMethod.RecoveryKey)}
|
||||||
|
>
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Text size="T300">Recovery Key</Text>
|
||||||
|
</Box>
|
||||||
|
</MenuItem>
|
||||||
|
</Box>
|
||||||
|
</Menu>
|
||||||
|
</FocusTrap>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type ManualVerificationTileProps = {
|
||||||
|
secretStorageKeyId: string;
|
||||||
|
secretStorageKeyContent: SecretStorageKeyContent;
|
||||||
|
options?: ReactNode;
|
||||||
|
};
|
||||||
|
export function ManualVerificationTile({
|
||||||
|
secretStorageKeyId,
|
||||||
|
secretStorageKeyContent,
|
||||||
|
options,
|
||||||
|
}: ManualVerificationTileProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const hasPassphrase = !!secretStorageKeyContent.passphrase;
|
||||||
|
const [method, setMethod] = useState(
|
||||||
|
hasPassphrase
|
||||||
|
? ManualVerificationMethod.RecoveryPassphrase
|
||||||
|
: ManualVerificationMethod.RecoveryKey
|
||||||
|
);
|
||||||
|
|
||||||
|
const verifyAndRestoreBackup = useCallback(
|
||||||
|
async (recoveryKey: Uint8Array) => {
|
||||||
|
const crypto = mx.getCrypto();
|
||||||
|
if (!crypto) {
|
||||||
|
throw new Error('Unexpected Error! Crypto object not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
storePrivateKey(secretStorageKeyId, recoveryKey);
|
||||||
|
|
||||||
|
await crypto.bootstrapCrossSigning({});
|
||||||
|
await crypto.bootstrapSecretStorage({});
|
||||||
|
|
||||||
|
await crypto.loadSessionBackupPrivateKeyFromSecretStorage();
|
||||||
|
},
|
||||||
|
[mx, secretStorageKeyId]
|
||||||
|
);
|
||||||
|
|
||||||
|
const [verifyState, handleDecodedRecoveryKey] = useAsyncCallback<void, Error, [Uint8Array]>(
|
||||||
|
verifyAndRestoreBackup
|
||||||
|
);
|
||||||
|
const verifying = verifyState.status === AsyncStatus.Loading;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="200">
|
||||||
|
<SettingTile
|
||||||
|
title="Verify Manually"
|
||||||
|
description={hasPassphrase ? 'Select a verification method.' : 'Provide recovery key.'}
|
||||||
|
after={
|
||||||
|
<Box alignItems="Center" gap="200">
|
||||||
|
{hasPassphrase && (
|
||||||
|
<ManualVerificationMethodSwitcher value={method} onChange={setMethod} />
|
||||||
|
)}
|
||||||
|
{options}
|
||||||
|
</Box>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{verifyState.status === AsyncStatus.Success ? (
|
||||||
|
<Text size="T200" style={{ color: color.Success.Main }}>
|
||||||
|
<b>Device verified!</b>
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Box direction="Column" gap="100">
|
||||||
|
{method === ManualVerificationMethod.RecoveryKey && (
|
||||||
|
<SecretStorageRecoveryKey
|
||||||
|
processing={verifying}
|
||||||
|
keyContent={secretStorageKeyContent}
|
||||||
|
onDecodedRecoveryKey={handleDecodedRecoveryKey}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{method === ManualVerificationMethod.RecoveryPassphrase &&
|
||||||
|
secretStorageKeyContent.passphrase && (
|
||||||
|
<SecretStorageRecoveryPassphrase
|
||||||
|
processing={verifying}
|
||||||
|
keyContent={secretStorageKeyContent}
|
||||||
|
passphraseContent={secretStorageKeyContent.passphrase}
|
||||||
|
onDecodedRecoveryKey={handleDecodedRecoveryKey}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{verifyState.status === AsyncStatus.Error && (
|
||||||
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
|
<b>{verifyState.error.message}</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
19
src/app/components/MediaConfigLoader.tsx
Normal file
19
src/app/components/MediaConfigLoader.tsx
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { ReactNode, useCallback, useEffect } from 'react';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
import { MediaConfig } from '../hooks/useMediaConfig';
|
||||||
|
|
||||||
|
type MediaConfigLoaderProps = {
|
||||||
|
children: (mediaConfig: MediaConfig | undefined) => ReactNode;
|
||||||
|
};
|
||||||
|
export function MediaConfigLoader({ children }: MediaConfigLoaderProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const [state, load] = useAsyncCallback(useCallback(() => mx.getMediaConfig(), [mx]));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
return children(state.status === AsyncStatus.Success ? state.data : undefined);
|
||||||
|
}
|
||||||
29
src/app/components/Modal500.tsx
Normal file
29
src/app/components/Modal500.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import React, { ReactNode } from 'react';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import { Modal, Overlay, OverlayBackdrop, OverlayCenter } from 'folds';
|
||||||
|
import { stopPropagation } from '../utils/keyboard';
|
||||||
|
|
||||||
|
type Modal500Props = {
|
||||||
|
requestClose: () => void;
|
||||||
|
children: ReactNode;
|
||||||
|
};
|
||||||
|
export function Modal500({ requestClose, children }: Modal500Props) {
|
||||||
|
return (
|
||||||
|
<Overlay open backdrop={<OverlayBackdrop />}>
|
||||||
|
<OverlayCenter>
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
clickOutsideDeactivates: true,
|
||||||
|
onDeactivate: requestClose,
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Modal size="500" variant="Background">
|
||||||
|
{children}
|
||||||
|
</Modal>
|
||||||
|
</FocusTrap>
|
||||||
|
</OverlayCenter>
|
||||||
|
</Overlay>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
/* eslint-disable no-param-reassign */
|
/* eslint-disable no-param-reassign */
|
||||||
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
|
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
|
||||||
import React, { FormEventHandler, useEffect, useRef, useState } from 'react';
|
import React, { FormEventHandler, MouseEventHandler, useEffect, useRef, useState } from 'react';
|
||||||
import classNames from 'classnames';
|
import classNames from 'classnames';
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
Input,
|
Input,
|
||||||
Menu,
|
Menu,
|
||||||
PopOut,
|
PopOut,
|
||||||
|
RectCords,
|
||||||
Scroll,
|
Scroll,
|
||||||
Spinner,
|
Spinner,
|
||||||
Text,
|
Text,
|
||||||
@@ -25,6 +26,7 @@ import * as css from './PdfViewer.css';
|
|||||||
import { AsyncStatus } from '../../hooks/useAsyncCallback';
|
import { AsyncStatus } from '../../hooks/useAsyncCallback';
|
||||||
import { useZoom } from '../../hooks/useZoom';
|
import { useZoom } from '../../hooks/useZoom';
|
||||||
import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '../../plugins/pdfjs-dist';
|
import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '../../plugins/pdfjs-dist';
|
||||||
|
import { stopPropagation } from '../../utils/keyboard';
|
||||||
|
|
||||||
export type PdfViewerProps = {
|
export type PdfViewerProps = {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -48,7 +50,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
|||||||
const isError =
|
const isError =
|
||||||
pdfJSState.status === AsyncStatus.Error || docState.status === AsyncStatus.Error;
|
pdfJSState.status === AsyncStatus.Error || docState.status === AsyncStatus.Error;
|
||||||
const [pageNo, setPageNo] = useState(1);
|
const [pageNo, setPageNo] = useState(1);
|
||||||
const [openJump, setOpenJump] = useState(false);
|
const [jumpAnchor, setJumpAnchor] = useState<RectCords>();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadPdfJS();
|
loadPdfJS();
|
||||||
@@ -86,7 +88,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
|||||||
if (!jumpInput) return;
|
if (!jumpInput) return;
|
||||||
const jumpTo = parseInt(jumpInput.value, 10);
|
const jumpTo = parseInt(jumpInput.value, 10);
|
||||||
setPageNo(Math.max(1, Math.min(docState.data.numPages, jumpTo)));
|
setPageNo(Math.max(1, Math.min(docState.data.numPages, jumpTo)));
|
||||||
setOpenJump(false);
|
setJumpAnchor(undefined);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handlePrevPage = () => {
|
const handlePrevPage = () => {
|
||||||
@@ -98,6 +100,10 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
|||||||
setPageNo((n) => Math.min(n + 1, docState.data.numPages));
|
setPageNo((n) => Math.min(n + 1, docState.data.numPages));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleOpenJump: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
||||||
|
setJumpAnchor(evt.currentTarget.getBoundingClientRect());
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box className={classNames(css.PdfViewer, className)} direction="Column" {...props} ref={ref}>
|
<Box className={classNames(css.PdfViewer, className)} direction="Column" {...props} ref={ref}>
|
||||||
<Header className={css.PdfViewerHeader} size="400">
|
<Header className={css.PdfViewerHeader} size="400">
|
||||||
@@ -187,15 +193,16 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
|||||||
</Chip>
|
</Chip>
|
||||||
<Box grow="Yes" justifyContent="Center" alignItems="Center" gap="200">
|
<Box grow="Yes" justifyContent="Center" alignItems="Center" gap="200">
|
||||||
<PopOut
|
<PopOut
|
||||||
open={openJump}
|
anchor={jumpAnchor}
|
||||||
align="Center"
|
align="Center"
|
||||||
position="Top"
|
position="Top"
|
||||||
content={
|
content={
|
||||||
<FocusTrap
|
<FocusTrap
|
||||||
focusTrapOptions={{
|
focusTrapOptions={{
|
||||||
initialFocus: false,
|
initialFocus: false,
|
||||||
onDeactivate: () => setOpenJump(false),
|
onDeactivate: () => setJumpAnchor(undefined),
|
||||||
clickOutsideDeactivates: true,
|
clickOutsideDeactivates: true,
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Menu variant="Surface">
|
<Menu variant="Surface">
|
||||||
@@ -227,17 +234,14 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
|||||||
</FocusTrap>
|
</FocusTrap>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{(anchorRef) => (
|
<Chip
|
||||||
<Chip
|
onClick={handleOpenJump}
|
||||||
onClick={() => setOpenJump(!openJump)}
|
variant="SurfaceVariant"
|
||||||
ref={anchorRef}
|
radii="300"
|
||||||
variant="SurfaceVariant"
|
aria-pressed={jumpAnchor !== undefined}
|
||||||
radii="300"
|
>
|
||||||
aria-pressed={openJump}
|
<Text size="B300">{`${pageNo}/${docState.data.numPages}`}</Text>
|
||||||
>
|
</Chip>
|
||||||
<Text size="B300">{`${pageNo}/${docState.data.numPages}`}</Text>
|
|
||||||
</Chip>
|
|
||||||
)}
|
|
||||||
</PopOut>
|
</PopOut>
|
||||||
</Box>
|
</Box>
|
||||||
<Chip
|
<Chip
|
||||||
|
|||||||
271
src/app/components/RenderMessageContent.tsx
Normal file
271
src/app/components/RenderMessageContent.tsx
Normal file
@@ -0,0 +1,271 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { MsgType } from 'matrix-js-sdk';
|
||||||
|
import { HTMLReactParserOptions } from 'html-react-parser';
|
||||||
|
import { Opts } from 'linkifyjs';
|
||||||
|
import {
|
||||||
|
AudioContent,
|
||||||
|
DownloadFile,
|
||||||
|
FileContent,
|
||||||
|
ImageContent,
|
||||||
|
MAudio,
|
||||||
|
MBadEncrypted,
|
||||||
|
MEmote,
|
||||||
|
MFile,
|
||||||
|
MImage,
|
||||||
|
MLocation,
|
||||||
|
MNotice,
|
||||||
|
MText,
|
||||||
|
MVideo,
|
||||||
|
ReadPdfFile,
|
||||||
|
ReadTextFile,
|
||||||
|
RenderBody,
|
||||||
|
ThumbnailContent,
|
||||||
|
UnsupportedContent,
|
||||||
|
VideoContent,
|
||||||
|
} from './message';
|
||||||
|
import { UrlPreviewCard, UrlPreviewHolder } from './url-preview';
|
||||||
|
import { Image, MediaControl, Video } from './media';
|
||||||
|
import { ImageViewer } from './image-viewer';
|
||||||
|
import { PdfViewer } from './Pdf-viewer';
|
||||||
|
import { TextViewer } from './text-viewer';
|
||||||
|
import { testMatrixTo } from '../plugins/matrix-to';
|
||||||
|
import {IImageContent} from "../../types/matrix/common";
|
||||||
|
|
||||||
|
type RenderMessageContentProps = {
|
||||||
|
displayName: string;
|
||||||
|
msgType: string;
|
||||||
|
ts: number;
|
||||||
|
edited?: boolean;
|
||||||
|
getContent: <T>() => T;
|
||||||
|
mediaAutoLoad?: boolean;
|
||||||
|
urlPreview?: boolean;
|
||||||
|
highlightRegex?: RegExp;
|
||||||
|
htmlReactParserOptions: HTMLReactParserOptions;
|
||||||
|
linkifyOpts: Opts;
|
||||||
|
outlineAttachment?: boolean;
|
||||||
|
};
|
||||||
|
export function RenderMessageContent({
|
||||||
|
displayName,
|
||||||
|
msgType,
|
||||||
|
ts,
|
||||||
|
edited,
|
||||||
|
getContent,
|
||||||
|
mediaAutoLoad,
|
||||||
|
urlPreview,
|
||||||
|
highlightRegex,
|
||||||
|
htmlReactParserOptions,
|
||||||
|
linkifyOpts,
|
||||||
|
outlineAttachment,
|
||||||
|
}: RenderMessageContentProps) {
|
||||||
|
const renderUrlsPreview = (urls: string[]) => {
|
||||||
|
const filteredUrls = urls.filter((url) => !testMatrixTo(url));
|
||||||
|
if (filteredUrls.length === 0) return undefined;
|
||||||
|
return (
|
||||||
|
<UrlPreviewHolder>
|
||||||
|
{filteredUrls.map((url) => (
|
||||||
|
<UrlPreviewCard key={url} url={url} ts={ts} />
|
||||||
|
))}
|
||||||
|
</UrlPreviewHolder>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
const renderCaption = () => {
|
||||||
|
const content: IImageContent = getContent();
|
||||||
|
if(content.filename && content.filename !== content.body) {
|
||||||
|
return (
|
||||||
|
<MText
|
||||||
|
edited={edited}
|
||||||
|
content={content}
|
||||||
|
renderBody={(props) => (
|
||||||
|
<RenderBody
|
||||||
|
{...props}
|
||||||
|
highlightRegex={highlightRegex}
|
||||||
|
htmlReactParserOptions={htmlReactParserOptions}
|
||||||
|
linkifyOpts={linkifyOpts}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderFile = () => (
|
||||||
|
<>
|
||||||
|
<MFile
|
||||||
|
content={getContent()}
|
||||||
|
renderFileContent={({ body, mimeType, info, encInfo, url }) => (
|
||||||
|
<FileContent
|
||||||
|
body={body}
|
||||||
|
mimeType={mimeType}
|
||||||
|
renderAsPdfFile={() => (
|
||||||
|
<ReadPdfFile
|
||||||
|
body={body}
|
||||||
|
mimeType={mimeType}
|
||||||
|
url={url}
|
||||||
|
encInfo={encInfo}
|
||||||
|
renderViewer={(p) => <PdfViewer {...p} />}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
renderAsTextFile={() => (
|
||||||
|
<ReadTextFile
|
||||||
|
body={body}
|
||||||
|
mimeType={mimeType}
|
||||||
|
url={url}
|
||||||
|
encInfo={encInfo}
|
||||||
|
renderViewer={(p) => <TextViewer {...p} />}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<DownloadFile body={body} mimeType={mimeType} url={url} encInfo={encInfo} info={info} />
|
||||||
|
</FileContent>
|
||||||
|
|
||||||
|
)}
|
||||||
|
outlined={outlineAttachment}
|
||||||
|
/>
|
||||||
|
{renderCaption()}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (msgType === MsgType.Text) {
|
||||||
|
return (
|
||||||
|
<MText
|
||||||
|
edited={edited}
|
||||||
|
content={getContent()}
|
||||||
|
renderBody={(props) => (
|
||||||
|
<RenderBody
|
||||||
|
{...props}
|
||||||
|
highlightRegex={highlightRegex}
|
||||||
|
htmlReactParserOptions={htmlReactParserOptions}
|
||||||
|
linkifyOpts={linkifyOpts}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === MsgType.Emote) {
|
||||||
|
return (
|
||||||
|
<MEmote
|
||||||
|
displayName={displayName}
|
||||||
|
edited={edited}
|
||||||
|
content={getContent()}
|
||||||
|
renderBody={(props) => (
|
||||||
|
<RenderBody
|
||||||
|
{...props}
|
||||||
|
highlightRegex={highlightRegex}
|
||||||
|
htmlReactParserOptions={htmlReactParserOptions}
|
||||||
|
linkifyOpts={linkifyOpts}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === MsgType.Notice) {
|
||||||
|
return (
|
||||||
|
<MNotice
|
||||||
|
edited={edited}
|
||||||
|
content={getContent()}
|
||||||
|
renderBody={(props) => (
|
||||||
|
<RenderBody
|
||||||
|
{...props}
|
||||||
|
highlightRegex={highlightRegex}
|
||||||
|
htmlReactParserOptions={htmlReactParserOptions}
|
||||||
|
linkifyOpts={linkifyOpts}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === MsgType.Image) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<MImage
|
||||||
|
content={getContent()}
|
||||||
|
renderImageContent={(props) => (
|
||||||
|
<ImageContent
|
||||||
|
{...props}
|
||||||
|
autoPlay={mediaAutoLoad}
|
||||||
|
renderImage={(p) => <Image {...p} loading="lazy" />}
|
||||||
|
renderViewer={(p) => <ImageViewer {...p} />}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
outlined={outlineAttachment}
|
||||||
|
/>
|
||||||
|
{renderCaption()}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === MsgType.Video) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<MVideo
|
||||||
|
content={getContent()}
|
||||||
|
renderAsFile={renderFile}
|
||||||
|
renderVideoContent={({ body, info, mimeType, url, encInfo }) => (
|
||||||
|
<VideoContent
|
||||||
|
body={body}
|
||||||
|
info={info}
|
||||||
|
mimeType={mimeType}
|
||||||
|
url={url}
|
||||||
|
encInfo={encInfo}
|
||||||
|
renderThumbnail={
|
||||||
|
mediaAutoLoad
|
||||||
|
? () => (
|
||||||
|
<ThumbnailContent
|
||||||
|
info={info}
|
||||||
|
renderImage={(src) => (
|
||||||
|
<Image alt={body} title={body} src={src} loading="lazy" />
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
renderVideo={(p) => <Video {...p} />}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
outlined={outlineAttachment}
|
||||||
|
/>
|
||||||
|
{renderCaption()}
|
||||||
|
</>
|
||||||
|
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === MsgType.Audio) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<MAudio
|
||||||
|
content={getContent()}
|
||||||
|
renderAsFile={renderFile}
|
||||||
|
renderAudioContent={(props) => (
|
||||||
|
<AudioContent {...props} renderMediaControl={(p) => <MediaControl {...p} />} />
|
||||||
|
)}
|
||||||
|
outlined={outlineAttachment}
|
||||||
|
/>
|
||||||
|
{renderCaption()}
|
||||||
|
</>
|
||||||
|
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === MsgType.File) {
|
||||||
|
return renderFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === MsgType.Location) {
|
||||||
|
return <MLocation content={getContent()} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msgType === 'm.bad.encrypted') {
|
||||||
|
return <MBadEncrypted />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <UnsupportedContent />;
|
||||||
|
}
|
||||||
90
src/app/components/RoomSummaryLoader.tsx
Normal file
90
src/app/components/RoomSummaryLoader.tsx
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
import { ReactNode, useCallback, useState } from 'react';
|
||||||
|
import { MatrixClient, Room } from 'matrix-js-sdk';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
import { LocalRoomSummary, useLocalRoomSummary } from '../hooks/useLocalRoomSummary';
|
||||||
|
import { AsyncState, AsyncStatus } from '../hooks/useAsyncCallback';
|
||||||
|
|
||||||
|
export type IRoomSummary = Awaited<ReturnType<MatrixClient['getRoomSummary']>>;
|
||||||
|
|
||||||
|
type RoomSummaryLoaderProps = {
|
||||||
|
roomIdOrAlias: string;
|
||||||
|
children: (roomSummary?: IRoomSummary) => ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function RoomSummaryLoader({ roomIdOrAlias, children }: RoomSummaryLoaderProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const fetchSummary = useCallback(() => mx.getRoomSummary(roomIdOrAlias), [mx, roomIdOrAlias]);
|
||||||
|
|
||||||
|
const { data } = useQuery({
|
||||||
|
queryKey: [roomIdOrAlias, `summary`],
|
||||||
|
queryFn: fetchSummary,
|
||||||
|
});
|
||||||
|
|
||||||
|
return children(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LocalRoomSummaryLoader({
|
||||||
|
room,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
room: Room;
|
||||||
|
children: (roomSummary: LocalRoomSummary) => ReactNode;
|
||||||
|
}) {
|
||||||
|
const summary = useLocalRoomSummary(room);
|
||||||
|
|
||||||
|
return children(summary);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function HierarchyRoomSummaryLoader({
|
||||||
|
roomId,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
roomId: string;
|
||||||
|
children: (state: AsyncState<IHierarchyRoom, Error>) => ReactNode;
|
||||||
|
}) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const fetchSummary = useCallback(() => mx.getRoomHierarchy(roomId, 1, 1), [mx, roomId]);
|
||||||
|
const [errorMemo, setError] = useState<Error>();
|
||||||
|
|
||||||
|
const { data, error } = useQuery({
|
||||||
|
queryKey: [roomId, `hierarchy`],
|
||||||
|
queryFn: fetchSummary,
|
||||||
|
retryOnMount: false,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
retry: (failureCount, err) => {
|
||||||
|
setError(err);
|
||||||
|
if (failureCount > 3) return false;
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let state: AsyncState<IHierarchyRoom, Error> = {
|
||||||
|
status: AsyncStatus.Loading,
|
||||||
|
};
|
||||||
|
if (error) {
|
||||||
|
state = {
|
||||||
|
status: AsyncStatus.Error,
|
||||||
|
error,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (errorMemo) {
|
||||||
|
state = {
|
||||||
|
status: AsyncStatus.Error,
|
||||||
|
error: errorMemo,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = data?.rooms[0] ?? undefined;
|
||||||
|
if (summary) {
|
||||||
|
state = {
|
||||||
|
status: AsyncStatus.Success,
|
||||||
|
data: summary,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return children(state);
|
||||||
|
}
|
||||||
24
src/app/components/RoomUnreadProvider.tsx
Normal file
24
src/app/components/RoomUnreadProvider.tsx
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { ReactElement } from 'react';
|
||||||
|
import { Unread } from '../../types/matrix/room';
|
||||||
|
import { useRoomUnread, useRoomsUnread } from '../state/hooks/unread';
|
||||||
|
import { roomToUnreadAtom } from '../state/room/roomToUnread';
|
||||||
|
|
||||||
|
type RoomUnreadProviderProps = {
|
||||||
|
roomId: string;
|
||||||
|
children: (unread?: Unread) => ReactElement;
|
||||||
|
};
|
||||||
|
export function RoomUnreadProvider({ roomId, children }: RoomUnreadProviderProps) {
|
||||||
|
const unread = useRoomUnread(roomId, roomToUnreadAtom);
|
||||||
|
|
||||||
|
return children(unread);
|
||||||
|
}
|
||||||
|
|
||||||
|
type RoomsUnreadProviderProps = {
|
||||||
|
rooms: string[];
|
||||||
|
children: (unread?: Unread) => ReactElement;
|
||||||
|
};
|
||||||
|
export function RoomsUnreadProvider({ rooms, children }: RoomsUnreadProviderProps) {
|
||||||
|
const unread = useRoomsUnread(rooms, roomToUnreadAtom);
|
||||||
|
|
||||||
|
return children(unread);
|
||||||
|
}
|
||||||
200
src/app/components/SecretStorage.tsx
Normal file
200
src/app/components/SecretStorage.tsx
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
import React, { FormEventHandler, useCallback } from 'react';
|
||||||
|
import { Box, Text, Button, Spinner, color } from 'folds';
|
||||||
|
import { decodeRecoveryKey } from 'matrix-js-sdk/lib/crypto-api';
|
||||||
|
import { deriveKey } from 'matrix-js-sdk/lib/crypto/key_passphrase';
|
||||||
|
import { PasswordInput } from './password-input';
|
||||||
|
import {
|
||||||
|
SecretStorageKeyContent,
|
||||||
|
SecretStoragePassphraseContent,
|
||||||
|
} from '../../types/matrix/accountData';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
import { useAlive } from '../hooks/useAlive';
|
||||||
|
|
||||||
|
type SecretStorageRecoveryPassphraseProps = {
|
||||||
|
processing?: boolean;
|
||||||
|
keyContent: SecretStorageKeyContent;
|
||||||
|
passphraseContent: SecretStoragePassphraseContent;
|
||||||
|
onDecodedRecoveryKey: (recoveryKey: Uint8Array) => void;
|
||||||
|
};
|
||||||
|
export function SecretStorageRecoveryPassphrase({
|
||||||
|
processing,
|
||||||
|
keyContent,
|
||||||
|
passphraseContent,
|
||||||
|
onDecodedRecoveryKey,
|
||||||
|
}: SecretStorageRecoveryPassphraseProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const alive = useAlive();
|
||||||
|
|
||||||
|
const [driveKeyState, submitPassphrase] = useAsyncCallback<
|
||||||
|
Uint8Array,
|
||||||
|
Error,
|
||||||
|
Parameters<typeof deriveKey>
|
||||||
|
>(
|
||||||
|
useCallback(
|
||||||
|
async (passphrase, salt, iterations, bits) => {
|
||||||
|
const decodedRecoveryKey = await deriveKey(passphrase, salt, iterations, bits);
|
||||||
|
|
||||||
|
const match = await mx.secretStorage.checkKey(decodedRecoveryKey, keyContent as any);
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
throw new Error('Invalid recovery passphrase.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return decodedRecoveryKey;
|
||||||
|
},
|
||||||
|
[mx, keyContent]
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const drivingKey = driveKeyState.status === AsyncStatus.Loading;
|
||||||
|
const loading = drivingKey || processing;
|
||||||
|
|
||||||
|
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
|
||||||
|
if (loading) return;
|
||||||
|
evt.preventDefault();
|
||||||
|
|
||||||
|
const target = evt.target as HTMLFormElement | undefined;
|
||||||
|
const recoveryPassphraseInput = target?.recoveryPassphraseInput as HTMLInputElement | undefined;
|
||||||
|
if (!recoveryPassphraseInput) return;
|
||||||
|
const recoveryPassphrase = recoveryPassphraseInput.value.trim();
|
||||||
|
if (!recoveryPassphrase) return;
|
||||||
|
|
||||||
|
const { salt, iterations, bits } = passphraseContent;
|
||||||
|
submitPassphrase(recoveryPassphrase, salt, iterations, bits).then((decodedRecoveryKey) => {
|
||||||
|
if (alive()) {
|
||||||
|
recoveryPassphraseInput.value = '';
|
||||||
|
onDecodedRecoveryKey(decodedRecoveryKey);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box as="form" onSubmit={handleSubmit} direction="Column" gap="100">
|
||||||
|
<Box gap="200" alignItems="End">
|
||||||
|
<Box grow="Yes" direction="Column" gap="100">
|
||||||
|
<Text size="L400">Recovery Passphrase</Text>
|
||||||
|
<PasswordInput
|
||||||
|
name="recoveryPassphraseInput"
|
||||||
|
size="400"
|
||||||
|
variant="Secondary"
|
||||||
|
radii="300"
|
||||||
|
autoFocus
|
||||||
|
required
|
||||||
|
outlined
|
||||||
|
readOnly={loading}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Box shrink="No" gap="200">
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="Success"
|
||||||
|
size="400"
|
||||||
|
radii="300"
|
||||||
|
disabled={loading}
|
||||||
|
before={loading && <Spinner size="200" variant="Success" fill="Solid" />}
|
||||||
|
>
|
||||||
|
<Text as="span" size="B400">
|
||||||
|
Verify
|
||||||
|
</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
{driveKeyState.status === AsyncStatus.Error && (
|
||||||
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
|
<b>{driveKeyState.error.message}</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type SecretStorageRecoveryKeyProps = {
|
||||||
|
processing?: boolean;
|
||||||
|
keyContent: SecretStorageKeyContent;
|
||||||
|
onDecodedRecoveryKey: (recoveryKey: Uint8Array) => void;
|
||||||
|
};
|
||||||
|
export function SecretStorageRecoveryKey({
|
||||||
|
processing,
|
||||||
|
keyContent,
|
||||||
|
onDecodedRecoveryKey,
|
||||||
|
}: SecretStorageRecoveryKeyProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const alive = useAlive();
|
||||||
|
|
||||||
|
const [driveKeyState, submitRecoveryKey] = useAsyncCallback<Uint8Array, Error, [string]>(
|
||||||
|
useCallback(
|
||||||
|
async (recoveryKey) => {
|
||||||
|
const decodedRecoveryKey = decodeRecoveryKey(recoveryKey);
|
||||||
|
|
||||||
|
const match = await mx.secretStorage.checkKey(decodedRecoveryKey, keyContent as any);
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
throw new Error('Invalid recovery key.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return decodedRecoveryKey;
|
||||||
|
},
|
||||||
|
[mx, keyContent]
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const drivingKey = driveKeyState.status === AsyncStatus.Loading;
|
||||||
|
const loading = drivingKey || processing;
|
||||||
|
|
||||||
|
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
|
||||||
|
evt.preventDefault();
|
||||||
|
|
||||||
|
const target = evt.target as HTMLFormElement | undefined;
|
||||||
|
const recoveryKeyInput = target?.recoveryKeyInput as HTMLInputElement | undefined;
|
||||||
|
if (!recoveryKeyInput) return;
|
||||||
|
const recoveryKey = recoveryKeyInput.value.trim();
|
||||||
|
if (!recoveryKey) return;
|
||||||
|
|
||||||
|
submitRecoveryKey(recoveryKey).then((decodedRecoveryKey) => {
|
||||||
|
if (alive()) {
|
||||||
|
recoveryKeyInput.value = '';
|
||||||
|
onDecodedRecoveryKey(decodedRecoveryKey);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box as="form" onSubmit={handleSubmit} direction="Column" gap="100">
|
||||||
|
<Box gap="200" alignItems="End">
|
||||||
|
<Box grow="Yes" direction="Column" gap="100">
|
||||||
|
<Text size="L400">Recovery Key</Text>
|
||||||
|
<PasswordInput
|
||||||
|
name="recoveryKeyInput"
|
||||||
|
size="400"
|
||||||
|
variant="Secondary"
|
||||||
|
radii="300"
|
||||||
|
autoFocus
|
||||||
|
required
|
||||||
|
outlined
|
||||||
|
readOnly={loading}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Box shrink="No" gap="200">
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="Success"
|
||||||
|
size="400"
|
||||||
|
radii="300"
|
||||||
|
disabled={loading}
|
||||||
|
before={loading && <Spinner size="200" variant="Success" fill="Solid" />}
|
||||||
|
>
|
||||||
|
<Text as="span" size="B400">
|
||||||
|
Verify
|
||||||
|
</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
{driveKeyState.status === AsyncStatus.Error && (
|
||||||
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
|
<b>{driveKeyState.error.message}</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
28
src/app/components/SpaceChildDirectsProvider.tsx
Normal file
28
src/app/components/SpaceChildDirectsProvider.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { ReactNode } from 'react';
|
||||||
|
import { RoomToParents } from '../../types/matrix/room';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
import { allRoomsAtom } from '../state/room-list/roomList';
|
||||||
|
import { useChildDirectScopeFactory, useSpaceChildren } from '../state/hooks/roomList';
|
||||||
|
|
||||||
|
type SpaceChildDirectsProviderProps = {
|
||||||
|
spaceId: string;
|
||||||
|
mDirects: Set<string>;
|
||||||
|
roomToParents: RoomToParents;
|
||||||
|
children: (rooms: string[]) => ReactNode;
|
||||||
|
};
|
||||||
|
export function SpaceChildDirectsProvider({
|
||||||
|
spaceId,
|
||||||
|
roomToParents,
|
||||||
|
mDirects,
|
||||||
|
children,
|
||||||
|
}: SpaceChildDirectsProviderProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const childDirects = useSpaceChildren(
|
||||||
|
allRoomsAtom,
|
||||||
|
spaceId,
|
||||||
|
useChildDirectScopeFactory(mx, mDirects, roomToParents)
|
||||||
|
);
|
||||||
|
|
||||||
|
return children(childDirects);
|
||||||
|
}
|
||||||
28
src/app/components/SpaceChildRoomsProvider.tsx
Normal file
28
src/app/components/SpaceChildRoomsProvider.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { ReactNode } from 'react';
|
||||||
|
import { RoomToParents } from '../../types/matrix/room';
|
||||||
|
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||||
|
import { allRoomsAtom } from '../state/room-list/roomList';
|
||||||
|
import { useChildRoomScopeFactory, useSpaceChildren } from '../state/hooks/roomList';
|
||||||
|
|
||||||
|
type SpaceChildRoomsProviderProps = {
|
||||||
|
spaceId: string;
|
||||||
|
mDirects: Set<string>;
|
||||||
|
roomToParents: RoomToParents;
|
||||||
|
children: (rooms: string[]) => ReactNode;
|
||||||
|
};
|
||||||
|
export function SpaceChildRoomsProvider({
|
||||||
|
spaceId,
|
||||||
|
roomToParents,
|
||||||
|
mDirects,
|
||||||
|
children,
|
||||||
|
}: SpaceChildRoomsProviderProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const childRooms = useSpaceChildren(
|
||||||
|
allRoomsAtom,
|
||||||
|
spaceId,
|
||||||
|
useChildRoomScopeFactory(mx, mDirects, roomToParents)
|
||||||
|
);
|
||||||
|
|
||||||
|
return children(childRooms);
|
||||||
|
}
|
||||||
43
src/app/components/SpecVersionsLoader.tsx
Normal file
43
src/app/components/SpecVersionsLoader.tsx
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import { ReactNode, useCallback, useEffect, useState } from 'react';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
|
||||||
|
import { SpecVersions, specVersions } from '../cs-api';
|
||||||
|
|
||||||
|
type SpecVersionsLoaderProps = {
|
||||||
|
baseUrl: string;
|
||||||
|
fallback?: () => ReactNode;
|
||||||
|
error?: (err: unknown, retry: () => void, ignore: () => void) => ReactNode;
|
||||||
|
children: (versions: SpecVersions) => ReactNode;
|
||||||
|
};
|
||||||
|
export function SpecVersionsLoader({
|
||||||
|
baseUrl,
|
||||||
|
fallback,
|
||||||
|
error,
|
||||||
|
children,
|
||||||
|
}: SpecVersionsLoaderProps) {
|
||||||
|
const [state, load] = useAsyncCallback(
|
||||||
|
useCallback(() => specVersions(fetch, baseUrl), [baseUrl])
|
||||||
|
);
|
||||||
|
const [ignoreError, setIgnoreError] = useState(false);
|
||||||
|
|
||||||
|
const ignoreCallback = useCallback(() => setIgnoreError(true), []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
if (state.status === AsyncStatus.Idle || state.status === AsyncStatus.Loading) {
|
||||||
|
return fallback?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ignoreError && state.status === AsyncStatus.Error) {
|
||||||
|
return error?.(state.error, load, ignoreCallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
return children(
|
||||||
|
state.status === AsyncStatus.Success
|
||||||
|
? state.data
|
||||||
|
: {
|
||||||
|
versions: [],
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
17
src/app/components/SupportedUIAFlowsLoader.tsx
Normal file
17
src/app/components/SupportedUIAFlowsLoader.tsx
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { ReactNode } from 'react';
|
||||||
|
import { UIAFlow } from 'matrix-js-sdk';
|
||||||
|
import { useSupportedUIAFlows } from '../hooks/useUIAFlows';
|
||||||
|
|
||||||
|
export function SupportedUIAFlowsLoader({
|
||||||
|
flows,
|
||||||
|
supportedStages,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
supportedStages: string[];
|
||||||
|
flows: UIAFlow[];
|
||||||
|
children: (supportedFlows: UIAFlow[]) => ReactNode;
|
||||||
|
}) {
|
||||||
|
const supportedFlows = useSupportedUIAFlows(flows, supportedStages);
|
||||||
|
|
||||||
|
return children(supportedFlows);
|
||||||
|
}
|
||||||
72
src/app/components/UIAFlowOverlay.tsx
Normal file
72
src/app/components/UIAFlowOverlay.tsx
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import React, { ReactNode } from 'react';
|
||||||
|
import {
|
||||||
|
Overlay,
|
||||||
|
OverlayBackdrop,
|
||||||
|
Box,
|
||||||
|
config,
|
||||||
|
Text,
|
||||||
|
TooltipProvider,
|
||||||
|
Tooltip,
|
||||||
|
Icons,
|
||||||
|
Icon,
|
||||||
|
Chip,
|
||||||
|
IconButton,
|
||||||
|
} from 'folds';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
|
||||||
|
export type UIAFlowOverlayProps = {
|
||||||
|
currentStep: number;
|
||||||
|
stepCount: number;
|
||||||
|
children: ReactNode;
|
||||||
|
onCancel: () => void;
|
||||||
|
};
|
||||||
|
export function UIAFlowOverlay({
|
||||||
|
currentStep,
|
||||||
|
stepCount,
|
||||||
|
children,
|
||||||
|
onCancel,
|
||||||
|
}: UIAFlowOverlayProps) {
|
||||||
|
return (
|
||||||
|
<Overlay open backdrop={<OverlayBackdrop />}>
|
||||||
|
<FocusTrap focusTrapOptions={{ initialFocus: false, escapeDeactivates: false }}>
|
||||||
|
<Box style={{ height: '100%' }} direction="Column" grow="Yes" gap="400">
|
||||||
|
<Box grow="Yes" direction="Column" alignItems="Center" justifyContent="Center">
|
||||||
|
{children}
|
||||||
|
</Box>
|
||||||
|
<Box
|
||||||
|
style={{ padding: config.space.S200 }}
|
||||||
|
shrink="No"
|
||||||
|
justifyContent="Center"
|
||||||
|
alignItems="Center"
|
||||||
|
gap="200"
|
||||||
|
>
|
||||||
|
<Chip as="div" radii="Pill" outlined>
|
||||||
|
<Text as="span" size="T300">{`Step ${currentStep}/${stepCount}`}</Text>
|
||||||
|
</Chip>
|
||||||
|
<TooltipProvider
|
||||||
|
tooltip={
|
||||||
|
<Tooltip variant="Critical">
|
||||||
|
<Text>Exit</Text>
|
||||||
|
</Tooltip>
|
||||||
|
}
|
||||||
|
position="Top"
|
||||||
|
>
|
||||||
|
{(anchorRef) => (
|
||||||
|
<IconButton
|
||||||
|
ref={anchorRef}
|
||||||
|
variant="Critical"
|
||||||
|
size="300"
|
||||||
|
onClick={onCancel}
|
||||||
|
radii="Pill"
|
||||||
|
outlined
|
||||||
|
>
|
||||||
|
<Icon size="50" src={Icons.Cross} />
|
||||||
|
</IconButton>
|
||||||
|
)}
|
||||||
|
</TooltipProvider>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</FocusTrap>
|
||||||
|
</Overlay>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
|
|
||||||
import { CustomEditor, useEditor } from './Editor';
|
import { CustomEditor, useEditor } from './Editor';
|
||||||
import { Toolbar } from './Toolbar';
|
import { Toolbar } from './Toolbar';
|
||||||
|
import { stopPropagation } from '../../utils/keyboard';
|
||||||
|
|
||||||
export function EditorPreview() {
|
export function EditorPreview() {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
@@ -32,6 +33,7 @@ export function EditorPreview() {
|
|||||||
initialFocus: false,
|
initialFocus: false,
|
||||||
onDeactivate: () => setOpen(false),
|
onDeactivate: () => setOpen(false),
|
||||||
clickOutsideDeactivates: true,
|
clickOutsideDeactivates: true,
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Modal size="500">
|
<Modal size="500">
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import { CommandElement, EmoticonElement, LinkElement, MentionElement } from './
|
|||||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
import { getBeginCommand } from './utils';
|
import { getBeginCommand } from './utils';
|
||||||
import { BlockType } from './types';
|
import { BlockType } from './types';
|
||||||
|
import { mxcUrlToHttp } from '../../utils/matrix';
|
||||||
|
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||||
|
|
||||||
// Put this at the start and end of an inline component to work around this Chromium bug:
|
// Put this at the start and end of an inline component to work around this Chromium bug:
|
||||||
// https://bugs.chromium.org/p/chromium/issues/detail?id=1249405
|
// https://bugs.chromium.org/p/chromium/issues/detail?id=1249405
|
||||||
@@ -76,6 +78,7 @@ function RenderEmoticonElement({
|
|||||||
children,
|
children,
|
||||||
}: { element: EmoticonElement } & RenderElementProps) {
|
}: { element: EmoticonElement } & RenderElementProps) {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
|
const useAuthentication = useMediaAuthentication();
|
||||||
const selected = useSelected();
|
const selected = useSelected();
|
||||||
const focused = useFocused();
|
const focused = useFocused();
|
||||||
|
|
||||||
@@ -90,7 +93,7 @@ function RenderEmoticonElement({
|
|||||||
{element.key.startsWith('mxc://') ? (
|
{element.key.startsWith('mxc://') ? (
|
||||||
<img
|
<img
|
||||||
className={css.EmoticonImg}
|
className={css.EmoticonImg}
|
||||||
src={mx.mxcUrlToHttp(element.key) ?? element.key}
|
src={mxcUrlToHttp(mx, element.key, useAuthentication) ?? element.key}
|
||||||
alt={element.shortcode}
|
alt={element.shortcode}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -10,13 +10,14 @@ import {
|
|||||||
Line,
|
Line,
|
||||||
Menu,
|
Menu,
|
||||||
PopOut,
|
PopOut,
|
||||||
|
RectCords,
|
||||||
Scroll,
|
Scroll,
|
||||||
Text,
|
Text,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
TooltipProvider,
|
TooltipProvider,
|
||||||
toRem,
|
toRem,
|
||||||
} from 'folds';
|
} from 'folds';
|
||||||
import React, { ReactNode, useState } from 'react';
|
import React, { MouseEventHandler, ReactNode, useState } from 'react';
|
||||||
import { ReactEditor, useSlate } from 'slate-react';
|
import { ReactEditor, useSlate } from 'slate-react';
|
||||||
import {
|
import {
|
||||||
headingLevel,
|
headingLevel,
|
||||||
@@ -34,6 +35,7 @@ import { isMacOS } from '../../utils/user-agent';
|
|||||||
import { KeySymbol } from '../../utils/key-symbol';
|
import { KeySymbol } from '../../utils/key-symbol';
|
||||||
import { useSetting } from '../../state/hooks/settings';
|
import { useSetting } from '../../state/hooks/settings';
|
||||||
import { settingsAtom } from '../../state/settings';
|
import { settingsAtom } from '../../state/settings';
|
||||||
|
import { stopPropagation } from '../../utils/keyboard';
|
||||||
|
|
||||||
function BtnTooltip({ text, shortCode }: { text: string; shortCode?: string }) {
|
function BtnTooltip({ text, shortCode }: { text: string; shortCode?: string }) {
|
||||||
return (
|
return (
|
||||||
@@ -119,30 +121,38 @@ export function BlockButton({ format, icon, tooltip }: BlockButtonProps) {
|
|||||||
export function HeadingBlockButton() {
|
export function HeadingBlockButton() {
|
||||||
const editor = useSlate();
|
const editor = useSlate();
|
||||||
const level = headingLevel(editor);
|
const level = headingLevel(editor);
|
||||||
const [open, setOpen] = useState(false);
|
const [anchor, setAnchor] = useState<RectCords>();
|
||||||
const isActive = isBlockActive(editor, BlockType.Heading);
|
const isActive = isBlockActive(editor, BlockType.Heading);
|
||||||
const modKey = isMacOS() ? KeySymbol.Command : 'Ctrl';
|
const modKey = isMacOS() ? KeySymbol.Command : 'Ctrl';
|
||||||
|
|
||||||
const handleMenuSelect = (selectedLevel: HeadingLevel) => {
|
const handleMenuSelect = (selectedLevel: HeadingLevel) => {
|
||||||
setOpen(false);
|
setAnchor(undefined);
|
||||||
toggleBlock(editor, BlockType.Heading, { level: selectedLevel });
|
toggleBlock(editor, BlockType.Heading, { level: selectedLevel });
|
||||||
ReactEditor.focus(editor);
|
ReactEditor.focus(editor);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleMenuOpen: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
||||||
|
if (isActive) {
|
||||||
|
toggleBlock(editor, BlockType.Heading);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setAnchor(evt.currentTarget.getBoundingClientRect());
|
||||||
|
};
|
||||||
return (
|
return (
|
||||||
<PopOut
|
<PopOut
|
||||||
open={open}
|
anchor={anchor}
|
||||||
offset={5}
|
offset={5}
|
||||||
position="Top"
|
position="Top"
|
||||||
content={
|
content={
|
||||||
<FocusTrap
|
<FocusTrap
|
||||||
focusTrapOptions={{
|
focusTrapOptions={{
|
||||||
initialFocus: false,
|
initialFocus: false,
|
||||||
onDeactivate: () => setOpen(false),
|
onDeactivate: () => setAnchor(undefined),
|
||||||
clickOutsideDeactivates: true,
|
clickOutsideDeactivates: true,
|
||||||
isKeyForward: (evt: KeyboardEvent) =>
|
isKeyForward: (evt: KeyboardEvent) =>
|
||||||
evt.key === 'ArrowDown' || evt.key === 'ArrowRight',
|
evt.key === 'ArrowDown' || evt.key === 'ArrowRight',
|
||||||
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp' || evt.key === 'ArrowLeft',
|
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp' || evt.key === 'ArrowLeft',
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Menu style={{ padding: config.space.S100 }}>
|
<Menu style={{ padding: config.space.S100 }}>
|
||||||
@@ -197,20 +207,17 @@ export function HeadingBlockButton() {
|
|||||||
</FocusTrap>
|
</FocusTrap>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{(ref) => (
|
<IconButton
|
||||||
<IconButton
|
style={{ width: 'unset' }}
|
||||||
style={{ width: 'unset' }}
|
variant="SurfaceVariant"
|
||||||
ref={ref}
|
onClick={handleMenuOpen}
|
||||||
variant="SurfaceVariant"
|
aria-pressed={isActive}
|
||||||
onClick={() => (isActive ? toggleBlock(editor, BlockType.Heading) : setOpen(!open))}
|
size="400"
|
||||||
aria-pressed={isActive}
|
radii="300"
|
||||||
size="400"
|
>
|
||||||
radii="300"
|
<Icon size="200" src={level ? Icons[`Heading${level}`] : Icons.Heading1} />
|
||||||
>
|
<Icon size="200" src={isActive ? Icons.Cross : Icons.ChevronBottom} />
|
||||||
<Icon size="200" src={level ? Icons[`Heading${level}`] : Icons.Heading1} />
|
</IconButton>
|
||||||
<Icon size="200" src={isActive ? Icons.Cross : Icons.ChevronBottom} />
|
|
||||||
</IconButton>
|
|
||||||
)}
|
|
||||||
</PopOut>
|
</PopOut>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -250,7 +257,9 @@ export function Toolbar() {
|
|||||||
const modKey = isMacOS() ? KeySymbol.Command : 'Ctrl';
|
const modKey = isMacOS() ? KeySymbol.Command : 'Ctrl';
|
||||||
const disableInline = isBlockActive(editor, BlockType.CodeBlock);
|
const disableInline = isBlockActive(editor, BlockType.CodeBlock);
|
||||||
|
|
||||||
const canEscape = isAnyMarkActive(editor) || !isBlockActive(editor, BlockType.Paragraph);
|
const canEscape = isBlockActive(editor, BlockType.Paragraph)
|
||||||
|
? isAnyMarkActive(editor)
|
||||||
|
: ReactEditor.isFocused(editor);
|
||||||
const [isMarkdown, setIsMarkdown] = useSetting(settingsAtom, 'isMarkdown');
|
const [isMarkdown, setIsMarkdown] = useSetting(settingsAtom, 'isMarkdown');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { isKeyHotkey } from 'is-hotkey';
|
|||||||
import { Header, Menu, Scroll, config } from 'folds';
|
import { Header, Menu, Scroll, config } from 'folds';
|
||||||
|
|
||||||
import * as css from './AutocompleteMenu.css';
|
import * as css from './AutocompleteMenu.css';
|
||||||
import { preventScrollWithArrowKey } from '../../../utils/keyboard';
|
import { preventScrollWithArrowKey, stopPropagation } from '../../../utils/keyboard';
|
||||||
|
|
||||||
type AutocompleteMenuProps = {
|
type AutocompleteMenuProps = {
|
||||||
requestClose: () => void;
|
requestClose: () => void;
|
||||||
@@ -24,6 +24,7 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
|
|||||||
allowOutsideClick: true,
|
allowOutsideClick: true,
|
||||||
isKeyForward: (evt: KeyboardEvent) => isKeyHotkey('arrowdown', evt),
|
isKeyForward: (evt: KeyboardEvent) => isKeyHotkey('arrowdown', evt),
|
||||||
isKeyBackward: (evt: KeyboardEvent) => isKeyHotkey('arrowup', evt),
|
isKeyBackward: (evt: KeyboardEvent) => isKeyHotkey('arrowup', evt),
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Menu className={css.AutocompleteMenu}>
|
<Menu className={css.AutocompleteMenu}>
|
||||||
|
|||||||
@@ -16,12 +16,14 @@ import { createEmoticonElement, moveCursor, replaceWithElement } from '../utils'
|
|||||||
import { useRecentEmoji } from '../../../hooks/useRecentEmoji';
|
import { useRecentEmoji } from '../../../hooks/useRecentEmoji';
|
||||||
import { useRelevantImagePacks } from '../../../hooks/useImagePacks';
|
import { useRelevantImagePacks } from '../../../hooks/useImagePacks';
|
||||||
import { IEmoji, emojis } from '../../../plugins/emoji';
|
import { IEmoji, emojis } from '../../../plugins/emoji';
|
||||||
import { ExtendedPackImage, PackUsage } from '../../../plugins/custom-emoji';
|
|
||||||
import { useKeyDown } from '../../../hooks/useKeyDown';
|
import { useKeyDown } from '../../../hooks/useKeyDown';
|
||||||
|
import { mxcUrlToHttp } from '../../../utils/matrix';
|
||||||
|
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
|
||||||
|
import { ImageUsage, PackImageReader } from '../../../plugins/custom-emoji';
|
||||||
|
|
||||||
type EmoticonCompleteHandler = (key: string, shortcode: string) => void;
|
type EmoticonCompleteHandler = (key: string, shortcode: string) => void;
|
||||||
|
|
||||||
type EmoticonSearchItem = ExtendedPackImage | IEmoji;
|
type EmoticonSearchItem = PackImageReader | IEmoji;
|
||||||
|
|
||||||
type EmoticonAutocompleteProps = {
|
type EmoticonAutocompleteProps = {
|
||||||
imagePackRooms: Room[];
|
imagePackRooms: Room[];
|
||||||
@@ -48,20 +50,23 @@ export function EmoticonAutocomplete({
|
|||||||
requestClose,
|
requestClose,
|
||||||
}: EmoticonAutocompleteProps) {
|
}: EmoticonAutocompleteProps) {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
|
const useAuthentication = useMediaAuthentication();
|
||||||
|
|
||||||
const imagePacks = useRelevantImagePacks(mx, PackUsage.Emoticon, imagePackRooms);
|
const imagePacks = useRelevantImagePacks(ImageUsage.Emoticon, imagePackRooms);
|
||||||
const recentEmoji = useRecentEmoji(mx, 20);
|
const recentEmoji = useRecentEmoji(mx, 20);
|
||||||
|
|
||||||
const searchList = useMemo(() => {
|
const searchList = useMemo(() => {
|
||||||
const list: Array<EmoticonSearchItem> = [];
|
const list: Array<EmoticonSearchItem> = [];
|
||||||
return list.concat(
|
return list.concat(
|
||||||
imagePacks.flatMap((pack) => pack.getImagesFor(PackUsage.Emoticon)),
|
imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)),
|
||||||
emojis
|
emojis
|
||||||
);
|
);
|
||||||
}, [imagePacks]);
|
}, [imagePacks]);
|
||||||
|
|
||||||
const [result, search, resetSearch] = useAsyncSearch(searchList, getEmoticonStr, SEARCH_OPTIONS);
|
const [result, search, resetSearch] = useAsyncSearch(searchList, getEmoticonStr, SEARCH_OPTIONS);
|
||||||
const autoCompleteEmoticon = result ? result.items : recentEmoji;
|
const autoCompleteEmoticon = (result ? result.items : recentEmoji).sort((a, b) =>
|
||||||
|
a.shortcode.localeCompare(b.shortcode)
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (query.text) search(query.text);
|
if (query.text) search(query.text);
|
||||||
@@ -103,7 +108,7 @@ export function EmoticonAutocomplete({
|
|||||||
<Box
|
<Box
|
||||||
shrink="No"
|
shrink="No"
|
||||||
as="img"
|
as="img"
|
||||||
src={mx.mxcUrlToHttp(key) || key}
|
src={mxcUrlToHttp(mx, key, useAuthentication) || key}
|
||||||
alt={emoticon.shortcode}
|
alt={emoticon.shortcode}
|
||||||
style={{ width: toRem(24), height: toRem(24), objectFit: 'contain' }}
|
style={{ width: toRem(24), height: toRem(24), objectFit: 'contain' }}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import React, { KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect, useMemo } from 'react';
|
import React, { KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect } from 'react';
|
||||||
import { Editor } from 'slate';
|
import { Editor } from 'slate';
|
||||||
import { Avatar, AvatarFallback, AvatarImage, Icon, Icons, MenuItem, Text, color } from 'folds';
|
import { Avatar, Icon, Icons, MenuItem, Text } from 'folds';
|
||||||
import { MatrixClient } from 'matrix-js-sdk';
|
import { JoinRule, MatrixClient } from 'matrix-js-sdk';
|
||||||
|
import { useAtomValue } from 'jotai';
|
||||||
|
|
||||||
import { createMentionElement, moveCursor, replaceWithElement } from '../utils';
|
import { createMentionElement, moveCursor, replaceWithElement } from '../utils';
|
||||||
import { getRoomAvatarUrl, joinRuleToIconSrc } from '../../../utils/room';
|
import { getDirectRoomAvatarUrl } from '../../../utils/room';
|
||||||
import { roomIdByActivity } from '../../../../util/sort';
|
|
||||||
import initMatrix from '../../../../client/initMatrix';
|
|
||||||
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||||
import { AutocompleteQuery } from './autocompleteQuery';
|
import { AutocompleteQuery } from './autocompleteQuery';
|
||||||
import { AutocompleteMenu } from './AutocompleteMenu';
|
import { AutocompleteMenu } from './AutocompleteMenu';
|
||||||
@@ -14,6 +13,11 @@ import { getMxIdServer, validMxId } from '../../../utils/matrix';
|
|||||||
import { UseAsyncSearchOptions, useAsyncSearch } from '../../../hooks/useAsyncSearch';
|
import { UseAsyncSearchOptions, useAsyncSearch } from '../../../hooks/useAsyncSearch';
|
||||||
import { onTabPress } from '../../../utils/keyboard';
|
import { onTabPress } from '../../../utils/keyboard';
|
||||||
import { useKeyDown } from '../../../hooks/useKeyDown';
|
import { useKeyDown } from '../../../hooks/useKeyDown';
|
||||||
|
import { mDirectAtom } from '../../../state/mDirectList';
|
||||||
|
import { allRoomsAtom } from '../../../state/room-list/roomList';
|
||||||
|
import { factoryRoomIdByActivity } from '../../../utils/sort';
|
||||||
|
import { RoomAvatar, RoomIcon } from '../../room-avatar';
|
||||||
|
import { getViaServers } from '../../../plugins/via-servers';
|
||||||
|
|
||||||
type MentionAutoCompleteHandler = (roomAliasOrId: string, name: string) => void;
|
type MentionAutoCompleteHandler = (roomAliasOrId: string, name: string) => void;
|
||||||
|
|
||||||
@@ -74,15 +78,12 @@ export function RoomMentionAutocomplete({
|
|||||||
requestClose,
|
requestClose,
|
||||||
}: RoomMentionAutocompleteProps) {
|
}: RoomMentionAutocompleteProps) {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
const dms: Set<string> = initMatrix.roomList?.directs ?? new Set();
|
const mDirects = useAtomValue(mDirectAtom);
|
||||||
|
|
||||||
const allRoomId: string[] = useMemo(() => {
|
const allRooms = useAtomValue(allRoomsAtom).sort(factoryRoomIdByActivity(mx));
|
||||||
const { spaces = [], rooms = [], directs = [] } = initMatrix.roomList ?? {};
|
|
||||||
return [...spaces, ...rooms, ...directs].sort(roomIdByActivity);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const [result, search, resetSearch] = useAsyncSearch(
|
const [result, search, resetSearch] = useAsyncSearch(
|
||||||
allRoomId,
|
allRooms,
|
||||||
useCallback(
|
useCallback(
|
||||||
(rId) => {
|
(rId) => {
|
||||||
const r = mx.getRoom(rId);
|
const r = mx.getRoom(rId);
|
||||||
@@ -96,7 +97,7 @@ export function RoomMentionAutocomplete({
|
|||||||
SEARCH_OPTIONS
|
SEARCH_OPTIONS
|
||||||
);
|
);
|
||||||
|
|
||||||
const autoCompleteRoomIds = result ? result.items : allRoomId.slice(0, 20);
|
const autoCompleteRoomIds = result ? result.items : allRooms.slice(0, 20);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (query.text) search(query.text);
|
if (query.text) search(query.text);
|
||||||
@@ -104,10 +105,14 @@ export function RoomMentionAutocomplete({
|
|||||||
}, [query.text, search, resetSearch]);
|
}, [query.text, search, resetSearch]);
|
||||||
|
|
||||||
const handleAutocomplete: MentionAutoCompleteHandler = (roomAliasOrId, name) => {
|
const handleAutocomplete: MentionAutoCompleteHandler = (roomAliasOrId, name) => {
|
||||||
|
const mentionRoom = mx.getRoom(roomAliasOrId);
|
||||||
|
const viaServers = mentionRoom ? getViaServers(mentionRoom) : undefined;
|
||||||
const mentionEl = createMentionElement(
|
const mentionEl = createMentionElement(
|
||||||
roomAliasOrId,
|
roomAliasOrId,
|
||||||
name.startsWith('#') ? name : `#${name}`,
|
name.startsWith('#') ? name : `#${name}`,
|
||||||
roomId === roomAliasOrId || mx.getRoom(roomId)?.getCanonicalAlias() === roomAliasOrId
|
roomId === roomAliasOrId || mx.getRoom(roomId)?.getCanonicalAlias() === roomAliasOrId,
|
||||||
|
undefined,
|
||||||
|
viaServers
|
||||||
);
|
);
|
||||||
replaceWithElement(editor, query.range, mentionEl);
|
replaceWithElement(editor, query.range, mentionEl);
|
||||||
moveCursor(editor, true);
|
moveCursor(editor, true);
|
||||||
@@ -136,9 +141,7 @@ export function RoomMentionAutocomplete({
|
|||||||
autoCompleteRoomIds.map((rId) => {
|
autoCompleteRoomIds.map((rId) => {
|
||||||
const room = mx.getRoom(rId);
|
const room = mx.getRoom(rId);
|
||||||
if (!room) return null;
|
if (!room) return null;
|
||||||
const dm = dms.has(room.roomId);
|
const dm = mDirects.has(room.roomId);
|
||||||
const avatarUrl = getRoomAvatarUrl(mx, room);
|
|
||||||
const iconSrc = !dm && joinRuleToIconSrc(Icons, room.getJoinRule(), room.isSpaceRoom());
|
|
||||||
|
|
||||||
const handleSelect = () => handleAutocomplete(room.getCanonicalAlias() ?? rId, room.name);
|
const handleSelect = () => handleAutocomplete(room.getCanonicalAlias() ?? rId, room.name);
|
||||||
|
|
||||||
@@ -158,17 +161,21 @@ export function RoomMentionAutocomplete({
|
|||||||
}
|
}
|
||||||
before={
|
before={
|
||||||
<Avatar size="200">
|
<Avatar size="200">
|
||||||
{iconSrc && <Icon src={iconSrc} size="100" />}
|
{dm ? (
|
||||||
{avatarUrl && !iconSrc && <AvatarImage src={avatarUrl} alt={room.name} />}
|
<RoomAvatar
|
||||||
{!avatarUrl && !iconSrc && (
|
roomId={room.roomId}
|
||||||
<AvatarFallback
|
src={getDirectRoomAvatarUrl(mx, room)}
|
||||||
style={{
|
alt={room.name}
|
||||||
backgroundColor: color.Secondary.Container,
|
renderFallback={() => (
|
||||||
color: color.Secondary.OnContainer,
|
<RoomIcon
|
||||||
}}
|
size="50"
|
||||||
>
|
joinRule={room.getJoinRule() ?? JoinRule.Restricted}
|
||||||
<Text size="H6">{room.name[0]}</Text>
|
filled
|
||||||
</AvatarFallback>
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<RoomIcon size="100" joinRule={room.getJoinRule()} space={room.isSpaceRoom()} />
|
||||||
)}
|
)}
|
||||||
</Avatar>
|
</Avatar>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import React, { useEffect, KeyboardEvent as ReactKeyboardEvent } from 'react';
|
import React, { useEffect, KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||||
import { Editor } from 'slate';
|
import { Editor } from 'slate';
|
||||||
import { Avatar, AvatarFallback, AvatarImage, MenuItem, Text, color } from 'folds';
|
import { Avatar, Icon, Icons, MenuItem, Text } from 'folds';
|
||||||
import { MatrixClient, Room, RoomMember } from 'matrix-js-sdk';
|
import { MatrixClient, Room, RoomMember } from 'matrix-js-sdk';
|
||||||
|
|
||||||
import { AutocompleteQuery } from './autocompleteQuery';
|
import { AutocompleteQuery } from './autocompleteQuery';
|
||||||
@@ -17,6 +17,9 @@ import { createMentionElement, moveCursor, replaceWithElement } from '../utils';
|
|||||||
import { useKeyDown } from '../../../hooks/useKeyDown';
|
import { useKeyDown } from '../../../hooks/useKeyDown';
|
||||||
import { getMxIdLocalPart, getMxIdServer, validMxId } from '../../../utils/matrix';
|
import { getMxIdLocalPart, getMxIdServer, validMxId } from '../../../utils/matrix';
|
||||||
import { getMemberDisplayName, getMemberSearchStr } from '../../../utils/room';
|
import { getMemberDisplayName, getMemberSearchStr } from '../../../utils/room';
|
||||||
|
import { UserAvatar } from '../../user-avatar';
|
||||||
|
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
|
||||||
|
import { Membership } from '../../../../types/matrix/room';
|
||||||
|
|
||||||
type MentionAutoCompleteHandler = (userId: string, name: string) => void;
|
type MentionAutoCompleteHandler = (userId: string, name: string) => void;
|
||||||
|
|
||||||
@@ -26,12 +29,10 @@ const userIdFromQueryText = (mx: MatrixClient, text: string) =>
|
|||||||
: `@${text}${text.endsWith(':') ? '' : ':'}${getMxIdServer(mx.getUserId() ?? '')}`;
|
: `@${text}${text.endsWith(':') ? '' : ':'}${getMxIdServer(mx.getUserId() ?? '')}`;
|
||||||
|
|
||||||
function UnknownMentionItem({
|
function UnknownMentionItem({
|
||||||
query,
|
|
||||||
userId,
|
userId,
|
||||||
name,
|
name,
|
||||||
handleAutocomplete,
|
handleAutocomplete,
|
||||||
}: {
|
}: {
|
||||||
query: AutocompleteQuery<string>;
|
|
||||||
userId: string;
|
userId: string;
|
||||||
name: string;
|
name: string;
|
||||||
handleAutocomplete: MentionAutoCompleteHandler;
|
handleAutocomplete: MentionAutoCompleteHandler;
|
||||||
@@ -46,14 +47,10 @@ function UnknownMentionItem({
|
|||||||
onClick={() => handleAutocomplete(userId, name)}
|
onClick={() => handleAutocomplete(userId, name)}
|
||||||
before={
|
before={
|
||||||
<Avatar size="200">
|
<Avatar size="200">
|
||||||
<AvatarFallback
|
<UserAvatar
|
||||||
style={{
|
userId={userId}
|
||||||
backgroundColor: color.Secondary.Container,
|
renderFallback={() => <Icon size="50" src={Icons.User} filled />}
|
||||||
color: color.Secondary.OnContainer,
|
/>
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Text size="H6">{query.text[0]}</Text>
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
</Avatar>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
@@ -71,6 +68,11 @@ type UserMentionAutocompleteProps = {
|
|||||||
requestClose: () => void;
|
requestClose: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const withAllowedMembership = (member: RoomMember): boolean =>
|
||||||
|
member.membership === Membership.Join ||
|
||||||
|
member.membership === Membership.Invite ||
|
||||||
|
member.membership === Membership.Knock;
|
||||||
|
|
||||||
const SEARCH_OPTIONS: UseAsyncSearchOptions = {
|
const SEARCH_OPTIONS: UseAsyncSearchOptions = {
|
||||||
limit: 20,
|
limit: 20,
|
||||||
matchOptions: {
|
matchOptions: {
|
||||||
@@ -89,12 +91,15 @@ export function UserMentionAutocomplete({
|
|||||||
requestClose,
|
requestClose,
|
||||||
}: UserMentionAutocompleteProps) {
|
}: UserMentionAutocompleteProps) {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
|
const useAuthentication = useMediaAuthentication();
|
||||||
const roomId: string = room.roomId!;
|
const roomId: string = room.roomId!;
|
||||||
const roomAliasOrId = room.getCanonicalAlias() || roomId;
|
const roomAliasOrId = room.getCanonicalAlias() || roomId;
|
||||||
const members = useRoomMembers(mx, roomId);
|
const members = useRoomMembers(mx, roomId);
|
||||||
|
|
||||||
const [result, search, resetSearch] = useAsyncSearch(members, getRoomMemberStr, SEARCH_OPTIONS);
|
const [result, search, resetSearch] = useAsyncSearch(members, getRoomMemberStr, SEARCH_OPTIONS);
|
||||||
const autoCompleteMembers = result ? result.items : members.slice(0, 20);
|
const autoCompleteMembers = (result ? result.items : members.slice(0, 20)).filter(
|
||||||
|
withAllowedMembership
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (query.text) search(query.text);
|
if (query.text) search(query.text);
|
||||||
@@ -135,7 +140,6 @@ export function UserMentionAutocomplete({
|
|||||||
<AutocompleteMenu headerContent={<Text size="L400">Mentions</Text>} requestClose={requestClose}>
|
<AutocompleteMenu headerContent={<Text size="L400">Mentions</Text>} requestClose={requestClose}>
|
||||||
{query.text === 'room' && (
|
{query.text === 'room' && (
|
||||||
<UnknownMentionItem
|
<UnknownMentionItem
|
||||||
query={query}
|
|
||||||
userId={roomAliasOrId}
|
userId={roomAliasOrId}
|
||||||
name="@room"
|
name="@room"
|
||||||
handleAutocomplete={handleAutocomplete}
|
handleAutocomplete={handleAutocomplete}
|
||||||
@@ -143,14 +147,16 @@ export function UserMentionAutocomplete({
|
|||||||
)}
|
)}
|
||||||
{autoCompleteMembers.length === 0 ? (
|
{autoCompleteMembers.length === 0 ? (
|
||||||
<UnknownMentionItem
|
<UnknownMentionItem
|
||||||
query={query}
|
|
||||||
userId={userIdFromQueryText(mx, query.text)}
|
userId={userIdFromQueryText(mx, query.text)}
|
||||||
name={userIdFromQueryText(mx, query.text)}
|
name={userIdFromQueryText(mx, query.text)}
|
||||||
handleAutocomplete={handleAutocomplete}
|
handleAutocomplete={handleAutocomplete}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
autoCompleteMembers.map((roomMember) => {
|
autoCompleteMembers.map((roomMember) => {
|
||||||
const avatarUrl = roomMember.getAvatarUrl(mx.baseUrl, 32, 32, 'crop', undefined, false);
|
const avatarMxcUrl = roomMember.getMxcAvatarUrl();
|
||||||
|
const avatarUrl = avatarMxcUrl
|
||||||
|
? mx.mxcUrlToHttp(avatarMxcUrl, 32, 32, 'crop', undefined, false, useAuthentication)
|
||||||
|
: undefined;
|
||||||
return (
|
return (
|
||||||
<MenuItem
|
<MenuItem
|
||||||
key={roomMember.userId}
|
key={roomMember.userId}
|
||||||
@@ -167,18 +173,12 @@ export function UserMentionAutocomplete({
|
|||||||
}
|
}
|
||||||
before={
|
before={
|
||||||
<Avatar size="200">
|
<Avatar size="200">
|
||||||
{avatarUrl ? (
|
<UserAvatar
|
||||||
<AvatarImage src={avatarUrl} alt={getName(roomMember)} />
|
userId={roomMember.userId}
|
||||||
) : (
|
src={avatarUrl ?? undefined}
|
||||||
<AvatarFallback
|
alt={getName(roomMember)}
|
||||||
style={{
|
renderFallback={() => <Icon size="50" src={Icons.User} filled />}
|
||||||
backgroundColor: color.Secondary.Container,
|
/>
|
||||||
color: color.Secondary.OnContainer,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Text size="H6">{getName(roomMember)[0]}</Text>
|
|
||||||
</AvatarFallback>
|
|
||||||
)}
|
|
||||||
</Avatar>
|
</Avatar>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -18,8 +18,14 @@ import {
|
|||||||
ParagraphElement,
|
ParagraphElement,
|
||||||
UnorderedListElement,
|
UnorderedListElement,
|
||||||
} from './slate';
|
} from './slate';
|
||||||
import { parseMatrixToUrl } from '../../utils/matrix';
|
|
||||||
import { createEmoticonElement, createMentionElement } from './utils';
|
import { createEmoticonElement, createMentionElement } from './utils';
|
||||||
|
import {
|
||||||
|
parseMatrixToRoom,
|
||||||
|
parseMatrixToRoomEvent,
|
||||||
|
parseMatrixToUser,
|
||||||
|
testMatrixTo,
|
||||||
|
} from '../../plugins/matrix-to';
|
||||||
|
import { tryDecodeURIComponent } from '../../utils/dom';
|
||||||
|
|
||||||
const markNodeToType: Record<string, MarkType> = {
|
const markNodeToType: Record<string, MarkType> = {
|
||||||
b: MarkType.Bold,
|
b: MarkType.Bold,
|
||||||
@@ -68,11 +74,33 @@ const elementToInlineNode = (node: Element): MentionElement | EmoticonElement |
|
|||||||
return createEmoticonElement(src, alt || 'Unknown Emoji');
|
return createEmoticonElement(src, alt || 'Unknown Emoji');
|
||||||
}
|
}
|
||||||
if (node.name === 'a') {
|
if (node.name === 'a') {
|
||||||
const { href } = node.attribs;
|
const href = tryDecodeURIComponent(node.attribs.href);
|
||||||
if (typeof href !== 'string') return undefined;
|
if (typeof href !== 'string') return undefined;
|
||||||
const [mxId] = parseMatrixToUrl(href);
|
if (testMatrixTo(href)) {
|
||||||
if (mxId) {
|
const userMention = parseMatrixToUser(href);
|
||||||
return createMentionElement(mxId, parseNodeText(node) || mxId, false);
|
if (userMention) {
|
||||||
|
return createMentionElement(userMention, parseNodeText(node) || userMention, false);
|
||||||
|
}
|
||||||
|
const roomMention = parseMatrixToRoom(href);
|
||||||
|
if (roomMention) {
|
||||||
|
return createMentionElement(
|
||||||
|
roomMention.roomIdOrAlias,
|
||||||
|
parseNodeText(node) || roomMention.roomIdOrAlias,
|
||||||
|
false,
|
||||||
|
undefined,
|
||||||
|
roomMention.viaServers
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const eventMention = parseMatrixToRoomEvent(href);
|
||||||
|
if (eventMention) {
|
||||||
|
return createMentionElement(
|
||||||
|
eventMention.roomIdOrAlias,
|
||||||
|
parseNodeText(node) || eventMention.roomIdOrAlias,
|
||||||
|
false,
|
||||||
|
eventMention.eventId,
|
||||||
|
eventMention.viaServers
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ import { Descendant, Text } from 'slate';
|
|||||||
import { sanitizeText } from '../../utils/sanitize';
|
import { sanitizeText } from '../../utils/sanitize';
|
||||||
import { BlockType } from './types';
|
import { BlockType } from './types';
|
||||||
import { CustomElement } from './slate';
|
import { CustomElement } from './slate';
|
||||||
import { parseBlockMD, parseInlineMD, replaceMatch } from '../../utils/markdown';
|
import { parseBlockMD, parseInlineMD } from '../../plugins/markdown';
|
||||||
|
import { findAndReplace } from '../../utils/findAndReplace';
|
||||||
|
|
||||||
export type OutputOptions = {
|
export type OutputOptions = {
|
||||||
allowTextFormatting?: boolean;
|
allowTextFormatting?: boolean;
|
||||||
@@ -50,29 +51,42 @@ const elementToCustomHtml = (node: CustomElement, children: string): string => {
|
|||||||
case BlockType.UnorderedList:
|
case BlockType.UnorderedList:
|
||||||
return `<ul>${children}</ul>`;
|
return `<ul>${children}</ul>`;
|
||||||
|
|
||||||
case BlockType.Mention:
|
case BlockType.Mention: {
|
||||||
return `<a href="https://matrix.to/#/${node.id}">${node.name}</a>`;
|
let fragment = node.id;
|
||||||
|
|
||||||
|
if (node.eventId) {
|
||||||
|
fragment += `/${node.eventId}`;
|
||||||
|
}
|
||||||
|
if (node.viaServers && node.viaServers.length > 0) {
|
||||||
|
fragment += `?${node.viaServers.map((server) => `via=${server}`).join('&')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const matrixTo = `https://matrix.to/#/${fragment}`;
|
||||||
|
return `<a href="${encodeURI(matrixTo)}">${sanitizeText(node.name)}</a>`;
|
||||||
|
}
|
||||||
case BlockType.Emoticon:
|
case BlockType.Emoticon:
|
||||||
return node.key.startsWith('mxc://')
|
return node.key.startsWith('mxc://')
|
||||||
? `<img data-mx-emoticon src="${node.key}" alt="${node.shortcode}" title="${node.shortcode}" height="32">`
|
? `<img data-mx-emoticon src="${node.key}" alt="${sanitizeText(
|
||||||
: node.key;
|
node.shortcode
|
||||||
|
)}" title="${sanitizeText(node.shortcode)}" height="32" />`
|
||||||
|
: sanitizeText(node.key);
|
||||||
case BlockType.Link:
|
case BlockType.Link:
|
||||||
return `<a href="${node.href}">${node.children}</a>`;
|
return `<a href="${encodeURI(node.href)}">${node.children}</a>`;
|
||||||
case BlockType.Command:
|
case BlockType.Command:
|
||||||
return `/${node.command}`;
|
return `/${sanitizeText(node.command)}`;
|
||||||
default:
|
default:
|
||||||
return children;
|
return children;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const HTML_TAG_REG = /<([a-z]+)(?![^>]*\/>)[^<]*<\/\1>/;
|
const HTML_TAG_REG_G = /<([\w-]+)(?: [^>]*)?(?:(?:\/>)|(?:>.*?<\/\1>))/g;
|
||||||
const ignoreHTMLParseInlineMD = (text: string): string => {
|
const ignoreHTMLParseInlineMD = (text: string): string =>
|
||||||
if (text === '') return text;
|
findAndReplace(
|
||||||
const match = text.match(HTML_TAG_REG);
|
text,
|
||||||
if (!match) return parseInlineMD(text);
|
HTML_TAG_REG_G,
|
||||||
const [matchedTxt] = match;
|
(match) => match[0],
|
||||||
return replaceMatch((txt) => [ignoreHTMLParseInlineMD(txt)], text, match, matchedTxt).join('');
|
(txt) => parseInlineMD(txt)
|
||||||
};
|
).join('');
|
||||||
|
|
||||||
export const toMatrixCustomHTML = (
|
export const toMatrixCustomHTML = (
|
||||||
node: Descendant | Descendant[],
|
node: Descendant | Descendant[],
|
||||||
|
|||||||
2
src/app/components/editor/slate.d.ts
vendored
2
src/app/components/editor/slate.d.ts
vendored
@@ -29,6 +29,8 @@ export type LinkElement = {
|
|||||||
export type MentionElement = {
|
export type MentionElement = {
|
||||||
type: BlockType.Mention;
|
type: BlockType.Mention;
|
||||||
id: string;
|
id: string;
|
||||||
|
eventId?: string;
|
||||||
|
viaServers?: string[];
|
||||||
highlight: boolean;
|
highlight: boolean;
|
||||||
name: string;
|
name: string;
|
||||||
children: Text[];
|
children: Text[];
|
||||||
|
|||||||
@@ -158,10 +158,14 @@ export const resetEditorHistory = (editor: Editor) => {
|
|||||||
export const createMentionElement = (
|
export const createMentionElement = (
|
||||||
id: string,
|
id: string,
|
||||||
name: string,
|
name: string,
|
||||||
highlight: boolean
|
highlight: boolean,
|
||||||
|
eventId?: string,
|
||||||
|
viaServers?: string[]
|
||||||
): MentionElement => ({
|
): MentionElement => ({
|
||||||
type: BlockType.Mention,
|
type: BlockType.Mention,
|
||||||
id,
|
id,
|
||||||
|
eventId,
|
||||||
|
viaServers,
|
||||||
highlight,
|
highlight,
|
||||||
name,
|
name,
|
||||||
children: [{ text: '' }],
|
children: [{ text: '' }],
|
||||||
|
|||||||
@@ -37,18 +37,19 @@ import * as css from './EmojiBoard.css';
|
|||||||
import { EmojiGroupId, IEmoji, IEmojiGroup, emojiGroups, emojis } from '../../plugins/emoji';
|
import { EmojiGroupId, IEmoji, IEmojiGroup, emojiGroups, emojis } from '../../plugins/emoji';
|
||||||
import { IEmojiGroupLabels, useEmojiGroupLabels } from './useEmojiGroupLabels';
|
import { IEmojiGroupLabels, useEmojiGroupLabels } from './useEmojiGroupLabels';
|
||||||
import { IEmojiGroupIcons, useEmojiGroupIcons } from './useEmojiGroupIcons';
|
import { IEmojiGroupIcons, useEmojiGroupIcons } from './useEmojiGroupIcons';
|
||||||
import { preventScrollWithArrowKey } from '../../utils/keyboard';
|
import { preventScrollWithArrowKey, stopPropagation } from '../../utils/keyboard';
|
||||||
import { useRelevantImagePacks } from '../../hooks/useImagePacks';
|
import { useRelevantImagePacks } from '../../hooks/useImagePacks';
|
||||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
import { useRecentEmoji } from '../../hooks/useRecentEmoji';
|
import { useRecentEmoji } from '../../hooks/useRecentEmoji';
|
||||||
import { ExtendedPackImage, ImagePack, PackUsage } from '../../plugins/custom-emoji';
|
import { isUserId, mxcUrlToHttp } from '../../utils/matrix';
|
||||||
import { isUserId } from '../../utils/matrix';
|
|
||||||
import { editableActiveElement, isIntersectingScrollView, targetFromEvent } from '../../utils/dom';
|
import { editableActiveElement, isIntersectingScrollView, targetFromEvent } from '../../utils/dom';
|
||||||
import { useAsyncSearch, UseAsyncSearchOptions } from '../../hooks/useAsyncSearch';
|
import { useAsyncSearch, UseAsyncSearchOptions } from '../../hooks/useAsyncSearch';
|
||||||
import { useDebounce } from '../../hooks/useDebounce';
|
import { useDebounce } from '../../hooks/useDebounce';
|
||||||
import { useThrottle } from '../../hooks/useThrottle';
|
import { useThrottle } from '../../hooks/useThrottle';
|
||||||
import { addRecentEmoji } from '../../plugins/recent-emoji';
|
import { addRecentEmoji } from '../../plugins/recent-emoji';
|
||||||
import { mobileOrTablet } from '../../utils/user-agent';
|
import { mobileOrTablet } from '../../utils/user-agent';
|
||||||
|
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||||
|
import { ImagePack, ImageUsage, PackImageReader } from '../../plugins/custom-emoji';
|
||||||
|
|
||||||
const RECENT_GROUP_ID = 'recent_group';
|
const RECENT_GROUP_ID = 'recent_group';
|
||||||
const SEARCH_GROUP_ID = 'search_group';
|
const SEARCH_GROUP_ID = 'search_group';
|
||||||
@@ -174,18 +175,6 @@ function EmojiBoardTabs({
|
|||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<Box gap="100">
|
<Box gap="100">
|
||||||
<Badge
|
|
||||||
className={css.EmojiBoardTab}
|
|
||||||
as="button"
|
|
||||||
variant="Secondary"
|
|
||||||
fill={tab === EmojiBoardTab.Emoji ? 'Solid' : 'None'}
|
|
||||||
size="500"
|
|
||||||
onClick={() => onTabChange(EmojiBoardTab.Emoji)}
|
|
||||||
>
|
|
||||||
<Text as="span" size="L400">
|
|
||||||
Emoji
|
|
||||||
</Text>
|
|
||||||
</Badge>
|
|
||||||
<Badge
|
<Badge
|
||||||
className={css.EmojiBoardTab}
|
className={css.EmojiBoardTab}
|
||||||
as="button"
|
as="button"
|
||||||
@@ -198,6 +187,18 @@ function EmojiBoardTabs({
|
|||||||
Sticker
|
Sticker
|
||||||
</Text>
|
</Text>
|
||||||
</Badge>
|
</Badge>
|
||||||
|
<Badge
|
||||||
|
className={css.EmojiBoardTab}
|
||||||
|
as="button"
|
||||||
|
variant="Secondary"
|
||||||
|
fill={tab === EmojiBoardTab.Emoji ? 'Solid' : 'None'}
|
||||||
|
size="500"
|
||||||
|
onClick={() => onTabChange(EmojiBoardTab.Emoji)}
|
||||||
|
>
|
||||||
|
<Text as="span" size="L400">
|
||||||
|
Emoji
|
||||||
|
</Text>
|
||||||
|
</Badge>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -354,18 +355,20 @@ function ImagePackSidebarStack({
|
|||||||
packs,
|
packs,
|
||||||
usage,
|
usage,
|
||||||
onItemClick,
|
onItemClick,
|
||||||
|
useAuthentication,
|
||||||
}: {
|
}: {
|
||||||
mx: MatrixClient;
|
mx: MatrixClient;
|
||||||
packs: ImagePack[];
|
packs: ImagePack[];
|
||||||
usage: PackUsage;
|
usage: ImageUsage;
|
||||||
onItemClick: (id: string) => void;
|
onItemClick: (id: string) => void;
|
||||||
|
useAuthentication?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const activeGroupId = useAtomValue(activeGroupIdAtom);
|
const activeGroupId = useAtomValue(activeGroupIdAtom);
|
||||||
return (
|
return (
|
||||||
<SidebarStack>
|
<SidebarStack>
|
||||||
{usage === PackUsage.Emoticon && <SidebarDivider />}
|
{usage === ImageUsage.Emoticon && <SidebarDivider />}
|
||||||
{packs.map((pack) => {
|
{packs.map((pack) => {
|
||||||
let label = pack.displayName;
|
let label = pack.meta.name;
|
||||||
if (!label) label = isUserId(pack.id) ? 'Personal Pack' : mx.getRoom(pack.id)?.name;
|
if (!label) label = isUserId(pack.id) ? 'Personal Pack' : mx.getRoom(pack.id)?.name;
|
||||||
return (
|
return (
|
||||||
<SidebarBtn
|
<SidebarBtn
|
||||||
@@ -381,7 +384,10 @@ function ImagePackSidebarStack({
|
|||||||
height: toRem(24),
|
height: toRem(24),
|
||||||
objectFit: 'contain',
|
objectFit: 'contain',
|
||||||
}}
|
}}
|
||||||
src={mx.mxcUrlToHttp(pack.getPackAvatarUrl(usage) ?? '') || pack.avatarUrl}
|
src={
|
||||||
|
mxcUrlToHttp(mx, pack.getAvatarUrl(usage) ?? '', useAuthentication) ||
|
||||||
|
pack.meta.avatar
|
||||||
|
}
|
||||||
alt={label || 'Unknown Pack'}
|
alt={label || 'Unknown Pack'}
|
||||||
/>
|
/>
|
||||||
</SidebarBtn>
|
</SidebarBtn>
|
||||||
@@ -453,44 +459,48 @@ export function SearchEmojiGroup({
|
|||||||
label,
|
label,
|
||||||
id,
|
id,
|
||||||
emojis: searchResult,
|
emojis: searchResult,
|
||||||
|
useAuthentication,
|
||||||
}: {
|
}: {
|
||||||
mx: MatrixClient;
|
mx: MatrixClient;
|
||||||
tab: EmojiBoardTab;
|
tab: EmojiBoardTab;
|
||||||
label: string;
|
label: string;
|
||||||
id: string;
|
id: string;
|
||||||
emojis: Array<ExtendedPackImage | IEmoji>;
|
emojis: Array<PackImageReader | IEmoji>;
|
||||||
|
useAuthentication?: boolean;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<EmojiGroup key={id} id={id} label={label}>
|
<EmojiGroup key={id} id={id} label={label}>
|
||||||
{tab === EmojiBoardTab.Emoji
|
{tab === EmojiBoardTab.Emoji
|
||||||
? searchResult.map((emoji) =>
|
? searchResult
|
||||||
'unicode' in emoji ? (
|
.sort((a, b) => a.shortcode.localeCompare(b.shortcode))
|
||||||
<EmojiItem
|
.map((emoji) =>
|
||||||
key={emoji.unicode}
|
'unicode' in emoji ? (
|
||||||
label={emoji.label}
|
<EmojiItem
|
||||||
type={EmojiType.Emoji}
|
key={emoji.unicode}
|
||||||
data={emoji.unicode}
|
label={emoji.label}
|
||||||
shortcode={emoji.shortcode}
|
type={EmojiType.Emoji}
|
||||||
>
|
data={emoji.unicode}
|
||||||
{emoji.unicode}
|
shortcode={emoji.shortcode}
|
||||||
</EmojiItem>
|
>
|
||||||
) : (
|
{emoji.unicode}
|
||||||
<EmojiItem
|
</EmojiItem>
|
||||||
key={emoji.shortcode}
|
) : (
|
||||||
label={emoji.body || emoji.shortcode}
|
<EmojiItem
|
||||||
type={EmojiType.CustomEmoji}
|
key={emoji.shortcode}
|
||||||
data={emoji.url}
|
label={emoji.body || emoji.shortcode}
|
||||||
shortcode={emoji.shortcode}
|
type={EmojiType.CustomEmoji}
|
||||||
>
|
data={emoji.url}
|
||||||
<img
|
shortcode={emoji.shortcode}
|
||||||
loading="lazy"
|
>
|
||||||
className={css.CustomEmojiImg}
|
<img
|
||||||
alt={emoji.body || emoji.shortcode}
|
loading="lazy"
|
||||||
src={mx.mxcUrlToHttp(emoji.url) ?? emoji.url}
|
className={css.CustomEmojiImg}
|
||||||
/>
|
alt={emoji.body || emoji.shortcode}
|
||||||
</EmojiItem>
|
src={mxcUrlToHttp(mx, emoji.url, useAuthentication) ?? emoji.url}
|
||||||
|
/>
|
||||||
|
</EmojiItem>
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
|
||||||
: searchResult.map((emoji) =>
|
: searchResult.map((emoji) =>
|
||||||
'unicode' in emoji ? null : (
|
'unicode' in emoji ? null : (
|
||||||
<StickerItem
|
<StickerItem
|
||||||
@@ -504,7 +514,7 @@ export function SearchEmojiGroup({
|
|||||||
loading="lazy"
|
loading="lazy"
|
||||||
className={css.StickerImg}
|
className={css.StickerImg}
|
||||||
alt={emoji.body || emoji.shortcode}
|
alt={emoji.body || emoji.shortcode}
|
||||||
src={mx.mxcUrlToHttp(emoji.url) ?? emoji.url}
|
src={mxcUrlToHttp(mx, emoji.url, useAuthentication) ?? emoji.url}
|
||||||
/>
|
/>
|
||||||
</StickerItem>
|
</StickerItem>
|
||||||
)
|
)
|
||||||
@@ -514,73 +524,97 @@ export function SearchEmojiGroup({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const CustomEmojiGroups = memo(
|
export const CustomEmojiGroups = memo(
|
||||||
({ mx, groups }: { mx: MatrixClient; groups: ImagePack[] }) => (
|
({
|
||||||
|
mx,
|
||||||
|
groups,
|
||||||
|
useAuthentication,
|
||||||
|
}: {
|
||||||
|
mx: MatrixClient;
|
||||||
|
groups: ImagePack[];
|
||||||
|
useAuthentication?: boolean;
|
||||||
|
}) => (
|
||||||
<>
|
<>
|
||||||
{groups.map((pack) => (
|
{groups.map((pack) => (
|
||||||
<EmojiGroup key={pack.id} id={pack.id} label={pack.displayName || 'Unknown'}>
|
<EmojiGroup key={pack.id} id={pack.id} label={pack.meta.name || 'Unknown'}>
|
||||||
{pack.getEmojis().map((image) => (
|
{pack
|
||||||
<EmojiItem
|
.getImages(ImageUsage.Emoticon)
|
||||||
key={image.shortcode}
|
.sort((a, b) => a.shortcode.localeCompare(b.shortcode))
|
||||||
label={image.body || image.shortcode}
|
.map((image) => (
|
||||||
type={EmojiType.CustomEmoji}
|
<EmojiItem
|
||||||
data={image.url}
|
key={image.shortcode}
|
||||||
shortcode={image.shortcode}
|
label={image.body || image.shortcode}
|
||||||
>
|
type={EmojiType.CustomEmoji}
|
||||||
<img
|
data={image.url}
|
||||||
loading="lazy"
|
shortcode={image.shortcode}
|
||||||
className={css.CustomEmojiImg}
|
>
|
||||||
alt={image.body || image.shortcode}
|
<img
|
||||||
src={mx.mxcUrlToHttp(image.url) ?? image.url}
|
loading="lazy"
|
||||||
/>
|
className={css.CustomEmojiImg}
|
||||||
</EmojiItem>
|
alt={image.body || image.shortcode}
|
||||||
))}
|
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? image.url}
|
||||||
|
/>
|
||||||
|
</EmojiItem>
|
||||||
|
))}
|
||||||
</EmojiGroup>
|
</EmojiGroup>
|
||||||
))}
|
))}
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
export const StickerGroups = memo(({ mx, groups }: { mx: MatrixClient; groups: ImagePack[] }) => (
|
export const StickerGroups = memo(
|
||||||
<>
|
({
|
||||||
{groups.length === 0 && (
|
mx,
|
||||||
<Box
|
groups,
|
||||||
style={{ padding: `${toRem(60)} ${config.space.S500}` }}
|
useAuthentication,
|
||||||
alignItems="Center"
|
}: {
|
||||||
justifyContent="Center"
|
mx: MatrixClient;
|
||||||
direction="Column"
|
groups: ImagePack[];
|
||||||
gap="300"
|
useAuthentication?: boolean;
|
||||||
>
|
}) => (
|
||||||
<Icon size="600" src={Icons.Sticker} />
|
<>
|
||||||
<Box direction="Inherit">
|
{groups.length === 0 && (
|
||||||
<Text align="Center">No Sticker Packs!</Text>
|
<Box
|
||||||
<Text priority="300" align="Center" size="T200">
|
style={{ padding: `${toRem(60)} ${config.space.S500}` }}
|
||||||
Add stickers from user, room or space settings.
|
alignItems="Center"
|
||||||
</Text>
|
justifyContent="Center"
|
||||||
|
direction="Column"
|
||||||
|
gap="300"
|
||||||
|
>
|
||||||
|
<Icon size="600" src={Icons.Sticker} />
|
||||||
|
<Box direction="Inherit">
|
||||||
|
<Text align="Center">No Sticker Packs!</Text>
|
||||||
|
<Text priority="300" align="Center" size="T200">
|
||||||
|
Add stickers from user, room or space settings.
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
)}
|
||||||
)}
|
{groups.map((pack) => (
|
||||||
{groups.map((pack) => (
|
<EmojiGroup key={pack.id} id={pack.id} label={pack.meta.name || 'Unknown'}>
|
||||||
<EmojiGroup key={pack.id} id={pack.id} label={pack.displayName || 'Unknown'}>
|
{pack
|
||||||
{pack.getStickers().map((image) => (
|
.getImages(ImageUsage.Sticker)
|
||||||
<StickerItem
|
.sort((a, b) => a.shortcode.localeCompare(b.shortcode))
|
||||||
key={image.shortcode}
|
.map((image) => (
|
||||||
label={image.body || image.shortcode}
|
<StickerItem
|
||||||
type={EmojiType.Sticker}
|
key={image.shortcode}
|
||||||
data={image.url}
|
label={image.body || image.shortcode}
|
||||||
shortcode={image.shortcode}
|
type={EmojiType.Sticker}
|
||||||
>
|
data={image.url}
|
||||||
<img
|
shortcode={image.shortcode}
|
||||||
loading="lazy"
|
>
|
||||||
className={css.StickerImg}
|
<img
|
||||||
alt={image.body || image.shortcode}
|
loading="lazy"
|
||||||
src={mx.mxcUrlToHttp(image.url) ?? image.url}
|
className={css.StickerImg}
|
||||||
/>
|
alt={image.body || image.shortcode}
|
||||||
</StickerItem>
|
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? image.url}
|
||||||
))}
|
/>
|
||||||
</EmojiGroup>
|
</StickerItem>
|
||||||
))}
|
))}
|
||||||
</>
|
</EmojiGroup>
|
||||||
));
|
))}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
export const NativeEmojiGroups = memo(
|
export const NativeEmojiGroups = memo(
|
||||||
({ groups, labels }: { groups: IEmojiGroup[]; labels: IEmojiGroupLabels }) => (
|
({ groups, labels }: { groups: IEmojiGroup[]; labels: IEmojiGroupLabels }) => (
|
||||||
@@ -604,7 +638,7 @@ export const NativeEmojiGroups = memo(
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
const getSearchListItemStr = (item: ExtendedPackImage | IEmoji) => {
|
const getSearchListItemStr = (item: PackImageReader | IEmoji) => {
|
||||||
const shortcode = `:${item.shortcode}:`;
|
const shortcode = `:${item.shortcode}:`;
|
||||||
if ('body' in item) {
|
if ('body' in item) {
|
||||||
return [shortcode, item.body ?? ''];
|
return [shortcode, item.body ?? ''];
|
||||||
@@ -641,13 +675,14 @@ export function EmojiBoard({
|
|||||||
}) {
|
}) {
|
||||||
const emojiTab = tab === EmojiBoardTab.Emoji;
|
const emojiTab = tab === EmojiBoardTab.Emoji;
|
||||||
const stickerTab = tab === EmojiBoardTab.Sticker;
|
const stickerTab = tab === EmojiBoardTab.Sticker;
|
||||||
const usage = emojiTab ? PackUsage.Emoticon : PackUsage.Sticker;
|
const usage = emojiTab ? ImageUsage.Emoticon : ImageUsage.Sticker;
|
||||||
|
|
||||||
const setActiveGroupId = useSetAtom(activeGroupIdAtom);
|
const setActiveGroupId = useSetAtom(activeGroupIdAtom);
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
|
const useAuthentication = useMediaAuthentication();
|
||||||
const emojiGroupLabels = useEmojiGroupLabels();
|
const emojiGroupLabels = useEmojiGroupLabels();
|
||||||
const emojiGroupIcons = useEmojiGroupIcons();
|
const emojiGroupIcons = useEmojiGroupIcons();
|
||||||
const imagePacks = useRelevantImagePacks(mx, usage, imagePackRooms);
|
const imagePacks = useRelevantImagePacks(usage, imagePackRooms);
|
||||||
const recentEmojis = useRecentEmoji(mx, 21);
|
const recentEmojis = useRecentEmoji(mx, 21);
|
||||||
|
|
||||||
const contentScrollRef = useRef<HTMLDivElement>(null);
|
const contentScrollRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -655,8 +690,8 @@ export function EmojiBoard({
|
|||||||
const emojiPreviewTextRef = useRef<HTMLParagraphElement>(null);
|
const emojiPreviewTextRef = useRef<HTMLParagraphElement>(null);
|
||||||
|
|
||||||
const searchList = useMemo(() => {
|
const searchList = useMemo(() => {
|
||||||
let list: Array<ExtendedPackImage | IEmoji> = [];
|
let list: Array<PackImageReader | IEmoji> = [];
|
||||||
list = list.concat(imagePacks.flatMap((pack) => pack.getImagesFor(usage)));
|
list = list.concat(imagePacks.flatMap((pack) => pack.getImages(usage)));
|
||||||
if (emojiTab) list = list.concat(emojis);
|
if (emojiTab) list = list.concat(emojis);
|
||||||
return list;
|
return list;
|
||||||
}, [emojiTab, usage, imagePacks]);
|
}, [emojiTab, usage, imagePacks]);
|
||||||
@@ -682,7 +717,7 @@ export function EmojiBoard({
|
|||||||
const syncActiveGroupId = useCallback(() => {
|
const syncActiveGroupId = useCallback(() => {
|
||||||
const targetEl = contentScrollRef.current;
|
const targetEl = contentScrollRef.current;
|
||||||
if (!targetEl) return;
|
if (!targetEl) return;
|
||||||
const groupEls = [...targetEl.querySelectorAll('div[data-group-id]')] as HTMLElement[];
|
const groupEls = Array.from(targetEl.querySelectorAll('div[data-group-id]')) as HTMLElement[];
|
||||||
const groupEl = groupEls.find((el) => isIntersectingScrollView(targetEl, el));
|
const groupEl = groupEls.find((el) => isIntersectingScrollView(targetEl, el));
|
||||||
const groupId = groupEl?.getAttribute('data-group-id') ?? undefined;
|
const groupId = groupEl?.getAttribute('data-group-id') ?? undefined;
|
||||||
setActiveGroupId(groupId);
|
setActiveGroupId(groupId);
|
||||||
@@ -729,14 +764,17 @@ export function EmojiBoard({
|
|||||||
} else if (emojiInfo.type === EmojiType.CustomEmoji && emojiPreviewRef.current) {
|
} else if (emojiInfo.type === EmojiType.CustomEmoji && emojiPreviewRef.current) {
|
||||||
const img = document.createElement('img');
|
const img = document.createElement('img');
|
||||||
img.className = css.CustomEmojiImg;
|
img.className = css.CustomEmojiImg;
|
||||||
img.setAttribute('src', mx.mxcUrlToHttp(emojiInfo.data) || emojiInfo.data);
|
img.setAttribute(
|
||||||
|
'src',
|
||||||
|
mxcUrlToHttp(mx, emojiInfo.data, useAuthentication) || emojiInfo.data
|
||||||
|
);
|
||||||
img.setAttribute('alt', emojiInfo.shortcode);
|
img.setAttribute('alt', emojiInfo.shortcode);
|
||||||
emojiPreviewRef.current.textContent = '';
|
emojiPreviewRef.current.textContent = '';
|
||||||
emojiPreviewRef.current.appendChild(img);
|
emojiPreviewRef.current.appendChild(img);
|
||||||
}
|
}
|
||||||
emojiPreviewTextRef.current.textContent = `:${emojiInfo.shortcode}:`;
|
emojiPreviewTextRef.current.textContent = `:${emojiInfo.shortcode}:`;
|
||||||
},
|
},
|
||||||
[mx]
|
[mx, useAuthentication]
|
||||||
);
|
);
|
||||||
|
|
||||||
const throttleEmojiHover = useThrottle(handleEmojiPreview, {
|
const throttleEmojiHover = useThrottle(handleEmojiPreview, {
|
||||||
@@ -775,6 +813,7 @@ export function EmojiBoard({
|
|||||||
!editableActiveElement() && isKeyHotkey(['arrowdown', 'arrowright'], evt),
|
!editableActiveElement() && isKeyHotkey(['arrowdown', 'arrowright'], evt),
|
||||||
isKeyBackward: (evt: KeyboardEvent) =>
|
isKeyBackward: (evt: KeyboardEvent) =>
|
||||||
!editableActiveElement() && isKeyHotkey(['arrowup', 'arrowleft'], evt),
|
!editableActiveElement() && isKeyHotkey(['arrowup', 'arrowleft'], evt),
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<EmojiBoardLayout
|
<EmojiBoardLayout
|
||||||
@@ -828,6 +867,7 @@ export function EmojiBoard({
|
|||||||
usage={usage}
|
usage={usage}
|
||||||
packs={imagePacks}
|
packs={imagePacks}
|
||||||
onItemClick={handleScrollToGroup}
|
onItemClick={handleScrollToGroup}
|
||||||
|
useAuthentication={useAuthentication}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{emojiTab && (
|
{emojiTab && (
|
||||||
@@ -889,13 +929,22 @@ export function EmojiBoard({
|
|||||||
id={SEARCH_GROUP_ID}
|
id={SEARCH_GROUP_ID}
|
||||||
label={result.items.length ? 'Search Results' : 'No Results found'}
|
label={result.items.length ? 'Search Results' : 'No Results found'}
|
||||||
emojis={result.items}
|
emojis={result.items}
|
||||||
|
useAuthentication={useAuthentication}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{emojiTab && recentEmojis.length > 0 && (
|
{emojiTab && recentEmojis.length > 0 && (
|
||||||
<RecentEmojiGroup id={RECENT_GROUP_ID} label="Recent" emojis={recentEmojis} />
|
<RecentEmojiGroup id={RECENT_GROUP_ID} label="Recent" emojis={recentEmojis} />
|
||||||
)}
|
)}
|
||||||
{emojiTab && <CustomEmojiGroups mx={mx} groups={imagePacks} />}
|
{emojiTab && (
|
||||||
{stickerTab && <StickerGroups mx={mx} groups={imagePacks} />}
|
<CustomEmojiGroups
|
||||||
|
mx={mx}
|
||||||
|
groups={imagePacks}
|
||||||
|
useAuthentication={useAuthentication}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{stickerTab && (
|
||||||
|
<StickerGroups mx={mx} groups={imagePacks} useAuthentication={useAuthentication} />
|
||||||
|
)}
|
||||||
{emojiTab && <NativeEmojiGroups groups={emojiGroups} labels={emojiGroupLabels} />}
|
{emojiTab && <NativeEmojiGroups groups={emojiGroups} labels={emojiGroupLabels} />}
|
||||||
</Box>
|
</Box>
|
||||||
</Scroll>
|
</Scroll>
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ import React from 'react';
|
|||||||
import classNames from 'classnames';
|
import classNames from 'classnames';
|
||||||
import {
|
import {
|
||||||
Avatar,
|
Avatar,
|
||||||
AvatarFallback,
|
|
||||||
AvatarImage,
|
|
||||||
Box,
|
Box,
|
||||||
Header,
|
Header,
|
||||||
Icon,
|
Icon,
|
||||||
@@ -21,8 +19,9 @@ import { getMemberDisplayName } from '../../utils/room';
|
|||||||
import { getMxIdLocalPart } from '../../utils/matrix';
|
import { getMxIdLocalPart } from '../../utils/matrix';
|
||||||
import * as css from './EventReaders.css';
|
import * as css from './EventReaders.css';
|
||||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
import colorMXID from '../../../util/colorMXID';
|
|
||||||
import { openProfileViewer } from '../../../client/action/navigation';
|
import { openProfileViewer } from '../../../client/action/navigation';
|
||||||
|
import { UserAvatar } from '../user-avatar';
|
||||||
|
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||||
|
|
||||||
export type EventReadersProps = {
|
export type EventReadersProps = {
|
||||||
room: Room;
|
room: Room;
|
||||||
@@ -32,6 +31,7 @@ export type EventReadersProps = {
|
|||||||
export const EventReaders = as<'div', EventReadersProps>(
|
export const EventReaders = as<'div', EventReadersProps>(
|
||||||
({ className, room, eventId, requestClose, ...props }, ref) => {
|
({ className, room, eventId, requestClose, ...props }, ref) => {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
|
const useAuthentication = useMediaAuthentication();
|
||||||
const latestEventReaders = useRoomEventReaders(room, eventId);
|
const latestEventReaders = useRoomEventReaders(room, eventId);
|
||||||
|
|
||||||
const getName = (userId: string) =>
|
const getName = (userId: string) =>
|
||||||
@@ -57,9 +57,10 @@ export const EventReaders = as<'div', EventReadersProps>(
|
|||||||
<Box className={css.Content} direction="Column">
|
<Box className={css.Content} direction="Column">
|
||||||
{latestEventReaders.map((readerId) => {
|
{latestEventReaders.map((readerId) => {
|
||||||
const name = getName(readerId);
|
const name = getName(readerId);
|
||||||
const avatarUrl = room
|
const avatarMxcUrl = room
|
||||||
.getMember(readerId)
|
.getMember(readerId)
|
||||||
?.getAvatarUrl(mx.baseUrl, 100, 100, 'crop', undefined, false);
|
?.getMxcAvatarUrl();
|
||||||
|
const avatarUrl = avatarMxcUrl ? mx.mxcUrlToHttp(avatarMxcUrl, 100, 100, 'crop', undefined, false, useAuthentication) : undefined;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MenuItem
|
<MenuItem
|
||||||
@@ -72,18 +73,12 @@ export const EventReaders = as<'div', EventReadersProps>(
|
|||||||
}}
|
}}
|
||||||
before={
|
before={
|
||||||
<Avatar size="200">
|
<Avatar size="200">
|
||||||
{avatarUrl ? (
|
<UserAvatar
|
||||||
<AvatarImage src={avatarUrl} />
|
userId={readerId}
|
||||||
) : (
|
src={avatarUrl ?? undefined}
|
||||||
<AvatarFallback
|
alt={name}
|
||||||
style={{
|
renderFallback={() => <Icon size="50" src={Icons.User} filled />}
|
||||||
background: colorMXID(readerId),
|
/>
|
||||||
color: 'white',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Text size="H6">{name[0]}</Text>
|
|
||||||
</AvatarFallback>
|
|
||||||
)}
|
|
||||||
</Avatar>
|
</Avatar>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
|||||||
35
src/app/components/image-editor/ImageEditor.css.ts
Normal file
35
src/app/components/image-editor/ImageEditor.css.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { style } from '@vanilla-extract/css';
|
||||||
|
import { DefaultReset, color, config } from 'folds';
|
||||||
|
|
||||||
|
export const ImageEditor = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
height: '100%',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const ImageEditorHeader = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
paddingLeft: config.space.S200,
|
||||||
|
paddingRight: config.space.S200,
|
||||||
|
borderBottomWidth: config.borderWidth.B300,
|
||||||
|
flexShrink: 0,
|
||||||
|
gap: config.space.S200,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const ImageEditorContent = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
backgroundColor: color.Background.Container,
|
||||||
|
color: color.Background.OnContainer,
|
||||||
|
overflow: 'hidden',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const Image = style({
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
objectFit: 'contain',
|
||||||
|
});
|
||||||
51
src/app/components/image-editor/ImageEditor.tsx
Normal file
51
src/app/components/image-editor/ImageEditor.tsx
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import classNames from 'classnames';
|
||||||
|
import { Box, Chip, Header, Icon, IconButton, Icons, Text, as } from 'folds';
|
||||||
|
import * as css from './ImageEditor.css';
|
||||||
|
|
||||||
|
export type ImageEditorProps = {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
requestClose: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ImageEditor = as<'div', ImageEditorProps>(
|
||||||
|
({ className, name, url, requestClose, ...props }, ref) => {
|
||||||
|
const handleApply = () => {
|
||||||
|
//
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
className={classNames(css.ImageEditor, className)}
|
||||||
|
direction="Column"
|
||||||
|
{...props}
|
||||||
|
ref={ref}
|
||||||
|
>
|
||||||
|
<Header className={css.ImageEditorHeader} size="400">
|
||||||
|
<Box grow="Yes" alignItems="Center" gap="200">
|
||||||
|
<IconButton size="300" radii="300" onClick={requestClose}>
|
||||||
|
<Icon size="50" src={Icons.ArrowLeft} />
|
||||||
|
</IconButton>
|
||||||
|
<Text size="T300" truncate>
|
||||||
|
Image Editor
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
<Box shrink="No" alignItems="Center" gap="200">
|
||||||
|
<Chip variant="Primary" radii="300" onClick={handleApply}>
|
||||||
|
<Text size="B300">Save</Text>
|
||||||
|
</Chip>
|
||||||
|
</Box>
|
||||||
|
</Header>
|
||||||
|
<Box
|
||||||
|
grow="Yes"
|
||||||
|
className={css.ImageEditorContent}
|
||||||
|
justifyContent="Center"
|
||||||
|
alignItems="Center"
|
||||||
|
>
|
||||||
|
<img className={css.Image} src={url} alt={name} />
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
1
src/app/components/image-editor/index.ts
Normal file
1
src/app/components/image-editor/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './ImageEditor';
|
||||||
388
src/app/components/image-pack-view/ImagePackContent.tsx
Normal file
388
src/app/components/image-pack-view/ImagePackContent.tsx
Normal file
@@ -0,0 +1,388 @@
|
|||||||
|
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
|
import { as, Box, Text, config, Button, Menu, Spinner } from 'folds';
|
||||||
|
import {
|
||||||
|
ImagePack,
|
||||||
|
ImageUsage,
|
||||||
|
PackContent,
|
||||||
|
PackImage,
|
||||||
|
PackImageReader,
|
||||||
|
packMetaEqual,
|
||||||
|
PackMetaReader,
|
||||||
|
} from '../../plugins/custom-emoji';
|
||||||
|
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||||
|
import { SequenceCard } from '../sequence-card';
|
||||||
|
import { ImageTile, ImageTileEdit, ImageTileUpload } from './ImageTile';
|
||||||
|
import { SettingTile } from '../setting-tile';
|
||||||
|
import { UsageSwitcher } from './UsageSwitcher';
|
||||||
|
import { ImagePackProfile, ImagePackProfileEdit } from './PackMeta';
|
||||||
|
import * as css from './style.css';
|
||||||
|
import { useFilePicker } from '../../hooks/useFilePicker';
|
||||||
|
import { CompactUploadCardRenderer } from '../upload-card';
|
||||||
|
import { UploadSuccess } from '../../state/upload';
|
||||||
|
import { getImageInfo, TUploadContent } from '../../utils/matrix';
|
||||||
|
import { getImageFileUrl, loadImageElement, renameFile } from '../../utils/dom';
|
||||||
|
import { replaceSpaceWithDash, suffixRename } from '../../utils/common';
|
||||||
|
import { getFileNameWithoutExt } from '../../utils/mimeTypes';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
||||||
|
|
||||||
|
export type ImagePackContentProps = {
|
||||||
|
imagePack: ImagePack;
|
||||||
|
canEdit?: boolean;
|
||||||
|
onUpdate?: (packContent: PackContent) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ImagePackContent = as<'div', ImagePackContentProps>(
|
||||||
|
({ imagePack, canEdit, onUpdate, ...props }, ref) => {
|
||||||
|
const useAuthentication = useMediaAuthentication();
|
||||||
|
|
||||||
|
const [metaEditing, setMetaEditing] = useState(false);
|
||||||
|
const [savedMeta, setSavedMeta] = useState<PackMetaReader>();
|
||||||
|
const currentMeta = savedMeta ?? imagePack.meta;
|
||||||
|
|
||||||
|
const images = useMemo(() => Array.from(imagePack.images.collection.values()), [imagePack]);
|
||||||
|
const [files, setFiles] = useState<File[]>([]);
|
||||||
|
const [uploadedImages, setUploadedImages] = useState<PackImageReader[]>([]);
|
||||||
|
const [imagesEditing, setImagesEditing] = useState<Set<string>>(new Set());
|
||||||
|
const [savedImages, setSavedImages] = useState<Map<string, PackImageReader>>(new Map());
|
||||||
|
const [deleteImages, setDeleteImages] = useState<Set<string>>(new Set());
|
||||||
|
|
||||||
|
const hasImageWithShortcode = useCallback(
|
||||||
|
(shortcode: string): boolean => {
|
||||||
|
const hasInPack = imagePack.images.collection.has(shortcode);
|
||||||
|
if (hasInPack) return true;
|
||||||
|
const hasInUploaded =
|
||||||
|
uploadedImages.find((img) => img.shortcode === shortcode) !== undefined;
|
||||||
|
if (hasInUploaded) return true;
|
||||||
|
const hasInSaved =
|
||||||
|
Array.from(savedImages).find(([, img]) => img.shortcode === shortcode) !== undefined;
|
||||||
|
return hasInSaved;
|
||||||
|
},
|
||||||
|
[imagePack, savedImages, uploadedImages]
|
||||||
|
);
|
||||||
|
|
||||||
|
const pickFiles = useFilePicker(
|
||||||
|
useCallback(
|
||||||
|
(pickedFiles: File[]) => {
|
||||||
|
const uniqueFiles = pickedFiles.map((file) => {
|
||||||
|
const fileName = replaceSpaceWithDash(file.name);
|
||||||
|
if (hasImageWithShortcode(fileName)) {
|
||||||
|
const uniqueName = suffixRename(fileName, hasImageWithShortcode);
|
||||||
|
return renameFile(file, uniqueName);
|
||||||
|
}
|
||||||
|
return fileName !== file.name ? renameFile(file, fileName) : file;
|
||||||
|
});
|
||||||
|
|
||||||
|
setFiles((f) => [...f, ...uniqueFiles]);
|
||||||
|
},
|
||||||
|
[hasImageWithShortcode]
|
||||||
|
),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleMetaSave = useCallback(
|
||||||
|
(editedMeta: PackMetaReader) => {
|
||||||
|
setMetaEditing(false);
|
||||||
|
setSavedMeta(
|
||||||
|
(m) =>
|
||||||
|
new PackMetaReader({
|
||||||
|
...imagePack.meta.content,
|
||||||
|
...m?.content,
|
||||||
|
...editedMeta.content,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[imagePack.meta]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleMetaCancel = () => setMetaEditing(false);
|
||||||
|
|
||||||
|
const handlePackUsageChange = useCallback(
|
||||||
|
(usg: ImageUsage[]) => {
|
||||||
|
setSavedMeta(
|
||||||
|
(m) =>
|
||||||
|
new PackMetaReader({
|
||||||
|
...imagePack.meta.content,
|
||||||
|
...m?.content,
|
||||||
|
usage: usg,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[imagePack.meta]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleUploadRemove = useCallback((file: TUploadContent) => {
|
||||||
|
setFiles((fs) => fs.filter((f) => f !== file));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleUploadComplete = useCallback(
|
||||||
|
async (data: UploadSuccess) => {
|
||||||
|
const imgEl = await loadImageElement(getImageFileUrl(data.file));
|
||||||
|
const packImage: PackImage = {
|
||||||
|
url: data.mxc,
|
||||||
|
info: getImageInfo(imgEl, data.file),
|
||||||
|
};
|
||||||
|
const image = PackImageReader.fromPackImage(
|
||||||
|
getFileNameWithoutExt(data.file.name),
|
||||||
|
packImage
|
||||||
|
);
|
||||||
|
if (!image) return;
|
||||||
|
handleUploadRemove(data.file);
|
||||||
|
setUploadedImages((imgs) => [image, ...imgs]);
|
||||||
|
},
|
||||||
|
[handleUploadRemove]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleImageEdit = (shortcode: string) => {
|
||||||
|
setImagesEditing((shortcodes) => {
|
||||||
|
const shortcodeSet = new Set(shortcodes);
|
||||||
|
shortcodeSet.add(shortcode);
|
||||||
|
return shortcodeSet;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const handleDeleteToggle = (shortcode: string) => {
|
||||||
|
setDeleteImages((shortcodes) => {
|
||||||
|
const shortcodeSet = new Set(shortcodes);
|
||||||
|
if (shortcodeSet.has(shortcode)) shortcodeSet.delete(shortcode);
|
||||||
|
else shortcodeSet.add(shortcode);
|
||||||
|
return shortcodeSet;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImageEditCancel = (shortcode: string) => {
|
||||||
|
setImagesEditing((shortcodes) => {
|
||||||
|
const shortcodeSet = new Set(shortcodes);
|
||||||
|
shortcodeSet.delete(shortcode);
|
||||||
|
return shortcodeSet;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImageEditSave = (shortcode: string, image: PackImageReader) => {
|
||||||
|
handleImageEditCancel(shortcode);
|
||||||
|
|
||||||
|
const saveImage =
|
||||||
|
shortcode !== image.shortcode && hasImageWithShortcode(image.shortcode)
|
||||||
|
? new PackImageReader(
|
||||||
|
suffixRename(image.shortcode, hasImageWithShortcode),
|
||||||
|
image.url,
|
||||||
|
image.content
|
||||||
|
)
|
||||||
|
: image;
|
||||||
|
|
||||||
|
setSavedImages((sImgs) => {
|
||||||
|
const imgs = new Map(sImgs);
|
||||||
|
imgs.set(shortcode, saveImage);
|
||||||
|
return imgs;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleResetSavedChanges = () => {
|
||||||
|
setSavedMeta(undefined);
|
||||||
|
setFiles([]);
|
||||||
|
setUploadedImages([]);
|
||||||
|
setSavedImages(new Map());
|
||||||
|
setDeleteImages(new Set());
|
||||||
|
};
|
||||||
|
|
||||||
|
const [applyState, applyChanges] = useAsyncCallback(
|
||||||
|
useCallback(async () => {
|
||||||
|
const pack: PackContent = {
|
||||||
|
pack: savedMeta?.content ?? imagePack.meta.content,
|
||||||
|
images: {},
|
||||||
|
};
|
||||||
|
const pushImage = (img: PackImageReader) => {
|
||||||
|
if (deleteImages.has(img.shortcode)) return;
|
||||||
|
if (!pack.images) return;
|
||||||
|
const imgToPush = savedImages.get(img.shortcode) ?? img;
|
||||||
|
pack.images[imgToPush.shortcode] = imgToPush.content;
|
||||||
|
};
|
||||||
|
uploadedImages.forEach((img) => pushImage(img));
|
||||||
|
images.forEach((img) => pushImage(img));
|
||||||
|
|
||||||
|
return onUpdate?.(pack);
|
||||||
|
}, [imagePack, images, savedMeta, uploadedImages, savedImages, deleteImages, onUpdate])
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (applyState.status === AsyncStatus.Success) {
|
||||||
|
handleResetSavedChanges();
|
||||||
|
}
|
||||||
|
}, [applyState]);
|
||||||
|
|
||||||
|
const savedChanges =
|
||||||
|
(savedMeta && !packMetaEqual(imagePack.meta, savedMeta)) ||
|
||||||
|
uploadedImages.length > 0 ||
|
||||||
|
savedImages.size > 0 ||
|
||||||
|
deleteImages.size > 0;
|
||||||
|
const canApplyChanges = !metaEditing && imagesEditing.size === 0 && files.length === 0;
|
||||||
|
const applying = applyState.status === AsyncStatus.Loading;
|
||||||
|
|
||||||
|
const renderImage = (image: PackImageReader) => (
|
||||||
|
<SequenceCard
|
||||||
|
key={image.shortcode}
|
||||||
|
style={{ padding: config.space.S300 }}
|
||||||
|
variant={deleteImages.has(image.shortcode) ? 'Critical' : 'SurfaceVariant'}
|
||||||
|
direction="Column"
|
||||||
|
gap="400"
|
||||||
|
>
|
||||||
|
{imagesEditing.has(image.shortcode) ? (
|
||||||
|
<ImageTileEdit
|
||||||
|
defaultShortcode={image.shortcode}
|
||||||
|
image={savedImages.get(image.shortcode) ?? image}
|
||||||
|
packUsage={currentMeta.usage}
|
||||||
|
useAuthentication={useAuthentication}
|
||||||
|
onCancel={handleImageEditCancel}
|
||||||
|
onSave={handleImageEditSave}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<ImageTile
|
||||||
|
defaultShortcode={image.shortcode}
|
||||||
|
image={savedImages.get(image.shortcode) ?? image}
|
||||||
|
packUsage={currentMeta.usage}
|
||||||
|
useAuthentication={useAuthentication}
|
||||||
|
canEdit={canEdit}
|
||||||
|
onEdit={handleImageEdit}
|
||||||
|
deleted={deleteImages.has(image.shortcode)}
|
||||||
|
onDeleteToggle={handleDeleteToggle}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</SequenceCard>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box grow="Yes" direction="Column" gap="700" {...props} ref={ref}>
|
||||||
|
{savedChanges && (
|
||||||
|
<Menu className={css.UnsavedMenu} variant="Success">
|
||||||
|
<Box alignItems="Center" gap="400">
|
||||||
|
<Box grow="Yes" direction="Column">
|
||||||
|
{applyState.status === AsyncStatus.Error ? (
|
||||||
|
<Text size="T200">
|
||||||
|
<b>Failed to apply changes! Please try again.</b>
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
<Text size="T200">
|
||||||
|
<b>Changes saved! Apply when ready.</b>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Box shrink="No" gap="200">
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
variant="Success"
|
||||||
|
fill="None"
|
||||||
|
radii="300"
|
||||||
|
disabled={!canApplyChanges || applying}
|
||||||
|
onClick={handleResetSavedChanges}
|
||||||
|
>
|
||||||
|
<Text size="B300">Reset</Text>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
variant="Success"
|
||||||
|
radii="300"
|
||||||
|
disabled={!canApplyChanges || applying}
|
||||||
|
before={applying && <Spinner variant="Success" fill="Solid" size="100" />}
|
||||||
|
onClick={applyChanges}
|
||||||
|
>
|
||||||
|
<Text size="B300">Apply Changes</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Menu>
|
||||||
|
)}
|
||||||
|
<Box direction="Column" gap="100">
|
||||||
|
<Text size="L400">Pack</Text>
|
||||||
|
<SequenceCard
|
||||||
|
style={{ padding: config.space.S300 }}
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
direction="Column"
|
||||||
|
gap="400"
|
||||||
|
>
|
||||||
|
{metaEditing ? (
|
||||||
|
<ImagePackProfileEdit
|
||||||
|
meta={currentMeta}
|
||||||
|
onCancel={handleMetaCancel}
|
||||||
|
onSave={handleMetaSave}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<ImagePackProfile
|
||||||
|
meta={currentMeta}
|
||||||
|
canEdit={canEdit}
|
||||||
|
onEdit={() => setMetaEditing(true)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</SequenceCard>
|
||||||
|
<SequenceCard
|
||||||
|
style={{ padding: config.space.S300 }}
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
direction="Column"
|
||||||
|
gap="400"
|
||||||
|
>
|
||||||
|
<SettingTile
|
||||||
|
title="Images Usage"
|
||||||
|
description="Select how the images are being used: as emojis, as stickers, or as both."
|
||||||
|
after={
|
||||||
|
<UsageSwitcher
|
||||||
|
usage={currentMeta.usage}
|
||||||
|
canEdit={canEdit}
|
||||||
|
onChange={handlePackUsageChange}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</SequenceCard>
|
||||||
|
</Box>
|
||||||
|
{images.length === 0 && !canEdit ? null : (
|
||||||
|
<Box direction="Column" gap="100">
|
||||||
|
<Text size="L400">Images</Text>
|
||||||
|
{canEdit && (
|
||||||
|
<SequenceCard
|
||||||
|
style={{ padding: config.space.S300 }}
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
direction="Column"
|
||||||
|
gap="400"
|
||||||
|
>
|
||||||
|
<SettingTile
|
||||||
|
title="Upload Images"
|
||||||
|
description="Select images from your storage to upload them in pack."
|
||||||
|
after={
|
||||||
|
<Button
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
type="button"
|
||||||
|
outlined
|
||||||
|
onClick={() => pickFiles('image/*')}
|
||||||
|
>
|
||||||
|
<Text size="B300">Select</Text>
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</SequenceCard>
|
||||||
|
)}
|
||||||
|
{files.map((file) => (
|
||||||
|
<SequenceCard
|
||||||
|
key={file.name}
|
||||||
|
style={{ padding: config.space.S300 }}
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
direction="Column"
|
||||||
|
gap="400"
|
||||||
|
>
|
||||||
|
<ImageTileUpload file={file}>
|
||||||
|
{(uploadAtom) => (
|
||||||
|
<CompactUploadCardRenderer
|
||||||
|
uploadAtom={uploadAtom}
|
||||||
|
onRemove={handleUploadRemove}
|
||||||
|
onComplete={handleUploadComplete}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</ImageTileUpload>
|
||||||
|
</SequenceCard>
|
||||||
|
))}
|
||||||
|
{uploadedImages.map(renderImage)}
|
||||||
|
{images.map(renderImage)}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
51
src/app/components/image-pack-view/ImagePackView.tsx
Normal file
51
src/app/components/image-pack-view/ImagePackView.tsx
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Box, IconButton, Text, Icon, Icons, Scroll, Chip } from 'folds';
|
||||||
|
import { PackAddress } from '../../plugins/custom-emoji';
|
||||||
|
import { Page, PageHeader, PageContent } from '../page';
|
||||||
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
|
import { RoomImagePack } from './RoomImagePack';
|
||||||
|
import { UserImagePack } from './UserImagePack';
|
||||||
|
|
||||||
|
type ImagePackViewProps = {
|
||||||
|
address: PackAddress | undefined;
|
||||||
|
requestClose: () => void;
|
||||||
|
};
|
||||||
|
export function ImagePackView({ address, requestClose }: ImagePackViewProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const room = address && mx.getRoom(address.roomId);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Page>
|
||||||
|
<PageHeader outlined={false} balance>
|
||||||
|
<Box alignItems="Center" grow="Yes" gap="200">
|
||||||
|
<Box alignItems="Inherit" grow="Yes" gap="200">
|
||||||
|
<Chip
|
||||||
|
size="500"
|
||||||
|
radii="Pill"
|
||||||
|
onClick={requestClose}
|
||||||
|
before={<Icon size="100" src={Icons.ArrowLeft} />}
|
||||||
|
>
|
||||||
|
<Text size="T300">Emojis & Stickers</Text>
|
||||||
|
</Chip>
|
||||||
|
</Box>
|
||||||
|
<Box shrink="No">
|
||||||
|
<IconButton onClick={requestClose} variant="Surface">
|
||||||
|
<Icon src={Icons.Cross} />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</PageHeader>
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Scroll hideTrack visibility="Hover">
|
||||||
|
<PageContent>
|
||||||
|
{room && address ? (
|
||||||
|
<RoomImagePack room={room} stateKey={address.stateKey} />
|
||||||
|
) : (
|
||||||
|
<UserImagePack />
|
||||||
|
)}
|
||||||
|
</PageContent>
|
||||||
|
</Scroll>
|
||||||
|
</Box>
|
||||||
|
</Page>
|
||||||
|
);
|
||||||
|
}
|
||||||
214
src/app/components/image-pack-view/ImageTile.tsx
Normal file
214
src/app/components/image-pack-view/ImageTile.tsx
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
import React, { FormEventHandler, ReactNode, useMemo, useState } from 'react';
|
||||||
|
import { Badge, Box, Button, Chip, Icon, Icons, Input, Text } from 'folds';
|
||||||
|
import { UsageSwitcher, useUsageStr } from './UsageSwitcher';
|
||||||
|
import { mxcUrlToHttp } from '../../utils/matrix';
|
||||||
|
import * as css from './style.css';
|
||||||
|
import { ImageUsage, imageUsageEqual, PackImageReader } from '../../plugins/custom-emoji';
|
||||||
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
|
import { SettingTile } from '../setting-tile';
|
||||||
|
import { useObjectURL } from '../../hooks/useObjectURL';
|
||||||
|
import { createUploadAtom, TUploadAtom } from '../../state/upload';
|
||||||
|
import { replaceSpaceWithDash } from '../../utils/common';
|
||||||
|
|
||||||
|
type ImageTileProps = {
|
||||||
|
defaultShortcode: string;
|
||||||
|
useAuthentication: boolean;
|
||||||
|
packUsage: ImageUsage[];
|
||||||
|
image: PackImageReader;
|
||||||
|
canEdit?: boolean;
|
||||||
|
onEdit?: (defaultShortcode: string, image: PackImageReader) => void;
|
||||||
|
deleted?: boolean;
|
||||||
|
onDeleteToggle?: (defaultShortcode: string) => void;
|
||||||
|
};
|
||||||
|
export function ImageTile({
|
||||||
|
defaultShortcode,
|
||||||
|
image,
|
||||||
|
packUsage,
|
||||||
|
useAuthentication,
|
||||||
|
canEdit,
|
||||||
|
onEdit,
|
||||||
|
onDeleteToggle,
|
||||||
|
deleted,
|
||||||
|
}: ImageTileProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const getUsageStr = useUsageStr();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SettingTile
|
||||||
|
before={
|
||||||
|
<img
|
||||||
|
className={css.ImagePackImage}
|
||||||
|
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? ''}
|
||||||
|
alt={image.shortcode}
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
title={
|
||||||
|
deleted ? (
|
||||||
|
<span className={css.DeleteImageShortcode}>{image.shortcode}</span>
|
||||||
|
) : (
|
||||||
|
image.shortcode
|
||||||
|
)
|
||||||
|
}
|
||||||
|
description={
|
||||||
|
<Box as="span" gap="200">
|
||||||
|
{image.usage && getUsageStr(image.usage) !== getUsageStr(packUsage) && (
|
||||||
|
<Badge as="span" variant="Secondary" size="400" radii="300" outlined>
|
||||||
|
<Text as="span" size="L400">
|
||||||
|
{getUsageStr(image.usage)}
|
||||||
|
</Text>
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
{image.body}
|
||||||
|
</Box>
|
||||||
|
}
|
||||||
|
after={
|
||||||
|
canEdit ? (
|
||||||
|
<Box shrink="No" alignItems="Center" gap="200">
|
||||||
|
<Chip
|
||||||
|
variant={deleted ? 'Critical' : 'Secondary'}
|
||||||
|
fill="None"
|
||||||
|
radii="Pill"
|
||||||
|
onClick={() => onDeleteToggle?.(defaultShortcode)}
|
||||||
|
>
|
||||||
|
{deleted ? <Text size="B300">Undo</Text> : <Icon size="50" src={Icons.Delete} />}
|
||||||
|
</Chip>
|
||||||
|
{!deleted && (
|
||||||
|
<Chip
|
||||||
|
variant="Secondary"
|
||||||
|
radii="Pill"
|
||||||
|
onClick={() => onEdit?.(defaultShortcode, image)}
|
||||||
|
>
|
||||||
|
<Text size="B300">Edit</Text>
|
||||||
|
</Chip>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
) : undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImageTileUploadProps = {
|
||||||
|
file: File;
|
||||||
|
children: (uploadAtom: TUploadAtom) => ReactNode;
|
||||||
|
};
|
||||||
|
export function ImageTileUpload({ file, children }: ImageTileUploadProps) {
|
||||||
|
const url = useObjectURL(file);
|
||||||
|
const uploadAtom = useMemo(() => createUploadAtom(file), [file]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SettingTile before={<img className={css.ImagePackImage} src={url} alt={file.name} />}>
|
||||||
|
{children(uploadAtom)}
|
||||||
|
</SettingTile>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImageTileEditProps = {
|
||||||
|
defaultShortcode: string;
|
||||||
|
useAuthentication: boolean;
|
||||||
|
packUsage: ImageUsage[];
|
||||||
|
image: PackImageReader;
|
||||||
|
onCancel: (shortcode: string) => void;
|
||||||
|
onSave: (shortcode: string, image: PackImageReader) => void;
|
||||||
|
};
|
||||||
|
export function ImageTileEdit({
|
||||||
|
defaultShortcode,
|
||||||
|
useAuthentication,
|
||||||
|
packUsage,
|
||||||
|
image,
|
||||||
|
onCancel,
|
||||||
|
onSave,
|
||||||
|
}: ImageTileEditProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const defaultUsage = image.usage ?? packUsage;
|
||||||
|
|
||||||
|
const [unsavedUsage, setUnsavedUsages] = useState(defaultUsage);
|
||||||
|
|
||||||
|
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
|
||||||
|
evt.preventDefault();
|
||||||
|
|
||||||
|
const target = evt.target as HTMLFormElement | undefined;
|
||||||
|
const shortcodeInput = target?.shortcodeInput as HTMLInputElement | undefined;
|
||||||
|
const bodyInput = target?.bodyInput as HTMLTextAreaElement | undefined;
|
||||||
|
if (!shortcodeInput || !bodyInput) return;
|
||||||
|
|
||||||
|
const shortcode = replaceSpaceWithDash(shortcodeInput.value.trim());
|
||||||
|
const body = bodyInput.value.trim() || undefined;
|
||||||
|
const usage = unsavedUsage;
|
||||||
|
|
||||||
|
if (!shortcode) return;
|
||||||
|
|
||||||
|
if (
|
||||||
|
shortcode === image.shortcode &&
|
||||||
|
body === image.body &&
|
||||||
|
imageUsageEqual(usage, defaultUsage)
|
||||||
|
) {
|
||||||
|
onCancel(defaultShortcode);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const imageReader = new PackImageReader(shortcode, image.url, {
|
||||||
|
info: image.info,
|
||||||
|
body,
|
||||||
|
usage: imageUsageEqual(usage, packUsage) ? undefined : usage,
|
||||||
|
});
|
||||||
|
|
||||||
|
onSave(defaultShortcode, imageReader);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SettingTile
|
||||||
|
before={
|
||||||
|
<img
|
||||||
|
className={css.ImagePackImage}
|
||||||
|
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? ''}
|
||||||
|
alt={image.shortcode}
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Box as="form" onSubmit={handleSubmit} direction="Column" gap="200">
|
||||||
|
<Box direction="Column" className={css.ImagePackImageInputs}>
|
||||||
|
<Input
|
||||||
|
before={<Text size="L400">Shortcode:</Text>}
|
||||||
|
defaultValue={image.shortcode}
|
||||||
|
name="shortcodeInput"
|
||||||
|
variant="Secondary"
|
||||||
|
size="300"
|
||||||
|
radii="0"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
before={<Text size="L400">Body:</Text>}
|
||||||
|
defaultValue={image.body}
|
||||||
|
name="bodyInput"
|
||||||
|
variant="Secondary"
|
||||||
|
size="300"
|
||||||
|
radii="0"
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Box gap="200">
|
||||||
|
<Box shrink="No" direction="Column">
|
||||||
|
<UsageSwitcher usage={unsavedUsage} onChange={setUnsavedUsages} canEdit />
|
||||||
|
</Box>
|
||||||
|
<Box grow="Yes" />
|
||||||
|
<Button type="submit" variant="Success" size="300" radii="300">
|
||||||
|
<Text size="B300">Save</Text>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="reset"
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
onClick={() => onCancel(defaultShortcode)}
|
||||||
|
>
|
||||||
|
<Text size="B300">Cancel</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</SettingTile>
|
||||||
|
);
|
||||||
|
}
|
||||||
232
src/app/components/image-pack-view/PackMeta.tsx
Normal file
232
src/app/components/image-pack-view/PackMeta.tsx
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
import React, { FormEventHandler, useCallback, useMemo, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Text,
|
||||||
|
Avatar,
|
||||||
|
AvatarImage,
|
||||||
|
AvatarFallback,
|
||||||
|
Button,
|
||||||
|
Icon,
|
||||||
|
Icons,
|
||||||
|
Input,
|
||||||
|
TextArea,
|
||||||
|
Chip,
|
||||||
|
} from 'folds';
|
||||||
|
import Linkify from 'linkify-react';
|
||||||
|
import { mxcUrlToHttp } from '../../utils/matrix';
|
||||||
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
|
import { nameInitials } from '../../utils/common';
|
||||||
|
import { BreakWord } from '../../styles/Text.css';
|
||||||
|
import { LINKIFY_OPTS } from '../../plugins/react-custom-html-parser';
|
||||||
|
import { ContainerColor } from '../../styles/ContainerColor.css';
|
||||||
|
import { useFilePicker } from '../../hooks/useFilePicker';
|
||||||
|
import { useObjectURL } from '../../hooks/useObjectURL';
|
||||||
|
import { createUploadAtom, UploadSuccess } from '../../state/upload';
|
||||||
|
import { CompactUploadCardRenderer } from '../upload-card';
|
||||||
|
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||||
|
import { PackMetaReader } from '../../plugins/custom-emoji';
|
||||||
|
|
||||||
|
type ImagePackAvatarProps = {
|
||||||
|
url?: string;
|
||||||
|
name?: string;
|
||||||
|
};
|
||||||
|
function ImagePackAvatar({ url, name }: ImagePackAvatarProps) {
|
||||||
|
return (
|
||||||
|
<Avatar size="500" className={ContainerColor({ variant: 'Secondary' })}>
|
||||||
|
{url ? (
|
||||||
|
<AvatarImage src={url} alt={name ?? 'Unknown'} />
|
||||||
|
) : (
|
||||||
|
<AvatarFallback>
|
||||||
|
<Text size="H2">{nameInitials(name ?? 'Unknown')}</Text>
|
||||||
|
</AvatarFallback>
|
||||||
|
)}
|
||||||
|
</Avatar>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImagePackProfileProps = {
|
||||||
|
meta: PackMetaReader;
|
||||||
|
canEdit?: boolean;
|
||||||
|
onEdit?: () => void;
|
||||||
|
};
|
||||||
|
export function ImagePackProfile({ meta, canEdit, onEdit }: ImagePackProfileProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const useAuthentication = useMediaAuthentication();
|
||||||
|
const avatarUrl = meta.avatar
|
||||||
|
? mxcUrlToHttp(mx, meta.avatar, useAuthentication) ?? undefined
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box gap="400">
|
||||||
|
<Box grow="Yes" direction="Column" gap="300">
|
||||||
|
<Box direction="Column" gap="100">
|
||||||
|
<Text className={BreakWord} size="H5">
|
||||||
|
{meta.name ?? 'Unknown'}
|
||||||
|
</Text>
|
||||||
|
{meta.attribution && (
|
||||||
|
<Text className={BreakWord} size="T200">
|
||||||
|
<Linkify options={LINKIFY_OPTS}>{meta.attribution}</Linkify>
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
{canEdit && (
|
||||||
|
<Box gap="200">
|
||||||
|
<Chip
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
radii="300"
|
||||||
|
before={<Icon size="50" src={Icons.Pencil} />}
|
||||||
|
onClick={onEdit}
|
||||||
|
outlined
|
||||||
|
>
|
||||||
|
<Text size="B300">Edit</Text>
|
||||||
|
</Chip>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Box shrink="No">
|
||||||
|
<ImagePackAvatar url={avatarUrl} name={meta.name} />
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImagePackProfileEditProps = {
|
||||||
|
meta: PackMetaReader;
|
||||||
|
onCancel: () => void;
|
||||||
|
onSave: (meta: PackMetaReader) => void;
|
||||||
|
};
|
||||||
|
export function ImagePackProfileEdit({ meta, onCancel, onSave }: ImagePackProfileEditProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const useAuthentication = useMediaAuthentication();
|
||||||
|
const [avatar, setAvatar] = useState(meta.avatar);
|
||||||
|
|
||||||
|
const avatarUrl = avatar ? mxcUrlToHttp(mx, avatar, useAuthentication) ?? undefined : undefined;
|
||||||
|
|
||||||
|
const [imageFile, setImageFile] = useState<File>();
|
||||||
|
const avatarFileUrl = useObjectURL(imageFile);
|
||||||
|
const uploadingAvatar = avatarFileUrl ? avatar === meta.avatar : false;
|
||||||
|
const uploadAtom = useMemo(() => {
|
||||||
|
if (imageFile) return createUploadAtom(imageFile);
|
||||||
|
return undefined;
|
||||||
|
}, [imageFile]);
|
||||||
|
|
||||||
|
const pickFile = useFilePicker(setImageFile, false);
|
||||||
|
|
||||||
|
const handleRemoveUpload = useCallback(() => {
|
||||||
|
setImageFile(undefined);
|
||||||
|
setAvatar(meta.avatar);
|
||||||
|
}, [meta.avatar]);
|
||||||
|
|
||||||
|
const handleUploaded = useCallback((upload: UploadSuccess) => {
|
||||||
|
setAvatar(upload.mxc);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
|
||||||
|
evt.preventDefault();
|
||||||
|
if (uploadingAvatar) return;
|
||||||
|
|
||||||
|
const target = evt.target as HTMLFormElement | undefined;
|
||||||
|
const nameInput = target?.nameInput as HTMLInputElement | undefined;
|
||||||
|
const attributionTextArea = target?.attributionTextArea as HTMLTextAreaElement | undefined;
|
||||||
|
if (!nameInput || !attributionTextArea) return;
|
||||||
|
|
||||||
|
const name = nameInput.value.trim();
|
||||||
|
const attribution = attributionTextArea.value.trim();
|
||||||
|
if (!name) return;
|
||||||
|
|
||||||
|
const metaReader = new PackMetaReader({
|
||||||
|
avatar_url: avatar,
|
||||||
|
display_name: name,
|
||||||
|
attribution,
|
||||||
|
});
|
||||||
|
onSave(metaReader);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box as="form" onSubmit={handleSubmit} direction="Column" gap="400">
|
||||||
|
<Box gap="400">
|
||||||
|
<Box grow="Yes" direction="Column" gap="100">
|
||||||
|
<Text size="L400">Pack Avatar</Text>
|
||||||
|
{uploadAtom ? (
|
||||||
|
<Box gap="200" direction="Column">
|
||||||
|
<CompactUploadCardRenderer
|
||||||
|
uploadAtom={uploadAtom}
|
||||||
|
onRemove={handleRemoveUpload}
|
||||||
|
onComplete={handleUploaded}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<Box gap="200">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="300"
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
radii="300"
|
||||||
|
onClick={() => pickFile('image/*')}
|
||||||
|
>
|
||||||
|
<Text size="B300">Upload</Text>
|
||||||
|
</Button>
|
||||||
|
{!avatar && meta.avatar && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="300"
|
||||||
|
variant="Success"
|
||||||
|
fill="None"
|
||||||
|
radii="300"
|
||||||
|
onClick={() => setAvatar(meta.avatar)}
|
||||||
|
>
|
||||||
|
<Text size="B300">Reset</Text>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{avatar && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="300"
|
||||||
|
variant="Critical"
|
||||||
|
fill="None"
|
||||||
|
radii="300"
|
||||||
|
onClick={() => setAvatar(undefined)}
|
||||||
|
>
|
||||||
|
<Text size="B300">Remove</Text>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Box shrink="No">
|
||||||
|
<ImagePackAvatar url={avatarFileUrl ?? avatarUrl} name={meta.name} />
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
<Box direction="Inherit" gap="100">
|
||||||
|
<Text size="L400">Name</Text>
|
||||||
|
<Input name="nameInput" defaultValue={meta.name} variant="Secondary" radii="300" required />
|
||||||
|
</Box>
|
||||||
|
<Box direction="Inherit" gap="100">
|
||||||
|
<Text size="L400">Attribution</Text>
|
||||||
|
<TextArea
|
||||||
|
name="attributionTextArea"
|
||||||
|
defaultValue={meta.attribution}
|
||||||
|
variant="Secondary"
|
||||||
|
radii="300"
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Box gap="300">
|
||||||
|
<Button type="submit" variant="Success" size="300" radii="300" disabled={uploadingAvatar}>
|
||||||
|
<Text size="B300">Save</Text>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="reset"
|
||||||
|
onClick={onCancel}
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
>
|
||||||
|
<Text size="B300">Cancel</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
55
src/app/components/image-pack-view/RoomImagePack.tsx
Normal file
55
src/app/components/image-pack-view/RoomImagePack.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import React, { useCallback, useMemo } from 'react';
|
||||||
|
import { Room } from 'matrix-js-sdk';
|
||||||
|
import { usePowerLevels, usePowerLevelsAPI } from '../../hooks/usePowerLevels';
|
||||||
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
|
import { ImagePackContent } from './ImagePackContent';
|
||||||
|
import { ImagePack, PackContent } from '../../plugins/custom-emoji';
|
||||||
|
import { StateEvent } from '../../../types/matrix/room';
|
||||||
|
import { useRoomImagePack } from '../../hooks/useImagePacks';
|
||||||
|
import { randomStr } from '../../utils/common';
|
||||||
|
|
||||||
|
type RoomImagePackProps = {
|
||||||
|
room: Room;
|
||||||
|
stateKey: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function RoomImagePack({ room, stateKey }: RoomImagePackProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const userId = mx.getUserId()!;
|
||||||
|
const powerLevels = usePowerLevels(room);
|
||||||
|
|
||||||
|
const { getPowerLevel, canSendStateEvent } = usePowerLevelsAPI(powerLevels);
|
||||||
|
const canEditImagePack = canSendStateEvent(StateEvent.PoniesRoomEmotes, getPowerLevel(userId));
|
||||||
|
|
||||||
|
const fallbackPack = useMemo(() => {
|
||||||
|
const fakePackId = randomStr(4);
|
||||||
|
return new ImagePack(
|
||||||
|
fakePackId,
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
roomId: room.roomId,
|
||||||
|
stateKey,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}, [room.roomId, stateKey]);
|
||||||
|
const imagePack = useRoomImagePack(room, stateKey) ?? fallbackPack;
|
||||||
|
|
||||||
|
const handleUpdate = useCallback(
|
||||||
|
async (packContent: PackContent) => {
|
||||||
|
const { address } = imagePack;
|
||||||
|
if (!address) return;
|
||||||
|
|
||||||
|
await mx.sendStateEvent(
|
||||||
|
address.roomId,
|
||||||
|
StateEvent.PoniesRoomEmotes,
|
||||||
|
packContent,
|
||||||
|
address.stateKey
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[mx, imagePack]
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ImagePackContent imagePack={imagePack} canEdit={canEditImagePack} onUpdate={handleUpdate} />
|
||||||
|
);
|
||||||
|
}
|
||||||
116
src/app/components/image-pack-view/UsageSwitcher.tsx
Normal file
116
src/app/components/image-pack-view/UsageSwitcher.tsx
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
import React, { MouseEventHandler, useMemo, useState } from 'react';
|
||||||
|
import { Box, Button, config, Icon, Icons, Menu, MenuItem, PopOut, RectCords, Text } from 'folds';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import { ImageUsage } from '../../plugins/custom-emoji';
|
||||||
|
import { stopPropagation } from '../../utils/keyboard';
|
||||||
|
|
||||||
|
export const useUsageStr = (): ((usage: ImageUsage[]) => string) => {
|
||||||
|
const getUsageStr = (usage: ImageUsage[]): string => {
|
||||||
|
const sticker = usage.includes(ImageUsage.Sticker);
|
||||||
|
const emoticon = usage.includes(ImageUsage.Emoticon);
|
||||||
|
|
||||||
|
if (sticker && emoticon) return 'Both';
|
||||||
|
if (sticker) return 'Sticker';
|
||||||
|
if (emoticon) return 'Emoji';
|
||||||
|
return 'Both';
|
||||||
|
};
|
||||||
|
return getUsageStr;
|
||||||
|
};
|
||||||
|
|
||||||
|
type UsageSelectorProps = {
|
||||||
|
selected: ImageUsage[];
|
||||||
|
onChange: (usage: ImageUsage[]) => void;
|
||||||
|
};
|
||||||
|
export function UsageSelector({ selected, onChange }: UsageSelectorProps) {
|
||||||
|
const getUsageStr = useUsageStr();
|
||||||
|
|
||||||
|
const selectedUsageStr = getUsageStr(selected);
|
||||||
|
const isSelected = (usage: ImageUsage[]) => getUsageStr(usage) === selectedUsageStr;
|
||||||
|
|
||||||
|
const allUsages: ImageUsage[][] = useMemo(
|
||||||
|
() => [[ImageUsage.Emoticon], [ImageUsage.Sticker], [ImageUsage.Sticker, ImageUsage.Emoticon]],
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
|
||||||
|
{allUsages.map((usage) => (
|
||||||
|
<MenuItem
|
||||||
|
key={getUsageStr(usage)}
|
||||||
|
size="300"
|
||||||
|
variant={isSelected(usage) ? 'SurfaceVariant' : 'Surface'}
|
||||||
|
aria-selected={isSelected(usage)}
|
||||||
|
radii="300"
|
||||||
|
onClick={() => onChange(usage)}
|
||||||
|
>
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Text size="T300">{getUsageStr(usage)}</Text>
|
||||||
|
</Box>
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type UsageSwitcherProps = {
|
||||||
|
usage: ImageUsage[];
|
||||||
|
canEdit?: boolean;
|
||||||
|
onChange: (usage: ImageUsage[]) => void;
|
||||||
|
};
|
||||||
|
export function UsageSwitcher({ usage, onChange, canEdit }: UsageSwitcherProps) {
|
||||||
|
const getUsageStr = useUsageStr();
|
||||||
|
|
||||||
|
const [menuCords, setMenuCords] = useState<RectCords>();
|
||||||
|
|
||||||
|
const handleSelectUsage: MouseEventHandler<HTMLButtonElement> = (event) => {
|
||||||
|
setMenuCords(event.currentTarget.getBoundingClientRect());
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
type="button"
|
||||||
|
outlined
|
||||||
|
aria-disabled={!canEdit}
|
||||||
|
after={canEdit && <Icon src={Icons.ChevronBottom} size="100" />}
|
||||||
|
onClick={canEdit ? handleSelectUsage : undefined}
|
||||||
|
>
|
||||||
|
<Text size="B300">{getUsageStr(usage)}</Text>
|
||||||
|
</Button>
|
||||||
|
<PopOut
|
||||||
|
anchor={menuCords}
|
||||||
|
offset={5}
|
||||||
|
position="Bottom"
|
||||||
|
align="End"
|
||||||
|
content={
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
onDeactivate: () => setMenuCords(undefined),
|
||||||
|
clickOutsideDeactivates: true,
|
||||||
|
isKeyForward: (evt: KeyboardEvent) =>
|
||||||
|
evt.key === 'ArrowDown' || evt.key === 'ArrowRight',
|
||||||
|
isKeyBackward: (evt: KeyboardEvent) =>
|
||||||
|
evt.key === 'ArrowUp' || evt.key === 'ArrowLeft',
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Menu>
|
||||||
|
<UsageSelector
|
||||||
|
selected={usage}
|
||||||
|
onChange={(usg) => {
|
||||||
|
setMenuCords(undefined);
|
||||||
|
onChange(usg);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Menu>
|
||||||
|
</FocusTrap>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
22
src/app/components/image-pack-view/UserImagePack.tsx
Normal file
22
src/app/components/image-pack-view/UserImagePack.tsx
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import React, { useCallback, useMemo } from 'react';
|
||||||
|
import { ImagePackContent } from './ImagePackContent';
|
||||||
|
import { ImagePack, PackContent } from '../../plugins/custom-emoji';
|
||||||
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
|
import { AccountDataEvent } from '../../../types/matrix/accountData';
|
||||||
|
import { useUserImagePack } from '../../hooks/useImagePacks';
|
||||||
|
|
||||||
|
export function UserImagePack() {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const defaultPack = useMemo(() => new ImagePack(mx.getUserId() ?? '', {}, undefined), [mx]);
|
||||||
|
const imagePack = useUserImagePack();
|
||||||
|
|
||||||
|
const handleUpdate = useCallback(
|
||||||
|
async (packContent: PackContent) => {
|
||||||
|
await mx.setAccountData(AccountDataEvent.PoniesUserEmotes, packContent);
|
||||||
|
},
|
||||||
|
[mx]
|
||||||
|
);
|
||||||
|
|
||||||
|
return <ImagePackContent imagePack={imagePack ?? defaultPack} canEdit onUpdate={handleUpdate} />;
|
||||||
|
}
|
||||||
1
src/app/components/image-pack-view/index.ts
Normal file
1
src/app/components/image-pack-view/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './ImagePackView';
|
||||||
37
src/app/components/image-pack-view/style.css.ts
Normal file
37
src/app/components/image-pack-view/style.css.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { style } from '@vanilla-extract/css';
|
||||||
|
import { color, config, DefaultReset, toRem } from 'folds';
|
||||||
|
|
||||||
|
export const ImagePackImage = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
width: toRem(36),
|
||||||
|
height: toRem(36),
|
||||||
|
objectFit: 'contain',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DeleteImageShortcode = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
color: color.Critical.Main,
|
||||||
|
textDecoration: 'line-through',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const ImagePackImageInputs = style([
|
||||||
|
DefaultReset,
|
||||||
|
{
|
||||||
|
overflow: 'hidden',
|
||||||
|
borderRadius: config.radii.R300,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const UnsavedMenu = style({
|
||||||
|
position: 'sticky',
|
||||||
|
padding: config.space.S200,
|
||||||
|
paddingLeft: config.space.S400,
|
||||||
|
top: config.space.S400,
|
||||||
|
left: config.space.S400,
|
||||||
|
right: 0,
|
||||||
|
zIndex: 1,
|
||||||
|
});
|
||||||
@@ -32,8 +32,10 @@ export const ImageViewerImg = style([
|
|||||||
DefaultReset,
|
DefaultReset,
|
||||||
{
|
{
|
||||||
objectFit: 'contain',
|
objectFit: 'contain',
|
||||||
width: '100%',
|
width: 'auto',
|
||||||
height: '100%',
|
height: 'auto',
|
||||||
|
maxWidth: '100%',
|
||||||
|
maxHeight: '100%',
|
||||||
backgroundColor: color.Surface.Container,
|
backgroundColor: color.Surface.Container,
|
||||||
transition: 'transform 100ms linear',
|
transition: 'transform 100ms linear',
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { Box, Chip, Header, Icon, IconButton, Icons, Text, as } from 'folds';
|
|||||||
import * as css from './ImageViewer.css';
|
import * as css from './ImageViewer.css';
|
||||||
import { useZoom } from '../../hooks/useZoom';
|
import { useZoom } from '../../hooks/useZoom';
|
||||||
import { usePan } from '../../hooks/usePan';
|
import { usePan } from '../../hooks/usePan';
|
||||||
|
import { downloadMedia } from '../../utils/matrix';
|
||||||
|
|
||||||
export type ImageViewerProps = {
|
export type ImageViewerProps = {
|
||||||
alt: string;
|
alt: string;
|
||||||
@@ -18,8 +19,9 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
|||||||
const { zoom, zoomIn, zoomOut, setZoom } = useZoom(0.2);
|
const { zoom, zoomIn, zoomOut, setZoom } = useZoom(0.2);
|
||||||
const { pan, cursor, onMouseDown } = usePan(zoom !== 1);
|
const { pan, cursor, onMouseDown } = usePan(zoom !== 1);
|
||||||
|
|
||||||
const handleDownload = () => {
|
const handleDownload = async () => {
|
||||||
FileSaver.saveAs(src, alt);
|
const fileContent = await downloadMedia(src);
|
||||||
|
FileSaver.saveAs(fileContent, alt);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
53
src/app/components/info-card/InfoCard.tsx
Normal file
53
src/app/components/info-card/InfoCard.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import { Box, ContainerColor, Text } from 'folds';
|
||||||
|
import React, { ReactNode } from 'react';
|
||||||
|
import classNames from 'classnames';
|
||||||
|
import { BreakWord } from '../../styles/Text.css';
|
||||||
|
import { ContainerColor as ContainerClr } from '../../styles/ContainerColor.css';
|
||||||
|
import * as css from './styles.css';
|
||||||
|
|
||||||
|
type InfoCardProps = {
|
||||||
|
variant?: ContainerColor;
|
||||||
|
title?: ReactNode;
|
||||||
|
description?: ReactNode;
|
||||||
|
before?: ReactNode;
|
||||||
|
after?: ReactNode;
|
||||||
|
children?: ReactNode;
|
||||||
|
};
|
||||||
|
export function InfoCard({
|
||||||
|
variant = 'Primary',
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
before,
|
||||||
|
after,
|
||||||
|
children,
|
||||||
|
}: InfoCardProps) {
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
direction="Column"
|
||||||
|
className={classNames(css.InfoCard, ContainerClr({ variant }))}
|
||||||
|
gap="300"
|
||||||
|
>
|
||||||
|
<Box gap="200" alignItems="Center">
|
||||||
|
{before && (
|
||||||
|
<Box shrink="No" alignSelf="Start">
|
||||||
|
{before}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
<Box grow="Yes" direction="Column" gap="100">
|
||||||
|
{title && (
|
||||||
|
<Text size="L400" className={BreakWord}>
|
||||||
|
{title}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{description && (
|
||||||
|
<Text size="T200" className={BreakWord}>
|
||||||
|
{description}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
{after && <Box shrink="No">{after}</Box>}
|
||||||
|
</Box>
|
||||||
|
{children}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
1
src/app/components/info-card/index.ts
Normal file
1
src/app/components/info-card/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './InfoCard';
|
||||||
10
src/app/components/info-card/styles.css.ts
Normal file
10
src/app/components/info-card/styles.css.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { style } from '@vanilla-extract/css';
|
||||||
|
import { config } from 'folds';
|
||||||
|
|
||||||
|
export const InfoCard = style([
|
||||||
|
{
|
||||||
|
padding: config.space.S200,
|
||||||
|
borderRadius: config.radii.R300,
|
||||||
|
borderWidth: config.borderWidth.B300,
|
||||||
|
},
|
||||||
|
]);
|
||||||
108
src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx
Normal file
108
src/app/components/leave-room-prompt/LeaveRoomPrompt.tsx
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
import React, { useCallback, useEffect } from 'react';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
Overlay,
|
||||||
|
OverlayCenter,
|
||||||
|
OverlayBackdrop,
|
||||||
|
Header,
|
||||||
|
config,
|
||||||
|
Box,
|
||||||
|
Text,
|
||||||
|
IconButton,
|
||||||
|
Icon,
|
||||||
|
Icons,
|
||||||
|
color,
|
||||||
|
Button,
|
||||||
|
Spinner,
|
||||||
|
} from 'folds';
|
||||||
|
import { MatrixError } from 'matrix-js-sdk';
|
||||||
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
||||||
|
import { stopPropagation } from '../../utils/keyboard';
|
||||||
|
|
||||||
|
type LeaveRoomPromptProps = {
|
||||||
|
roomId: string;
|
||||||
|
onDone: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
};
|
||||||
|
export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const [leaveState, leaveRoom] = useAsyncCallback<undefined, MatrixError, []>(
|
||||||
|
useCallback(async () => {
|
||||||
|
mx.leave(roomId);
|
||||||
|
}, [mx, roomId])
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleLeave = () => {
|
||||||
|
leaveRoom();
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (leaveState.status === AsyncStatus.Success) {
|
||||||
|
onDone();
|
||||||
|
}
|
||||||
|
}, [leaveState, onDone]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Overlay open backdrop={<OverlayBackdrop />}>
|
||||||
|
<OverlayCenter>
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
onDeactivate: onCancel,
|
||||||
|
clickOutsideDeactivates: true,
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Dialog variant="Surface">
|
||||||
|
<Header
|
||||||
|
style={{
|
||||||
|
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
|
||||||
|
borderBottomWidth: config.borderWidth.B300,
|
||||||
|
}}
|
||||||
|
variant="Surface"
|
||||||
|
size="500"
|
||||||
|
>
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Text size="H4">Leave Room</Text>
|
||||||
|
</Box>
|
||||||
|
<IconButton size="300" onClick={onCancel} radii="300">
|
||||||
|
<Icon src={Icons.Cross} />
|
||||||
|
</IconButton>
|
||||||
|
</Header>
|
||||||
|
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
|
||||||
|
<Box direction="Column" gap="200">
|
||||||
|
<Text priority="400">Are you sure you want to leave this room?</Text>
|
||||||
|
{leaveState.status === AsyncStatus.Error && (
|
||||||
|
<Text style={{ color: color.Critical.Main }} size="T300">
|
||||||
|
Failed to leave room! {leaveState.error.message}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="Critical"
|
||||||
|
onClick={handleLeave}
|
||||||
|
before={
|
||||||
|
leaveState.status === AsyncStatus.Loading ? (
|
||||||
|
<Spinner fill="Solid" variant="Critical" size="200" />
|
||||||
|
) : undefined
|
||||||
|
}
|
||||||
|
aria-disabled={
|
||||||
|
leaveState.status === AsyncStatus.Loading ||
|
||||||
|
leaveState.status === AsyncStatus.Success
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Text size="B400">
|
||||||
|
{leaveState.status === AsyncStatus.Loading ? 'Leaving...' : 'Leave'}
|
||||||
|
</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Dialog>
|
||||||
|
</FocusTrap>
|
||||||
|
</OverlayCenter>
|
||||||
|
</Overlay>
|
||||||
|
);
|
||||||
|
}
|
||||||
1
src/app/components/leave-room-prompt/index.ts
Normal file
1
src/app/components/leave-room-prompt/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './LeaveRoomPrompt';
|
||||||
108
src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx
Normal file
108
src/app/components/leave-space-prompt/LeaveSpacePrompt.tsx
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
import React, { useCallback, useEffect } from 'react';
|
||||||
|
import FocusTrap from 'focus-trap-react';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
Overlay,
|
||||||
|
OverlayCenter,
|
||||||
|
OverlayBackdrop,
|
||||||
|
Header,
|
||||||
|
config,
|
||||||
|
Box,
|
||||||
|
Text,
|
||||||
|
IconButton,
|
||||||
|
Icon,
|
||||||
|
Icons,
|
||||||
|
color,
|
||||||
|
Button,
|
||||||
|
Spinner,
|
||||||
|
} from 'folds';
|
||||||
|
import { MatrixError } from 'matrix-js-sdk';
|
||||||
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
|
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
||||||
|
import { stopPropagation } from '../../utils/keyboard';
|
||||||
|
|
||||||
|
type LeaveSpacePromptProps = {
|
||||||
|
roomId: string;
|
||||||
|
onDone: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
};
|
||||||
|
export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptProps) {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
|
||||||
|
const [leaveState, leaveRoom] = useAsyncCallback<undefined, MatrixError, []>(
|
||||||
|
useCallback(async () => {
|
||||||
|
mx.leave(roomId);
|
||||||
|
}, [mx, roomId])
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleLeave = () => {
|
||||||
|
leaveRoom();
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (leaveState.status === AsyncStatus.Success) {
|
||||||
|
onDone();
|
||||||
|
}
|
||||||
|
}, [leaveState, onDone]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Overlay open backdrop={<OverlayBackdrop />}>
|
||||||
|
<OverlayCenter>
|
||||||
|
<FocusTrap
|
||||||
|
focusTrapOptions={{
|
||||||
|
initialFocus: false,
|
||||||
|
onDeactivate: onCancel,
|
||||||
|
clickOutsideDeactivates: true,
|
||||||
|
escapeDeactivates: stopPropagation,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Dialog variant="Surface">
|
||||||
|
<Header
|
||||||
|
style={{
|
||||||
|
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
|
||||||
|
borderBottomWidth: config.borderWidth.B300,
|
||||||
|
}}
|
||||||
|
variant="Surface"
|
||||||
|
size="500"
|
||||||
|
>
|
||||||
|
<Box grow="Yes">
|
||||||
|
<Text size="H4">Leave Space</Text>
|
||||||
|
</Box>
|
||||||
|
<IconButton size="300" onClick={onCancel} radii="300">
|
||||||
|
<Icon src={Icons.Cross} />
|
||||||
|
</IconButton>
|
||||||
|
</Header>
|
||||||
|
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
|
||||||
|
<Box direction="Column" gap="200">
|
||||||
|
<Text priority="400">Are you sure you want to leave this space?</Text>
|
||||||
|
{leaveState.status === AsyncStatus.Error && (
|
||||||
|
<Text style={{ color: color.Critical.Main }} size="T300">
|
||||||
|
Failed to leave space! {leaveState.error.message}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="Critical"
|
||||||
|
onClick={handleLeave}
|
||||||
|
before={
|
||||||
|
leaveState.status === AsyncStatus.Loading ? (
|
||||||
|
<Spinner fill="Solid" variant="Critical" size="200" />
|
||||||
|
) : undefined
|
||||||
|
}
|
||||||
|
aria-disabled={
|
||||||
|
leaveState.status === AsyncStatus.Loading ||
|
||||||
|
leaveState.status === AsyncStatus.Success
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Text size="B400">
|
||||||
|
{leaveState.status === AsyncStatus.Loading ? 'Leaving...' : 'Leave'}
|
||||||
|
</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Dialog>
|
||||||
|
</FocusTrap>
|
||||||
|
</OverlayCenter>
|
||||||
|
</Overlay>
|
||||||
|
);
|
||||||
|
}
|
||||||
1
src/app/components/leave-space-prompt/index.ts
Normal file
1
src/app/components/leave-space-prompt/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './LeaveSpacePrompt';
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Badge, Box, Text, as, toRem } from 'folds';
|
import { Badge, Box, Text, as, toRem } from 'folds';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { mimeTypeToExt } from '../../../utils/mimeTypes';
|
import { mimeTypeToExt } from '../../utils/mimeTypes';
|
||||||
|
|
||||||
const badgeStyles = { maxWidth: toRem(100) };
|
const badgeStyles = { maxWidth: toRem(100) };
|
||||||
|
|
||||||
399
src/app/components/message/MsgTypeRenderers.tsx
Normal file
399
src/app/components/message/MsgTypeRenderers.tsx
Normal file
@@ -0,0 +1,399 @@
|
|||||||
|
import React, { ReactNode } from 'react';
|
||||||
|
import { Box, Chip, Icon, Icons, Text, toRem } from 'folds';
|
||||||
|
import { IContent } from 'matrix-js-sdk';
|
||||||
|
import { JUMBO_EMOJI_REG, URL_REG } from '../../utils/regex';
|
||||||
|
import { trimReplyFromBody } from '../../utils/room';
|
||||||
|
import { MessageTextBody } from './layout';
|
||||||
|
import {
|
||||||
|
MessageBadEncryptedContent,
|
||||||
|
MessageBrokenContent,
|
||||||
|
MessageDeletedContent,
|
||||||
|
MessageEditedContent,
|
||||||
|
MessageUnsupportedContent,
|
||||||
|
} from './content';
|
||||||
|
import {
|
||||||
|
IAudioContent,
|
||||||
|
IAudioInfo,
|
||||||
|
IEncryptedFile,
|
||||||
|
IFileContent,
|
||||||
|
IFileInfo,
|
||||||
|
IImageContent,
|
||||||
|
IImageInfo,
|
||||||
|
IThumbnailContent,
|
||||||
|
IVideoContent,
|
||||||
|
IVideoInfo,
|
||||||
|
} from '../../../types/matrix/common';
|
||||||
|
import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '../../utils/mimeTypes';
|
||||||
|
import { parseGeoUri, scaleYDimension } from '../../utils/common';
|
||||||
|
import { Attachment, AttachmentBox, AttachmentContent, AttachmentHeader } from './attachment';
|
||||||
|
import { FileHeader } from './FileHeader';
|
||||||
|
|
||||||
|
export function MBadEncrypted() {
|
||||||
|
return (
|
||||||
|
<Text>
|
||||||
|
<MessageBadEncryptedContent />
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type RedactedContentProps = {
|
||||||
|
reason?: string;
|
||||||
|
};
|
||||||
|
export function RedactedContent({ reason }: RedactedContentProps) {
|
||||||
|
return (
|
||||||
|
<Text>
|
||||||
|
<MessageDeletedContent reason={reason} />
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UnsupportedContent() {
|
||||||
|
return (
|
||||||
|
<Text>
|
||||||
|
<MessageUnsupportedContent />
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BrokenContent() {
|
||||||
|
return (
|
||||||
|
<Text>
|
||||||
|
<MessageBrokenContent />
|
||||||
|
</Text>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type RenderBodyProps = {
|
||||||
|
body: string;
|
||||||
|
customBody?: string;
|
||||||
|
};
|
||||||
|
type MTextProps = {
|
||||||
|
edited?: boolean;
|
||||||
|
content: Record<string, unknown>;
|
||||||
|
renderBody: (props: RenderBodyProps) => ReactNode;
|
||||||
|
renderUrlsPreview?: (urls: string[]) => ReactNode;
|
||||||
|
};
|
||||||
|
export function MText({ edited, content, renderBody, renderUrlsPreview }: MTextProps) {
|
||||||
|
const { body, formatted_body: customBody } = content;
|
||||||
|
|
||||||
|
if (typeof body !== 'string') return <BrokenContent />;
|
||||||
|
const trimmedBody = trimReplyFromBody(body);
|
||||||
|
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
|
||||||
|
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<MessageTextBody
|
||||||
|
preWrap={typeof customBody !== 'string'}
|
||||||
|
jumboEmoji={JUMBO_EMOJI_REG.test(trimmedBody)}
|
||||||
|
>
|
||||||
|
{renderBody({
|
||||||
|
body: trimmedBody,
|
||||||
|
customBody: typeof customBody === 'string' ? customBody : undefined,
|
||||||
|
})}
|
||||||
|
{edited && <MessageEditedContent />}
|
||||||
|
</MessageTextBody>
|
||||||
|
{renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type MEmoteProps = {
|
||||||
|
displayName: string;
|
||||||
|
edited?: boolean;
|
||||||
|
content: Record<string, unknown>;
|
||||||
|
renderBody: (props: RenderBodyProps) => ReactNode;
|
||||||
|
renderUrlsPreview?: (urls: string[]) => ReactNode;
|
||||||
|
};
|
||||||
|
export function MEmote({
|
||||||
|
displayName,
|
||||||
|
edited,
|
||||||
|
content,
|
||||||
|
renderBody,
|
||||||
|
renderUrlsPreview,
|
||||||
|
}: MEmoteProps) {
|
||||||
|
const { body, formatted_body: customBody } = content;
|
||||||
|
|
||||||
|
if (typeof body !== 'string') return <BrokenContent />;
|
||||||
|
const trimmedBody = trimReplyFromBody(body);
|
||||||
|
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
|
||||||
|
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<MessageTextBody
|
||||||
|
emote
|
||||||
|
preWrap={typeof customBody !== 'string'}
|
||||||
|
jumboEmoji={JUMBO_EMOJI_REG.test(trimmedBody)}
|
||||||
|
>
|
||||||
|
<b>{`${displayName} `}</b>
|
||||||
|
{renderBody({
|
||||||
|
body: trimmedBody,
|
||||||
|
customBody: typeof customBody === 'string' ? customBody : undefined,
|
||||||
|
})}
|
||||||
|
{edited && <MessageEditedContent />}
|
||||||
|
</MessageTextBody>
|
||||||
|
{renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type MNoticeProps = {
|
||||||
|
edited?: boolean;
|
||||||
|
content: Record<string, unknown>;
|
||||||
|
renderBody: (props: RenderBodyProps) => ReactNode;
|
||||||
|
renderUrlsPreview?: (urls: string[]) => ReactNode;
|
||||||
|
};
|
||||||
|
export function MNotice({ edited, content, renderBody, renderUrlsPreview }: MNoticeProps) {
|
||||||
|
const { body, formatted_body: customBody } = content;
|
||||||
|
|
||||||
|
if (typeof body !== 'string') return <BrokenContent />;
|
||||||
|
const trimmedBody = trimReplyFromBody(body);
|
||||||
|
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
|
||||||
|
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<MessageTextBody
|
||||||
|
notice
|
||||||
|
preWrap={typeof customBody !== 'string'}
|
||||||
|
jumboEmoji={JUMBO_EMOJI_REG.test(trimmedBody)}
|
||||||
|
>
|
||||||
|
{renderBody({
|
||||||
|
body: trimmedBody,
|
||||||
|
customBody: typeof customBody === 'string' ? customBody : undefined,
|
||||||
|
})}
|
||||||
|
{edited && <MessageEditedContent />}
|
||||||
|
</MessageTextBody>
|
||||||
|
{renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type RenderImageContentProps = {
|
||||||
|
body: string;
|
||||||
|
filename?: string;
|
||||||
|
info?: IImageInfo & IThumbnailContent;
|
||||||
|
mimeType?: string;
|
||||||
|
url: string;
|
||||||
|
encInfo?: IEncryptedFile;
|
||||||
|
};
|
||||||
|
type MImageProps = {
|
||||||
|
content: IImageContent;
|
||||||
|
renderImageContent: (props: RenderImageContentProps) => ReactNode;
|
||||||
|
outlined?: boolean;
|
||||||
|
};
|
||||||
|
export function MImage({ content, renderImageContent, outlined }: MImageProps) {
|
||||||
|
const imgInfo = content?.info;
|
||||||
|
const mxcUrl = content.file?.url ?? content.url;
|
||||||
|
if (typeof mxcUrl !== 'string') {
|
||||||
|
return <BrokenContent />;
|
||||||
|
}
|
||||||
|
const height = scaleYDimension(imgInfo?.w || 400, 400, imgInfo?.h || 400);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Attachment outlined={outlined}>
|
||||||
|
<AttachmentBox
|
||||||
|
style={{
|
||||||
|
height: toRem(height < 48 ? 48 : height),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{renderImageContent({
|
||||||
|
body: content.body || 'Image',
|
||||||
|
info: imgInfo,
|
||||||
|
mimeType: imgInfo?.mimetype,
|
||||||
|
url: mxcUrl,
|
||||||
|
encInfo: content.file,
|
||||||
|
})}
|
||||||
|
</AttachmentBox>
|
||||||
|
</Attachment>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type RenderVideoContentProps = {
|
||||||
|
body: string;
|
||||||
|
info: IVideoInfo & IThumbnailContent;
|
||||||
|
mimeType: string;
|
||||||
|
url: string;
|
||||||
|
encInfo?: IEncryptedFile;
|
||||||
|
};
|
||||||
|
type MVideoProps = {
|
||||||
|
content: IVideoContent;
|
||||||
|
renderAsFile: () => ReactNode;
|
||||||
|
renderVideoContent: (props: RenderVideoContentProps) => ReactNode;
|
||||||
|
outlined?: boolean;
|
||||||
|
};
|
||||||
|
export function MVideo({ content, renderAsFile, renderVideoContent, outlined }: MVideoProps) {
|
||||||
|
const videoInfo = content?.info;
|
||||||
|
const mxcUrl = content.file?.url ?? content.url;
|
||||||
|
const safeMimeType = getBlobSafeMimeType(videoInfo?.mimetype ?? '');
|
||||||
|
|
||||||
|
if (!videoInfo || !safeMimeType.startsWith('video') || typeof mxcUrl !== 'string') {
|
||||||
|
if (mxcUrl) {
|
||||||
|
return renderAsFile();
|
||||||
|
}
|
||||||
|
return <BrokenContent />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const height = scaleYDimension(videoInfo.w || 400, 400, videoInfo.h || 400);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Attachment outlined={outlined}>
|
||||||
|
<AttachmentBox
|
||||||
|
style={{
|
||||||
|
height: toRem(height < 48 ? 48 : height),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{renderVideoContent({
|
||||||
|
body: content.body || 'Video',
|
||||||
|
info: videoInfo,
|
||||||
|
mimeType: safeMimeType,
|
||||||
|
url: mxcUrl,
|
||||||
|
encInfo: content.file,
|
||||||
|
})}
|
||||||
|
</AttachmentBox>
|
||||||
|
</Attachment>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type RenderAudioContentProps = {
|
||||||
|
info: IAudioInfo;
|
||||||
|
mimeType: string;
|
||||||
|
url: string;
|
||||||
|
encInfo?: IEncryptedFile;
|
||||||
|
};
|
||||||
|
type MAudioProps = {
|
||||||
|
content: IAudioContent;
|
||||||
|
renderAsFile: () => ReactNode;
|
||||||
|
renderAudioContent: (props: RenderAudioContentProps) => ReactNode;
|
||||||
|
outlined?: boolean;
|
||||||
|
};
|
||||||
|
export function MAudio({ content, renderAsFile, renderAudioContent, outlined }: MAudioProps) {
|
||||||
|
const audioInfo = content?.info;
|
||||||
|
const mxcUrl = content.file?.url ?? content.url;
|
||||||
|
const safeMimeType = getBlobSafeMimeType(audioInfo?.mimetype ?? '');
|
||||||
|
|
||||||
|
if (!audioInfo || !safeMimeType.startsWith('audio') || typeof mxcUrl !== 'string') {
|
||||||
|
if (mxcUrl) {
|
||||||
|
return renderAsFile();
|
||||||
|
}
|
||||||
|
return <BrokenContent />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Attachment outlined={outlined}>
|
||||||
|
<AttachmentHeader>
|
||||||
|
<FileHeader body={content.filename ?? content.body ?? 'Audio'} mimeType={safeMimeType} />
|
||||||
|
</AttachmentHeader>
|
||||||
|
<AttachmentBox>
|
||||||
|
<AttachmentContent>
|
||||||
|
{renderAudioContent({
|
||||||
|
info: audioInfo,
|
||||||
|
mimeType: safeMimeType,
|
||||||
|
url: mxcUrl,
|
||||||
|
encInfo: content.file,
|
||||||
|
})}
|
||||||
|
</AttachmentContent>
|
||||||
|
</AttachmentBox>
|
||||||
|
</Attachment>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type RenderFileContentProps = {
|
||||||
|
body: string;
|
||||||
|
info: IFileInfo & IThumbnailContent;
|
||||||
|
mimeType: string;
|
||||||
|
url: string;
|
||||||
|
encInfo?: IEncryptedFile;
|
||||||
|
};
|
||||||
|
type MFileProps = {
|
||||||
|
content: IFileContent;
|
||||||
|
renderFileContent: (props: RenderFileContentProps) => ReactNode;
|
||||||
|
outlined?: boolean;
|
||||||
|
};
|
||||||
|
export function MFile({ content, renderFileContent, outlined }: MFileProps) {
|
||||||
|
const fileInfo = content?.info;
|
||||||
|
const mxcUrl = content.file?.url ?? content.url;
|
||||||
|
|
||||||
|
if (typeof mxcUrl !== 'string') {
|
||||||
|
return <BrokenContent />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Attachment outlined={outlined}>
|
||||||
|
<AttachmentHeader>
|
||||||
|
<FileHeader
|
||||||
|
body={content.filename ?? content.body ?? 'Unnamed File'}
|
||||||
|
mimeType={fileInfo?.mimetype ?? FALLBACK_MIMETYPE}
|
||||||
|
/>
|
||||||
|
</AttachmentHeader>
|
||||||
|
<AttachmentBox>
|
||||||
|
<AttachmentContent>
|
||||||
|
{renderFileContent({
|
||||||
|
body: content.filename ?? content.body ?? 'File',
|
||||||
|
info: fileInfo ?? {},
|
||||||
|
mimeType: fileInfo?.mimetype ?? FALLBACK_MIMETYPE,
|
||||||
|
url: mxcUrl,
|
||||||
|
encInfo: content.file,
|
||||||
|
})}
|
||||||
|
</AttachmentContent>
|
||||||
|
</AttachmentBox>
|
||||||
|
</Attachment>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type MLocationProps = {
|
||||||
|
content: IContent;
|
||||||
|
};
|
||||||
|
export function MLocation({ content }: MLocationProps) {
|
||||||
|
const geoUri = content.geo_uri;
|
||||||
|
if (typeof geoUri !== 'string') return <BrokenContent />;
|
||||||
|
const location = parseGeoUri(geoUri);
|
||||||
|
return (
|
||||||
|
<Box direction="Column" alignItems="Start" gap="100">
|
||||||
|
<Text size="T400">{geoUri}</Text>
|
||||||
|
<Chip
|
||||||
|
as="a"
|
||||||
|
size="400"
|
||||||
|
href={`https://www.openstreetmap.org/?mlat=${location.latitude}&mlon=${location.longitude}#map=16/${location.latitude}/${location.longitude}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer noopener"
|
||||||
|
variant="Primary"
|
||||||
|
radii="Pill"
|
||||||
|
before={<Icon src={Icons.External} size="50" />}
|
||||||
|
>
|
||||||
|
<Text size="B300">Open Location</Text>
|
||||||
|
</Chip>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type MStickerProps = {
|
||||||
|
content: IImageContent;
|
||||||
|
renderImageContent: (props: RenderImageContentProps) => ReactNode;
|
||||||
|
};
|
||||||
|
export function MSticker({ content, renderImageContent }: MStickerProps) {
|
||||||
|
const imgInfo = content?.info;
|
||||||
|
const mxcUrl = content.file?.url ?? content.url;
|
||||||
|
if (typeof mxcUrl !== 'string') {
|
||||||
|
return <MessageBrokenContent />;
|
||||||
|
}
|
||||||
|
const height = scaleYDimension(imgInfo?.w || 152, 152, imgInfo?.h || 152);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AttachmentBox
|
||||||
|
style={{
|
||||||
|
height: toRem(height < 48 ? 48 : height),
|
||||||
|
width: toRem(152),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{renderImageContent({
|
||||||
|
body: content.body || 'Sticker',
|
||||||
|
info: imgInfo,
|
||||||
|
mimeType: imgInfo?.mimetype,
|
||||||
|
url: mxcUrl,
|
||||||
|
encInfo: content.file,
|
||||||
|
})}
|
||||||
|
</AttachmentBox>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ import { MatrixClient, MatrixEvent, Room } from 'matrix-js-sdk';
|
|||||||
import * as css from './Reaction.css';
|
import * as css from './Reaction.css';
|
||||||
import { getHexcodeForEmoji, getShortcodeFor } from '../../plugins/emoji';
|
import { getHexcodeForEmoji, getShortcodeFor } from '../../plugins/emoji';
|
||||||
import { getMemberDisplayName } from '../../utils/room';
|
import { getMemberDisplayName } from '../../utils/room';
|
||||||
import { eventWithShortcode, getMxIdLocalPart } from '../../utils/matrix';
|
import { eventWithShortcode, getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix';
|
||||||
|
|
||||||
export const Reaction = as<
|
export const Reaction = as<
|
||||||
'button',
|
'button',
|
||||||
@@ -13,8 +13,9 @@ export const Reaction = as<
|
|||||||
mx: MatrixClient;
|
mx: MatrixClient;
|
||||||
count: number;
|
count: number;
|
||||||
reaction: string;
|
reaction: string;
|
||||||
|
useAuthentication?: boolean;
|
||||||
}
|
}
|
||||||
>(({ className, mx, count, reaction, ...props }, ref) => (
|
>(({ className, mx, count, reaction, useAuthentication, ...props }, ref) => (
|
||||||
<Box
|
<Box
|
||||||
as="button"
|
as="button"
|
||||||
className={classNames(css.Reaction, className)}
|
className={classNames(css.Reaction, className)}
|
||||||
@@ -28,7 +29,8 @@ export const Reaction = as<
|
|||||||
{reaction.startsWith('mxc://') ? (
|
{reaction.startsWith('mxc://') ? (
|
||||||
<img
|
<img
|
||||||
className={css.ReactionImg}
|
className={css.ReactionImg}
|
||||||
src={mx.mxcUrlToHttp(reaction) ?? reaction}
|
src={mxcUrlToHttp(mx, reaction, useAuthentication) ?? reaction
|
||||||
|
}
|
||||||
alt={reaction}
|
alt={reaction}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
36
src/app/components/message/RenderBody.tsx
Normal file
36
src/app/components/message/RenderBody.tsx
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import parse, { HTMLReactParserOptions } from 'html-react-parser';
|
||||||
|
import Linkify from 'linkify-react';
|
||||||
|
import { Opts } from 'linkifyjs';
|
||||||
|
import { MessageEmptyContent } from './content';
|
||||||
|
import { sanitizeCustomHtml } from '../../utils/sanitize';
|
||||||
|
import { highlightText, scaleSystemEmoji } from '../../plugins/react-custom-html-parser';
|
||||||
|
|
||||||
|
type RenderBodyProps = {
|
||||||
|
body: string;
|
||||||
|
customBody?: string;
|
||||||
|
|
||||||
|
highlightRegex?: RegExp;
|
||||||
|
htmlReactParserOptions: HTMLReactParserOptions;
|
||||||
|
linkifyOpts: Opts;
|
||||||
|
};
|
||||||
|
export function RenderBody({
|
||||||
|
body,
|
||||||
|
customBody,
|
||||||
|
highlightRegex,
|
||||||
|
htmlReactParserOptions,
|
||||||
|
linkifyOpts,
|
||||||
|
}: RenderBodyProps) {
|
||||||
|
if (body === '') <MessageEmptyContent />;
|
||||||
|
if (customBody) {
|
||||||
|
if (customBody === '') <MessageEmptyContent />;
|
||||||
|
return parse(sanitizeCustomHtml(customBody), htmlReactParserOptions);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Linkify options={linkifyOpts}>
|
||||||
|
{highlightRegex
|
||||||
|
? highlightText(highlightRegex, scaleSystemEmoji(body))
|
||||||
|
: scaleSystemEmoji(body)}
|
||||||
|
</Linkify>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,13 +1,39 @@
|
|||||||
import { style } from '@vanilla-extract/css';
|
import { style } from '@vanilla-extract/css';
|
||||||
import { config, toRem } from 'folds';
|
import { config, toRem } from 'folds';
|
||||||
|
|
||||||
|
export const ReplyBend = style({
|
||||||
|
flexShrink: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ThreadIndicator = style({
|
||||||
|
opacity: config.opacity.P300,
|
||||||
|
gap: toRem(2),
|
||||||
|
|
||||||
|
selectors: {
|
||||||
|
'button&': {
|
||||||
|
cursor: 'pointer',
|
||||||
|
},
|
||||||
|
':hover&': {
|
||||||
|
opacity: config.opacity.P500,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ThreadIndicatorIcon = style({
|
||||||
|
width: toRem(14),
|
||||||
|
height: toRem(14),
|
||||||
|
});
|
||||||
|
|
||||||
export const Reply = style({
|
export const Reply = style({
|
||||||
padding: `0 ${config.space.S100}`,
|
|
||||||
marginBottom: toRem(1),
|
marginBottom: toRem(1),
|
||||||
cursor: 'pointer',
|
|
||||||
minWidth: 0,
|
minWidth: 0,
|
||||||
maxWidth: '100%',
|
maxWidth: '100%',
|
||||||
minHeight: config.lineHeight.T300,
|
minHeight: config.lineHeight.T300,
|
||||||
|
selectors: {
|
||||||
|
'button&': {
|
||||||
|
cursor: 'pointer',
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export const ReplyContent = style({
|
export const ReplyContent = style({
|
||||||
@@ -19,7 +45,3 @@ export const ReplyContent = style({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export const ReplyContentText = style({
|
|
||||||
paddingRight: config.space.S100,
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import { Box, Icon, Icons, Text, as, color, toRem } from 'folds';
|
import { Box, Icon, Icons, Text, as, color, toRem } from 'folds';
|
||||||
import { EventTimelineSet, MatrixClient, MatrixEvent, Room } from 'matrix-js-sdk';
|
import { EventTimelineSet, Room } from 'matrix-js-sdk';
|
||||||
import { CryptoBackend } from 'matrix-js-sdk/lib/common-crypto/CryptoBackend';
|
import React, { MouseEventHandler, ReactNode, useCallback, useMemo } from 'react';
|
||||||
import React, { useEffect, useState } from 'react';
|
|
||||||
import to from 'await-to-js';
|
|
||||||
import classNames from 'classnames';
|
import classNames from 'classnames';
|
||||||
import colorMXID from '../../../util/colorMXID';
|
import colorMXID from '../../../util/colorMXID';
|
||||||
import { getMemberDisplayName, trimReplyFromBody } from '../../utils/room';
|
import { getMemberDisplayName, trimReplyFromBody } from '../../utils/room';
|
||||||
@@ -10,24 +8,57 @@ import { getMxIdLocalPart } from '../../utils/matrix';
|
|||||||
import { LinePlaceholder } from './placeholder';
|
import { LinePlaceholder } from './placeholder';
|
||||||
import { randomNumberBetween } from '../../utils/common';
|
import { randomNumberBetween } from '../../utils/common';
|
||||||
import * as css from './Reply.css';
|
import * as css from './Reply.css';
|
||||||
import {
|
import { MessageBadEncryptedContent, MessageDeletedContent, MessageFailedContent } from './content';
|
||||||
MessageBadEncryptedContent,
|
import { scaleSystemEmoji } from '../../plugins/react-custom-html-parser';
|
||||||
MessageDeletedContent,
|
import { useRoomEvent } from '../../hooks/useRoomEvent';
|
||||||
MessageFailedContent,
|
|
||||||
} from './MessageContentFallback';
|
type ReplyLayoutProps = {
|
||||||
|
userColor?: string;
|
||||||
|
username?: ReactNode;
|
||||||
|
};
|
||||||
|
export const ReplyLayout = as<'div', ReplyLayoutProps>(
|
||||||
|
({ username, userColor, className, children, ...props }, ref) => (
|
||||||
|
<Box
|
||||||
|
className={classNames(css.Reply, className)}
|
||||||
|
alignItems="Center"
|
||||||
|
gap="100"
|
||||||
|
{...props}
|
||||||
|
ref={ref}
|
||||||
|
>
|
||||||
|
<Box style={{ color: userColor, maxWidth: toRem(200) }} alignItems="Center" shrink="No">
|
||||||
|
<Icon size="100" src={Icons.ReplyArrow} />
|
||||||
|
{username}
|
||||||
|
</Box>
|
||||||
|
<Box grow="Yes" className={css.ReplyContent}>
|
||||||
|
{children}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
export const ThreadIndicator = as<'div'>(({ ...props }, ref) => (
|
||||||
|
<Box className={css.ThreadIndicator} alignItems="Center" {...props} ref={ref}>
|
||||||
|
<Icon className={css.ThreadIndicatorIcon} src={Icons.Message} />
|
||||||
|
<Text size="T200">Threaded reply</Text>
|
||||||
|
</Box>
|
||||||
|
));
|
||||||
|
|
||||||
type ReplyProps = {
|
type ReplyProps = {
|
||||||
mx: MatrixClient;
|
|
||||||
room: Room;
|
room: Room;
|
||||||
timelineSet: EventTimelineSet;
|
timelineSet?: EventTimelineSet | undefined;
|
||||||
eventId: string;
|
replyEventId: string;
|
||||||
|
threadRootId?: string | undefined;
|
||||||
|
onClick?: MouseEventHandler | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Reply = as<'div', ReplyProps>(
|
export const Reply = as<'div', ReplyProps>(
|
||||||
({ className, mx, room, timelineSet, eventId, ...props }, ref) => {
|
({ room, timelineSet, replyEventId, threadRootId, onClick, ...props }, ref) => {
|
||||||
const [replyEvent, setReplyEvent] = useState<MatrixEvent | null | undefined>(
|
const placeholderWidth = useMemo(() => randomNumberBetween(40, 400), []);
|
||||||
timelineSet.findEventById(eventId)
|
const getFromLocalTimeline = useCallback(
|
||||||
|
() => timelineSet?.findEventById(replyEventId),
|
||||||
|
[timelineSet, replyEventId]
|
||||||
);
|
);
|
||||||
|
const replyEvent = useRoomEvent(room, replyEventId, getFromLocalTimeline);
|
||||||
|
|
||||||
const { body } = replyEvent?.getContent() ?? {};
|
const { body } = replyEvent?.getContent() ?? {};
|
||||||
const sender = replyEvent?.getSender();
|
const sender = replyEvent?.getSender();
|
||||||
@@ -38,65 +69,41 @@ export const Reply = as<'div', ReplyProps>(
|
|||||||
<MessageFailedContent />
|
<MessageFailedContent />
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let disposed = false;
|
|
||||||
const loadEvent = async () => {
|
|
||||||
const [err, evt] = await to(mx.fetchRoomEvent(room.roomId, eventId));
|
|
||||||
const mEvent = new MatrixEvent(evt);
|
|
||||||
if (disposed) return;
|
|
||||||
if (err) {
|
|
||||||
setReplyEvent(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (mEvent.isEncrypted() && mx.getCrypto()) {
|
|
||||||
await to(mEvent.attemptDecryption(mx.getCrypto() as CryptoBackend));
|
|
||||||
}
|
|
||||||
setReplyEvent(mEvent);
|
|
||||||
};
|
|
||||||
if (replyEvent === undefined) loadEvent();
|
|
||||||
return () => {
|
|
||||||
disposed = true;
|
|
||||||
};
|
|
||||||
}, [replyEvent, mx, room, eventId]);
|
|
||||||
|
|
||||||
const badEncryption = replyEvent?.getContent().msgtype === 'm.bad.encrypted';
|
const badEncryption = replyEvent?.getContent().msgtype === 'm.bad.encrypted';
|
||||||
const bodyJSX = body ? trimReplyFromBody(body) : fallbackBody;
|
const bodyJSX = body ? scaleSystemEmoji(trimReplyFromBody(body)) : fallbackBody;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box direction="Column" alignItems="Start" {...props} ref={ref}>
|
||||||
className={classNames(css.Reply, className)}
|
{threadRootId && (
|
||||||
alignItems="Center"
|
<ThreadIndicator as="button" data-event-id={threadRootId} onClick={onClick} />
|
||||||
gap="100"
|
)}
|
||||||
{...props}
|
<ReplyLayout
|
||||||
ref={ref}
|
as="button"
|
||||||
>
|
userColor={sender ? colorMXID(sender) : undefined}
|
||||||
<Box
|
username={
|
||||||
style={{ color: colorMXID(sender ?? eventId), maxWidth: '50%' }}
|
sender && (
|
||||||
alignItems="Center"
|
<Text size="T300" truncate>
|
||||||
shrink="No"
|
<b>{getMemberDisplayName(room, sender) ?? getMxIdLocalPart(sender)}</b>
|
||||||
|
</Text>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
data-event-id={replyEventId}
|
||||||
|
onClick={onClick}
|
||||||
>
|
>
|
||||||
<Icon src={Icons.ReplyArrow} size="50" />
|
|
||||||
{sender && (
|
|
||||||
<Text size="T300" truncate>
|
|
||||||
{getMemberDisplayName(room, sender) ?? getMxIdLocalPart(sender)}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
<Box grow="Yes" className={css.ReplyContent}>
|
|
||||||
{replyEvent !== undefined ? (
|
{replyEvent !== undefined ? (
|
||||||
<Text className={css.ReplyContentText} size="T300" truncate>
|
<Text size="T300" truncate>
|
||||||
{badEncryption ? <MessageBadEncryptedContent /> : bodyJSX}
|
{badEncryption ? <MessageBadEncryptedContent /> : bodyJSX}
|
||||||
</Text>
|
</Text>
|
||||||
) : (
|
) : (
|
||||||
<LinePlaceholder
|
<LinePlaceholder
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: color.SurfaceVariant.ContainerActive,
|
backgroundColor: color.SurfaceVariant.ContainerActive,
|
||||||
maxWidth: toRem(randomNumberBetween(40, 400)),
|
width: toRem(placeholderWidth),
|
||||||
width: '100%',
|
maxWidth: '100%',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</ReplyLayout>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user