50 Commits
Author SHA1 Message Date
litruv ec7b4f04c5 Resync index.css onto the base and keep the mobile and stationery additions.
Checks / checks (push) Successful in 1m59s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 09:30:12 +11:00
litruv fcfb40549a Raise ContainerColor's specificity so the theme text color beats folds' DefaultReset in any stylesheet order. 2026-11-03 09:30:11 +11:00
litruv 9b3956d85f Turn off the prism index-key rule and drop the stale directives.
Checks / checks (push) Successful in 2m0s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 02:53:34 +11:00
litruv f81461c044 Merge the mutually recursive CSS scope helpers. [skip build]
Checks / checks (push) Successful in 2m0s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 02:32:08 +11:00
litruv 96d0d27549 Remove the TikTok embeds and the raw oEmbed HTML injection. [skip build] 2026-11-03 02:25:42 +11:00
litruv 33ae13e514 Drop the key conflict handler and the crypto store prefix. [skip build]
Checks / checks (push) Successful in 2m0s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 02:10:33 +11:00
litruv 17d1eef572 Turn off the accepted rules and fix the design tokens, alt text, and last type errors. [skip build]
Checks / checks (push) Successful in 2m18s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 01:10:06 +11:00
litruv 3db9b499af Use EventType at the space create sites and augment the room kind key. [skip build]
Checks / checks (push) Successful in 2m5s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-02 05:24:52 +11:00
litruv fea879497c Augment the custom event types and make the dep arrays honest. [skip build]
Checks / checks (push) Successful in 2m7s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-02 05:12:35 +11:00
litruv b85a2b9290 Fix the reaction content type and the fixable lint sites. [skip build]
Checks / checks (push) Successful in 2m6s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-02 04:21:58 +11:00
litruv 9d17b14a9e Type the crypto, settings, and component any sites. [skip build]
Checks / checks (push) Successful in 2m4s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-02 03:56:07 +11:00
litruv 6c8a085ae1 Type the paarrot api, WebKit globals, and plugin command content. [skip build]
Checks / checks (push) Successful in 2m6s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-02 02:22:02 +11:00
litruv b36335cde9 Type the window and power-level casts. [skip build]
Checks / checks (push) Successful in 2m5s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-02 01:45:51 +11:00
litruv 8d6aaa619f Move the Capacitor code to the mobile overlay. [skip build]
Checks / checks (push) Successful in 2m6s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-02 01:07:20 +11:00
litruv 1e3d630b1a Fix the ref, upload, keyframes, and implicit-any type errors. [skip build]
Checks / checks (push) Successful in 2m6s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-02 00:51:31 +11:00
litruv 45f38f2ac8 Drop the mutation and sequential-await rules and the stale directives. [skip build]
Checks / checks (push) Successful in 2m6s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-02 00:09:28 +11:00
litruv 48db806dd7 Use EventType at the state and account data call sites. [skip build]
Checks / checks (push) Successful in 2m4s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 23:50:13 +11:00
litruv 634d1e0a0f Resolve the exhaustive-deps findings and attach cause to the rethrown errors. [skip build]
Checks / checks (push) Successful in 2m7s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 23:04:36 +11:00
litruv 027dbee1f1 Type the updater API and the Tauri global. [skip build]
Checks / checks (push) Successful in 2m7s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 22:36:44 +11:00
litruv 3781b05f6f Type the electron and matrix plugin call sites instead of any. [skip build]
Checks / checks (push) Successful in 2m7s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 22:08:24 +11:00
litruv eaa9ac00dd Add keyboard activation to the interactive elements and use stable keys. [skip build]
Checks / checks (push) Successful in 2m8s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 21:32:32 +11:00
litruv 664b7eb739 Rewrite the restricted iterators and reorder the forward references. [skip build]
Checks / checks (push) Successful in 2m11s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 21:05:47 +11:00
litruv 5477242661 Fix the mechanical lint groups and delete the unused bindings. [skip build]
Checks / checks (push) Successful in 2m12s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 20:31:21 +11:00
litruv 593dd3bdf3 Mount the dialog host at the app root so prompts resolve before the client route renders. [skip build]
Checks / checks (push) Successful in 2m8s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 19:55:26 +11:00
litruv 9bc8679fb7 Replace the native confirm and alert with an in-app dialog. [skip build]
Checks / checks (push) Successful in 2m8s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 11:44:17 +11:00
litruv 6805762834 Drop autofocus and move the search reset out of render. [skip build]
Checks / checks (push) Successful in 2m6s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 10:48:55 +11:00
litruv 2db4fe4734 Drop the unused eslint-disable directives. [skip build]
Checks / checks (push) Successful in 2m7s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 10:39:41 +11:00
litruv 73554ecf7f Fix the small mechanical rules. [skip build]
Checks / checks (push) Successful in 2m12s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 10:28:59 +11:00
litruv bb85cd9778 Turn off the React Compiler rules and no-bitwise. [skip build]
Checks / checks (push) Successful in 2m17s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 09:58:49 +11:00
litruv 29aaba56f0 Move the browser-encrypt-attachment types into an ambient declaration file. [skip build]
Checks / checks (push) Successful in 2m11s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 09:54:17 +11:00
litruv 24cde1447d Put the repo in the commit link. [skip build]
Checks / checks (push) Successful in 2m9s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 09:29:39 +11:00
litruv 8a53006ead Use globalThis and React.JSX in the browser code. [skip build]
Checks / checks (push) Successful in 2m10s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 09:09:00 +11:00
litruv 230ca4fcf0 Add the debug packet recorder behind the developer-tools toggle.
Checks / checks (push) Successful in 2m14s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 09:01:38 +11:00
litruv 9591d8d01b Fix the mechanical style rules. [skip build] 2026-11-01 09:01:32 +11:00
litruv 831ce01150 Turn off the base unused-vars rule for the TS files. [skip build]
Checks / checks (push) Successful in 2m10s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 07:02:36 +11:00
litruv 2d3bebdc23 Drop the unused imports and the inert unused variables. [skip build]
Checks / checks (push) Successful in 2m16s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 06:09:31 +11:00
litruv c46d4d367e Turn off no-undef for the TS files too. [skip build]
Checks / checks (push) Successful in 2m11s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 05:48:37 +11:00
litruv d6fe94ff48 Drop the dead Tauri branches and the plugin packages. [skip build]
Checks / checks (push) Successful in 2m43s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 05:31:13 +11:00
litruv 0f60822cec Fix the single-violation style findings. [skip build] 2026-11-01 05:31:04 +11:00
litruv b158648fc4 Remove the playground. [skip build]
Checks / checks (push) Successful in 2m15s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 04:53:15 +11:00
litruv 205860c168 Turn off the JSX scope rule and allow console. [skip build] 2026-11-01 04:52:19 +11:00
litruv 3be37c5d09 Export the default in the raw module declaration so the typecheck compiles.
Checks / checks (push) Successful in 2m24s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 04:27:31 +11:00
litruv a6ad8651b3 Apply the auto-fixable lint rules and the formatter, and drop the Vite build artifacts.
Checks / checks (push) Successful in 2m11s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 04:23:53 +11:00
litruv 3cd159a63e Drop the redundant try around the render check fetch.
Checks / checks (push) Successful in 1m58s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 04:01:33 +11:00
litruv 0688075542 Point the commit link at the public web base.
Checks / checks (push) Successful in 1m56s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 03:58:19 +11:00
litruv 7edf179ec9 Drop the explicit undefined initialisation of encInfo.
Checks / checks (push) Successful in 1m56s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 03:45:49 +11:00
litruv c0aa7fa8f5 Comment the fixing commit when a check issue closes.
Checks / checks (push) Successful in 1m56s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 03:43:06 +11:00
litruv a77f72f5d6 Strip the ANSI codes from check output before matching findings.
Checks / checks (push) Successful in 1m56s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 03:37:32 +11:00
litruv 7689433376 Page the open issue list so dedupe sees every check issue.
Checks / checks (push) Successful in 1m58s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-01 03:32:37 +11:00
litruv 6e6d4322c5 Port the ESLint config to flat format and file check findings as Gitea issues.
Checks / checks (push) Successful in 2m38s
Trigger cinny-mobile / dispatch (push) Successful in 2s
2026-11-01 03:20:19 +11:00
645 changed files with 13718 additions and 15345 deletions
-72
View File
@@ -1,72 +0,0 @@
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
"eslint:recommended",
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
'airbnb',
'prettier',
],
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 'latest',
sourceType: 'module',
},
"globals": {
JSX: "readonly"
},
plugins: [
'react',
'@typescript-eslint'
],
rules: {
'linebreak-style': 0,
'no-underscore-dangle': 0,
"no-shadow": "off",
"import/prefer-default-export": "off",
"import/extensions": "off",
"import/no-unresolved": "off",
"import/no-extraneous-dependencies": [
"error",
{
devDependencies: true,
},
],
'react/no-unstable-nested-components': [
'error',
{ allowAsProps: true },
],
"react/jsx-filename-extension": [
"error",
{
extensions: [".tsx", ".jsx"],
},
],
"react/require-default-props": "off",
"react/jsx-props-no-spreading": "off",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "error",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-shadow": "error"
},
overrides: [
{
files: ['*.ts'],
rules: {
'no-undef': 'off',
},
},
],
};
+45
View File
@@ -0,0 +1,45 @@
name: Checks
on:
push:
branches:
- main
jobs:
checks:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci --prefer-offline
# ci-checks.sh always exits 0: findings become issues, not failed builds.
- name: Run checks
env:
API_BASE: ${{ github.server_url }}/api/v1
# github.server_url is the internal runner host, so the commit link needs the public one.
WEB_BASE: https://git.ruv.wtf
REPO: ${{ github.repository }}
SHA: ${{ github.sha }}
# Prefer a PAT with issue write scope (secret: GITEA_TOKEN).
# Default GITHUB_TOKEN is usually scoped to this repo only.
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
TOKEN="${GITEA_TOKEN:-${GITHUB_TOKEN:-}}"
if [ -z "$TOKEN" ]; then
echo "No GITEA_TOKEN/GITHUB_TOKEN available to file issues"
exit 0
fi
export TOKEN
bash scripts/ci-checks.sh
+3
View File
@@ -6,3 +6,6 @@ devAssets
.DS_Store .DS_Store
.idea .idea
.cache .cache
# Vite build artifacts
vite.config.js.timestamp-*
+10 -10
View File
@@ -17,23 +17,23 @@ diverse, inclusive, and healthy community.
Examples of behavior that contributes to a positive environment for our Examples of behavior that contributes to a positive environment for our
community include: community include:
* Demonstrating empathy and kindness toward other people - Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences - Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback - Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, - Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience and learning from the experience
* Focusing on what is best not just for us as individuals, but for the - Focusing on what is best not just for us as individuals, but for the
overall community overall community
Examples of unacceptable behavior include: Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or - The use of sexualized language or imagery, and sexual attention or
advances of any kind advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks - Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment - Public or private harassment
* Publishing others' private information, such as a physical or email - Publishing others' private information, such as a physical or email
address, without their explicit permission address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a - Other conduct which could reasonably be considered inappropriate in a
professional setting professional setting
## Enforcement Responsibilities ## Enforcement Responsibilities
+2 -4
View File
@@ -11,10 +11,8 @@
"allowCustomHomeservers": true, "allowCustomHomeservers": true,
"featuredCommunities": { "featuredCommunities": {
"openAsDefault": false, "openAsDefault": false,
"spaces": [ "spaces": [],
], "rooms": [],
"rooms": [
],
"servers": [] "servers": []
}, },
+15 -2
View File
@@ -11,6 +11,7 @@ The API server starts automatically when you run Paarrot. It listens on `http://
**Option 1: Using Postman** **Option 1: Using Postman**
Import the Postman collection for easy testing: Import the Postman collection for easy testing:
1. Open Postman 1. Open Postman
2. Click **Import** → **File** 2. Click **Import** → **File**
3. Select `paarrot-api.postman_collection.json` 3. Select `paarrot-api.postman_collection.json`
@@ -19,16 +20,19 @@ Import the Postman collection for easy testing:
The collection is automatically updated on git push. The collection is automatically updated on git push.
**Option 2: Using the test script** **Option 2: Using the test script**
```bash ```bash
node test-api.js node test-api.js
``` ```
**Option 3: Using curl** **Option 3: Using curl**
```bash ```bash
./test-api.sh ./test-api.sh
``` ```
**Option 4: Manual curl commands** **Option 4: Manual curl commands**
```bash ```bash
# Health check # Health check
curl http://127.0.0.1:33384/health curl http://127.0.0.1:33384/health
@@ -47,7 +51,7 @@ curl -X POST http://127.0.0.1:33384/message/current \
### Common Endpoints ### Common Endpoints
| Endpoint | Method | Description | | Endpoint | Method | Description |
|----------|--------|-------------| | -------------------- | ------ | ------------------------------------------------- |
| `/health` | GET | Check if API is running | | `/health` | GET | Check if API is running |
| `/status` | GET | Get app status (mute, deafen, etc.) | | `/status` | GET | Get app status (mute, deafen, etc.) |
| `/mute/toggle` | POST | Toggle microphone mute | | `/mute/toggle` | POST | Toggle microphone mute |
@@ -69,10 +73,12 @@ curl -X POST http://127.0.0.1:33384/message/current \
2. Create buttons with these settings: 2. Create buttons with these settings:
**Mute Toggle Button:** **Mute Toggle Button:**
- URL: `http://127.0.0.1:33384/mute/toggle` - URL: `http://127.0.0.1:33384/mute/toggle`
- Method: POST - Method: POST
**Quick Message Button:** **Quick Message Button:**
- URL: `http://127.0.0.1:33384/message/current` - URL: `http://127.0.0.1:33384/message/current`
- Method: POST - Method: POST
- Body: `{"message": "BRB!"}` - Body: `{"message": "BRB!"}`
@@ -82,6 +88,7 @@ curl -X POST http://127.0.0.1:33384/message/current \
To enable full functionality, you need to implement the action handlers in the Cinny frontend: To enable full functionality, you need to implement the action handlers in the Cinny frontend:
1. Import the API handler in your app initialization: 1. Import the API handler in your app initialization:
```typescript ```typescript
import { initPaarrotAPI } from './app/paarrot-api'; import { initPaarrotAPI } from './app/paarrot-api';
@@ -98,6 +105,7 @@ initPaarrotAPI(matrixClient);
## 📖 Full Documentation ## 📖 Full Documentation
See [API.md](API.md) for complete API documentation including: See [API.md](API.md) for complete API documentation including:
- All available endpoints - All available endpoints
- Request/response formats - Request/response formats
- Error handling - Error handling
@@ -107,6 +115,7 @@ See [API.md](API.md) for complete API documentation including:
## 🛠️ Configuration ## 🛠️ Configuration
Edit `electron/api-server.js` to customize: Edit `electron/api-server.js` to customize:
- Port number (default: 33384) - Port number (default: 33384)
- Timeout duration (default: 10s) - Timeout duration (default: 10s)
- CORS settings - CORS settings
@@ -114,11 +123,13 @@ Edit `electron/api-server.js` to customize:
## 🐛 Troubleshooting ## 🐛 Troubleshooting
**API not responding:** **API not responding:**
1. Check if Paarrot is running 1. Check if Paarrot is running
2. Look for "Paarrot API server listening" in console logs 2. Look for "Paarrot API server listening" in console logs
3. Verify port 33384 is not in use: `lsof -i :33384` 3. Verify port 33384 is not in use: `lsof -i :33384`
**Actions not working:** **Actions not working:**
1. Check browser console for errors 1. Check browser console for errors
2. Ensure `initPaarrotAPI()` is called in your app 2. Ensure `initPaarrotAPI()` is called in your app
3. Implement the TODO items in `paarrot-api.ts` 3. Implement the TODO items in `paarrot-api.ts`
@@ -144,6 +155,7 @@ Edit `electron/api-server.js` and change the port number in the constructor.
## 💡 Examples ## 💡 Examples
**Python Script:** **Python Script:**
```python ```python
import requests import requests
@@ -155,12 +167,13 @@ toggle_mute()
``` ```
**JavaScript:** **JavaScript:**
```javascript ```javascript
async function sendQuickMessage(msg) { async function sendQuickMessage(msg) {
const res = await fetch('http://127.0.0.1:33384/message/current', { const res = await fetch('http://127.0.0.1:33384/message/current', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: msg }) body: JSON.stringify({ message: msg }),
}); });
return res.json(); return res.json();
} }
+38 -11
View File
@@ -22,6 +22,7 @@ Check if the API server is running.
**Endpoint**: `GET /health` **Endpoint**: `GET /health`
**Response**: **Response**:
```json ```json
{ {
"status": "ok", "status": "ok",
@@ -39,6 +40,7 @@ Get the current status of the app (mute, deafen, current room, etc.).
**Endpoint**: `GET /status` **Endpoint**: `GET /status`
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -60,6 +62,7 @@ Set the mute status.
**Endpoint**: `POST /mute` **Endpoint**: `POST /mute`
**Request Body**: **Request Body**:
```json ```json
{ {
"muted": true "muted": true
@@ -67,6 +70,7 @@ Set the mute status.
``` ```
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -85,6 +89,7 @@ Toggle the current mute status.
**Endpoint**: `POST /mute/toggle` **Endpoint**: `POST /mute/toggle`
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -103,6 +108,7 @@ Set the deafen status (deafening also mutes).
**Endpoint**: `POST /deafen` **Endpoint**: `POST /deafen`
**Request Body**: **Request Body**:
```json ```json
{ {
"deafened": true "deafened": true
@@ -110,6 +116,7 @@ Set the deafen status (deafening also mutes).
``` ```
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -128,6 +135,7 @@ Toggle the current deafen status.
**Endpoint**: `POST /deafen/toggle` **Endpoint**: `POST /deafen/toggle`
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -146,6 +154,7 @@ Switch to a different Matrix room.
**Endpoint**: `POST /channel` **Endpoint**: `POST /channel`
**Request Body**: **Request Body**:
```json ```json
{ {
"roomId": "!abc123:matrix.org" "roomId": "!abc123:matrix.org"
@@ -153,6 +162,7 @@ Switch to a different Matrix room.
``` ```
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -172,6 +182,7 @@ Get a list of available rooms/channels.
**Endpoint**: `GET /channels` **Endpoint**: `GET /channels`
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -212,6 +223,7 @@ Send a message to a specific room.
**Endpoint**: `POST /message` **Endpoint**: `POST /message`
**Request Body**: **Request Body**:
```json ```json
{ {
"roomId": "!abc123:matrix.org", "roomId": "!abc123:matrix.org",
@@ -220,6 +232,7 @@ Send a message to a specific room.
``` ```
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -239,6 +252,7 @@ Send a message to the currently active room.
**Endpoint**: `POST /message/current` **Endpoint**: `POST /message/current`
**Request Body**: **Request Body**:
```json ```json
{ {
"message": "Hello from the API!" "message": "Hello from the API!"
@@ -246,6 +260,7 @@ Send a message to the currently active room.
``` ```
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -265,6 +280,7 @@ Get information about the currently active room.
**Endpoint**: `GET /room/current` **Endpoint**: `GET /room/current`
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -287,9 +303,11 @@ Get the most recent messages across joined group channels (non-DMs).
**Endpoint**: `GET /messages/groups` **Endpoint**: `GET /messages/groups`
**Query Parameters**: **Query Parameters**:
- `limit` (optional) — number of messages to return (1–100, default `10`) - `limit` (optional) — number of messages to return (1–100, default `10`)
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -323,6 +341,7 @@ Get the most recent messages across joined direct messages.
**Endpoint**: `GET /messages/dms` **Endpoint**: `GET /messages/dms`
**Query Parameters**: **Query Parameters**:
- `limit` (optional) — number of messages to return (1–100, default `10`) - `limit` (optional) — number of messages to return (1–100, default `10`)
**Response**: same shape as groups, with `"scope": "dms"`. **Response**: same shape as groups, with `"scope": "dms"`.
@@ -336,6 +355,7 @@ Get the most recent messages across groups and DMs together.
**Endpoint**: `GET /messages/combined` **Endpoint**: `GET /messages/combined`
**Query Parameters**: **Query Parameters**:
- `limit` (optional) — number of messages to return (1–100, default `10`) - `limit` (optional) — number of messages to return (1–100, default `10`)
**Response**: same shape as groups, with `"scope": "combined"`. **Response**: same shape as groups, with `"scope": "combined"`.
@@ -349,6 +369,7 @@ List joined group channels that currently have unread activity.
**Endpoint**: `GET /unreads/groups` **Endpoint**: `GET /unreads/groups`
**Response**: **Response**:
```json ```json
{ {
"success": true, "success": true,
@@ -409,6 +430,7 @@ All endpoints return error responses in the following format:
``` ```
Common HTTP status codes: Common HTTP status codes:
- `200 OK` - Request successful - `200 OK` - Request successful
- `400 Bad Request` - Missing or invalid parameters - `400 Bad Request` - Missing or invalid parameters
- `404 Not Found` - Endpoint not found - `404 Not Found` - Endpoint not found
@@ -443,7 +465,7 @@ const fetch = require('node-fetch');
// Toggle mute // Toggle mute
async function toggleMute() { async function toggleMute() {
const response = await fetch('http://127.0.0.1:33384/mute/toggle', { const response = await fetch('http://127.0.0.1:33384/mute/toggle', {
method: 'POST' method: 'POST',
}); });
const data = await response.json(); const data = await response.json();
console.log('Muted:', data.data.muted); console.log('Muted:', data.data.muted);
@@ -454,9 +476,9 @@ async function sendMessage(roomId, message) {
const response = await fetch('http://127.0.0.1:33384/message', { const response = await fetch('http://127.0.0.1:33384/message', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ roomId, message }) body: JSON.stringify({ roomId, message }),
}); });
const data = await response.json(); const data = await response.json();
console.log('Message sent:', data.data.eventId); console.log('Message sent:', data.data.eventId);
@@ -499,14 +521,17 @@ To integrate with Stream Deck:
Example configurations: Example configurations:
**Mute Toggle Button**: **Mute Toggle Button**:
- URL: `http://127.0.0.1:33384/mute/toggle` - URL: `http://127.0.0.1:33384/mute/toggle`
- Method: POST - Method: POST
**Deafen Toggle Button**: **Deafen Toggle Button**:
- URL: `http://127.0.0.1:33384/deafen/toggle` - URL: `http://127.0.0.1:33384/deafen/toggle`
- Method: POST - Method: POST
**Send Quick Message**: **Send Quick Message**:
- URL: `http://127.0.0.1:33384/message/current` - URL: `http://127.0.0.1:33384/message/current`
- Method: POST - Method: POST
- Body: `{"message": "BRB!"}` - Body: `{"message": "BRB!"}`
@@ -524,11 +549,8 @@ Add this to your app initialization:
```typescript ```typescript
// Listen for API actions from the Electron API server // Listen for API actions from the Electron API server
if (window.electron?.api?.onAction) { if (window.electron?.api?.onAction) {
window.electron.api.onAction(async (action: { window.electron.api.onAction(
action: string; async (action: { action: string; params: any; responseChannel: string }) => {
params: any;
responseChannel: string;
}) => {
try { try {
let result; let result;
@@ -590,16 +612,17 @@ if (window.electron?.api?.onAction) {
// Send success response back // Send success response back
window.electron.api.sendResponse(action.responseChannel, { window.electron.api.sendResponse(action.responseChannel, {
success: true, success: true,
data: result data: result,
}); });
} catch (error) { } catch (error) {
// Send error response back // Send error response back
window.electron.api.sendResponse(action.responseChannel, { window.electron.api.sendResponse(action.responseChannel, {
success: false, success: false,
error: error.message error: error.message,
}); });
} }
}); },
);
} }
``` ```
@@ -627,16 +650,19 @@ The API server can be configured by modifying `electron/api-server.js`:
## Troubleshooting ## Troubleshooting
**API server not starting**: **API server not starting**:
- Check if port 33384 is already in use - Check if port 33384 is already in use
- Check console logs for errors - Check console logs for errors
- Verify Express is installed: `npm install express cors body-parser` - Verify Express is installed: `npm install express cors body-parser`
**Actions not working**: **Actions not working**:
- Ensure the client-side handler is implemented - Ensure the client-side handler is implemented
- Check browser console for errors - Check browser console for errors
- Verify the action names match between API server and client - Verify the action names match between API server and client
**Timeout errors**: **Timeout errors**:
- Actions must respond within 10 seconds - Actions must respond within 10 seconds
- Check if the Matrix client is initialized - Check if the Matrix client is initialized
- Verify the action handler is registered - Verify the action handler is registered
@@ -646,6 +672,7 @@ The API server can be configured by modifying `electron/api-server.js`:
## Future Enhancements ## Future Enhancements
Potential features to add: Potential features to add:
- WebSocket support for real-time events - WebSocket support for real-time events
- Authentication with API keys - Authentication with API keys
- Voice channel controls (join/leave) - Voice channel controls (join/leave)
+6 -1
View File
@@ -5,6 +5,7 @@ The Paarrot desktop client includes a powerful plugin system that allows you to
## What are Plugins? ## What are Plugins?
Plugins are small JavaScript modules that run inside Paarrot and can: Plugins are small JavaScript modules that run inside Paarrot and can:
- Add custom commands - Add custom commands
- Modify the UI - Modify the UI
- React to Matrix events - React to Matrix events
@@ -53,6 +54,7 @@ Use the search bar to filter plugins by name, description, author, or tags.
⚠️ **Important Security Information** ⚠️ **Important Security Information**
Plugins run with access to your Matrix client and can: Plugins run with access to your Matrix client and can:
- Read your messages - Read your messages
- Send messages on your behalf - Send messages on your behalf
- Access your room list - Access your room list
@@ -79,6 +81,7 @@ Want to create your own plugin? Check out the [Plugin API Reference](docs/PLUGIN
- `plugin-metadata.json` - Plugin information - `plugin-metadata.json` - Plugin information
2. Implement the plugin interface: 2. Implement the plugin interface:
```javascript ```javascript
module.exports = { module.exports = {
onLoad: async (context) => { onLoad: async (context) => {
@@ -87,7 +90,7 @@ module.exports = {
}, },
onUnload: async () => { onUnload: async () => {
// Cleanup when disabled // Cleanup when disabled
} },
}; };
``` ```
@@ -98,6 +101,7 @@ module.exports = {
## Plugin API ## Plugin API
Plugins have access to: Plugins have access to:
- **Matrix Client**: Full matrix-js-sdk client instance - **Matrix Client**: Full matrix-js-sdk client instance
- **React**: For building UI components - **React**: For building UI components
- **Commands**: Register custom slash commands - **Commands**: Register custom slash commands
@@ -134,6 +138,7 @@ Check out the `example-plugin/` directory for a simple example, or the `plugins/
### Performance Issues ### Performance Issues
If Paarrot becomes slow: If Paarrot becomes slow:
1. Disable plugins one by one to identify the culprit 1. Disable plugins one by one to identify the culprit
2. Check for memory leaks in the console 2. Check for memory leaks in the console
3. Contact the plugin author with details 3. Contact the plugin author with details
+172 -151
View File
@@ -27,6 +27,7 @@ Complete reference for developing plugins for Paarrot/Cinny Desktop.
### Plugin Location ### Plugin Location
Plugins are installed in: Plugins are installed in:
- **Windows**: `%APPDATA%\paarrot\plugins\<plugin-name>\` - **Windows**: `%APPDATA%\paarrot\plugins\<plugin-name>\`
- **Linux**: `~/.config/Paarrot/plugins/<plugin-name>/` - **Linux**: `~/.config/Paarrot/plugins/<plugin-name>/`
- **macOS**: `~/Library/Application Support/Paarrot/plugins/<plugin-name>/` - **macOS**: `~/Library/Application Support/Paarrot/plugins/<plugin-name>/`
@@ -59,8 +60,8 @@ Plugins are installed in:
```javascript ```javascript
module.exports = { module.exports = {
name: "My Plugin", name: 'My Plugin',
version: "1.0.0", version: '1.0.0',
dependencies: { dependencies: {
// "other-plugin": "^1.0.0" // "other-plugin": "^1.0.0"
}, },
@@ -74,9 +75,9 @@ module.exports = {
// Initialize your plugin here // Initialize your plugin here
ctx.commands.register({ ctx.commands.register({
name: "hello", name: 'hello',
description: "Say hello", description: 'Say hello',
run: () => "Hello, world!" run: () => 'Hello, world!',
}); });
}, },
@@ -90,7 +91,7 @@ module.exports = {
/** /**
* API for other plugins * API for other plugins
*/ */
exports: null exports: null,
}; };
``` ```
@@ -129,54 +130,57 @@ Register slash commands that users can type in chat.
```javascript ```javascript
ctx.commands.register({ ctx.commands.register({
name: "mycommand", name: 'mycommand',
description: "Does something cool", description: 'Does something cool',
args: ["arg1", "arg2"], // Optional args: ['arg1', 'arg2'], // Optional
run: (args) => { run: (args) => {
// Return string to send as message // Return string to send as message
return `Got args: ${args.arg1}, ${args.arg2}`; return `Got args: ${args.arg1}, ${args.arg2}`;
} },
}); });
``` ```
#### Examples #### Examples
**Simple command:** **Simple command:**
```javascript ```javascript
ctx.commands.register({ ctx.commands.register({
name: "shrug", name: 'shrug',
description: "Send a shrug emoji", description: 'Send a shrug emoji',
run: () => "¯\\_(ツ)_/¯" run: () => '¯\\_(ツ)_/¯',
}); });
// Usage: /shrug // Usage: /shrug
``` ```
**Command with arguments:** **Command with arguments:**
```javascript ```javascript
ctx.commands.register({ ctx.commands.register({
name: "greet", name: 'greet',
description: "Greet someone", description: 'Greet someone',
args: ["name"], args: ['name'],
run: ({ name }) => `Hello, ${name || 'stranger'}!` run: ({ name }) => `Hello, ${name || 'stranger'}!`,
}); });
// Usage: /greet Alice // Usage: /greet Alice
``` ```
**Advanced command:** **Advanced command:**
```javascript ```javascript
ctx.commands.register({ ctx.commands.register({
name: "calc", name: 'calc',
description: "Simple calculator", description: 'Simple calculator',
args: ["expression"], args: ['expression'],
run: ({ expression }) => { run: ({ expression }) => {
try { try {
const sanitized = expression.replace(/[^0-9+\-*/().\s]/g, ''); const sanitized = expression.replace(/[^0-9+\-*/().\s]/g, '');
const result = Function(`'use strict'; return (${sanitized})`)(); const result = Function(`'use strict'; return (${sanitized})`)();
return `${expression} = ${result}`; return `${expression} = ${result}`;
} catch (err) { } catch (err) {
return "Invalid expression"; return 'Invalid expression';
}
} }
},
}); });
// Usage: /calc 2 + 2 * 3 // Usage: /calc 2 + 2 * 3
``` ```
@@ -231,7 +235,7 @@ ctx.messages.onReceive((msg) => {
ctx.notify({ ctx.notify({
title: 'Important Message', title: 'Important Message',
body: msg.content, body: msg.content,
type: 'info' type: 'info',
}); });
} }
}); });
@@ -240,13 +244,14 @@ ctx.messages.onReceive((msg) => {
#### Real-World Examples #### Real-World Examples
**Auto-expand abbreviations:** **Auto-expand abbreviations:**
```javascript ```javascript
ctx.messages.onBeforeSend((msg) => { ctx.messages.onBeforeSend((msg) => {
const expansions = { const expansions = {
'brb': 'be right back', brb: 'be right back',
'omw': 'on my way', omw: 'on my way',
'gtg': 'got to go', gtg: 'got to go',
'afk': 'away from keyboard' afk: 'away from keyboard',
}; };
Object.entries(expansions).forEach(([abbr, full]) => { Object.entries(expansions).forEach(([abbr, full]) => {
@@ -257,6 +262,7 @@ ctx.messages.onBeforeSend((msg) => {
``` ```
**Add auto-shrug to questions:** **Add auto-shrug to questions:**
```javascript ```javascript
ctx.messages.onBeforeSend((msg) => { ctx.messages.onBeforeSend((msg) => {
if (msg.content.trim().endsWith('?')) { if (msg.content.trim().endsWith('?')) {
@@ -266,6 +272,7 @@ ctx.messages.onBeforeSend((msg) => {
``` ```
**Track mentions:** **Track mentions:**
```javascript ```javascript
ctx.messages.onReceive((msg) => { ctx.messages.onReceive((msg) => {
const userId = ctx.matrixClient.getUserId(); const userId = ctx.matrixClient.getUserId();
@@ -300,13 +307,17 @@ Register custom UI renderers for messages, images, and other content types.
```javascript ```javascript
// Custom message renderer // Custom message renderer
ctx.ui.registerRenderer("message", (msg, defaultRenderer) => { ctx.ui.registerRenderer('message', (msg, defaultRenderer) => {
// Custom logic // Custom logic
if (msg.sender?.includes('bot')) { if (msg.sender?.includes('bot')) {
// Return custom React component // Return custom React component
return ctx.React.createElement('div', { return ctx.React.createElement(
style: { background: 'yellow' } 'div',
}, msg.content); {
style: { background: 'yellow' },
},
msg.content,
);
} }
// Fall back to default // Fall back to default
@@ -314,7 +325,7 @@ ctx.ui.registerRenderer("message", (msg, defaultRenderer) => {
}); });
// Custom image renderer // Custom image renderer
ctx.ui.registerRenderer("image", (data, defaultRenderer) => { ctx.ui.registerRenderer('image', (data, defaultRenderer) => {
// Add custom effects, borders, etc. // Add custom effects, borders, etc.
return defaultRenderer?.(); return defaultRenderer?.();
}); });
@@ -328,14 +339,11 @@ interface UIAPI {
unregisterButton(id: string): void; unregisterButton(id: string): void;
registerRenderer( registerRenderer(
type: string, type: string,
renderer: (data: any, defaultRenderer?: () => ReactNode) => ReactNode renderer: (data: any, defaultRenderer?: () => ReactNode) => ReactNode,
): void; ): void;
} }
type CustomRenderer = ( type CustomRenderer = (data: any, defaultRenderer?: () => ReactNode) => ReactNode;
data: any,
defaultRenderer?: () => ReactNode
) => ReactNode;
``` ```
--- ---
@@ -354,14 +362,14 @@ ctx.ui.registerButton({
location: 'text-composer-toolbar', location: 'text-composer-toolbar',
label: 'My Tool', label: 'My Tool',
icon: '🔧', icon: '🔧',
onClick: () => ctx.log('clicked!') onClick: () => ctx.log('clicked!'),
}); });
``` ```
#### UI Locations — Nav List Rows #### UI Locations — Nav List Rows
| Location | Where it appears | | Location | Where it appears |
|---|---| | ----------------- | ----------------------------------------------------------- |
| `channel-list` | Space channel list, below Lobby and Message Search | | `channel-list` | Space channel list, below Lobby and Message Search |
| `home-section` | Home panel, inside the Rooms category above the room list | | `home-section` | Home panel, inside the Rooms category above the room list |
| `direct-messages` | DMs panel, below "Create Chat" and above the CHATS dropdown | | `direct-messages` | DMs panel, below "Create Chat" and above the CHATS dropdown |
@@ -369,7 +377,7 @@ ctx.ui.registerButton({
#### UI Locations — Icon Buttons #### UI Locations — Icon Buttons
| Location | Where it appears | | Location | Where it appears |
|---|---| | ----------------------------- | --------------------------------------------------------------------------------------------- |
| `text-composer-toolbar` | Message composer toolbar (alongside emoji, sticker buttons) | | `text-composer-toolbar` | Message composer toolbar (alongside emoji, sticker buttons) |
| `composer-actions` | Left side of the composer, beside the `+` attach button | | `composer-actions` | Left side of the composer, beside the `+` attach button |
| `room-header` | Top room header bar, before the ⋮ menu | | `room-header` | Top room header bar, before the ⋮ menu |
@@ -390,9 +398,9 @@ ctx.ui.registerButton({
position: { position: {
after: 'emoji-picker-button', after: 'emoji-picker-button',
group: 'my-tools', group: 'my-tools',
order: 1 order: 1,
}, },
onClick: () => ctx.log('clicked!') onClick: () => ctx.log('clicked!'),
}); });
``` ```
@@ -407,10 +415,17 @@ ctx.ui.unregisterButton('my-button');
```typescript ```typescript
type UILocation = type UILocation =
| 'channel-list' | 'direct-messages' | 'home-section' | 'channel-list'
| 'text-composer-toolbar' | 'composer-actions' | 'direct-messages'
| 'room-header' | 'room-menu' | 'message-actions' | 'home-section'
| 'user-menu' | 'search-notification-section' | 'sidebar-actions'; | 'text-composer-toolbar'
| 'composer-actions'
| 'room-header'
| 'room-menu'
| 'message-actions'
| 'user-menu'
| 'search-notification-section'
| 'sidebar-actions';
interface UIButtonDefinition { interface UIButtonDefinition {
id: string; id: string;
@@ -443,47 +458,47 @@ Define settings that users can configure in the UI.
ctx.settings.define({ ctx.settings.define({
// Boolean toggle // Boolean toggle
enableFeature: { enableFeature: {
type: "boolean", type: 'boolean',
label: "Enable Feature", label: 'Enable Feature',
description: "Toggle this feature on/off", description: 'Toggle this feature on/off',
default: true default: true,
}, },
// String input // String input
apiKey: { apiKey: {
type: "string", type: 'string',
label: "API Key", label: 'API Key',
description: "Your API key", description: 'Your API key',
default: "" default: '',
}, },
// Number input // Number input
maxRetries: { maxRetries: {
type: "number", type: 'number',
label: "Max Retries", label: 'Max Retries',
description: "Maximum retry attempts", description: 'Maximum retry attempts',
default: 3 default: 3,
}, },
// Select dropdown // Select dropdown
theme: { theme: {
type: "select", type: 'select',
label: "Theme", label: 'Theme',
description: "Choose a theme", description: 'Choose a theme',
options: [ options: [
{ value: "dark", label: "Dark Mode" }, { value: 'dark', label: 'Dark Mode' },
{ value: "light", label: "Light Mode" } { value: 'light', label: 'Light Mode' },
], ],
default: "dark" default: 'dark',
}, },
// Color picker // Color picker
accentColor: { accentColor: {
type: "color", type: 'color',
label: "Accent Color", label: 'Accent Color',
description: "Choose your accent color", description: 'Choose your accent color',
default: "#6366f1" default: '#6366f1',
} },
}); });
``` ```
@@ -528,9 +543,9 @@ Register custom themes that appear in the theme selector dropdown. Themes use CS
```javascript ```javascript
ctx.themes.register({ ctx.themes.register({
id: "my-theme", id: 'my-theme',
name: "My Custom Theme", name: 'My Custom Theme',
kind: "dark", // "light" or "dark" kind: 'dark', // "light" or "dark"
css: ` css: `
body.plugin-my-plugin-my-theme { body.plugin-my-plugin-my-theme {
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%); background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
@@ -543,7 +558,7 @@ ctx.themes.register({
.plugin-my-plugin-my-theme { .plugin-my-plugin-my-theme {
--tc-link: hsl(213, 100%, 80%); --tc-link: hsl(213, 100%, 80%);
} }
` `,
}); });
``` ```
@@ -563,6 +578,7 @@ Example: plugin ID `my-plugin` + theme ID `dark-blue` = `.plugin-my-plugin-dark-
#### CSS Custom Properties #### CSS Custom Properties
Available CSS variables you can override: Available CSS variables you can override:
- `--tc-link` - Link color - `--tc-link` - Link color
- `--mx-uc-1` through `--mx-uc-8` - Matrix user ID colors (for different users) - `--mx-uc-1` through `--mx-uc-8` - Matrix user ID colors (for different users)
- `--font-emoji` - Emoji font family - `--font-emoji` - Emoji font family
@@ -571,6 +587,7 @@ Available CSS variables you can override:
#### Styling Elements #### Styling Elements
Common selectors to style: Common selectors to style:
- `body.plugin-{pluginId}-{themeId}` - Body background - `body.plugin-{pluginId}-{themeId}` - Body background
- `.plugin-{pluginId}-{themeId} #root` - Main app container - `.plugin-{pluginId}-{themeId} #root` - Main app container
- `.plugin-{pluginId}-{themeId} [role="navigation"]` - Navigation sidebar - `.plugin-{pluginId}-{themeId} [role="navigation"]` - Navigation sidebar
@@ -582,11 +599,12 @@ Common selectors to style:
#### Examples #### Examples
**Dark Theme with Gradients:** **Dark Theme with Gradients:**
```javascript ```javascript
ctx.themes.register({ ctx.themes.register({
id: "midnight", id: 'midnight',
name: "Midnight Blue 🌙", name: 'Midnight Blue 🌙',
kind: "dark", kind: 'dark',
css: ` css: `
body.plugin-my-plugin-midnight { body.plugin-my-plugin-midnight {
background: linear-gradient(135deg, #0a192f 0%, #112240 50%, #1a365d 100%); background: linear-gradient(135deg, #0a192f 0%, #112240 50%, #1a365d 100%);
@@ -613,16 +631,17 @@ ctx.themes.register({
.plugin-my-plugin-midnight { .plugin-my-plugin-midnight {
--tc-link: hsl(213, 100%, 80%); --tc-link: hsl(213, 100%, 80%);
} }
` `,
}); });
``` ```
**Light Theme:** **Light Theme:**
```javascript ```javascript
ctx.themes.register({ ctx.themes.register({
id: "sunrise", id: 'sunrise',
name: "Sunrise ☀️", name: 'Sunrise ☀️',
kind: "light", kind: 'light',
css: ` css: `
body.plugin-my-plugin-sunrise { body.plugin-my-plugin-sunrise {
background: linear-gradient(135deg, #fff4e6 0%, #ffe0b2 50%, #ffcc80 100%); background: linear-gradient(135deg, #fff4e6 0%, #ffe0b2 50%, #ffcc80 100%);
@@ -645,16 +664,17 @@ ctx.themes.register({
.plugin-my-plugin-sunrise { .plugin-my-plugin-sunrise {
--tc-link: hsl(30, 100%, 40%); --tc-link: hsl(30, 100%, 40%);
} }
` `,
}); });
``` ```
**Minimal Theme:** **Minimal Theme:**
```javascript ```javascript
ctx.themes.register({ ctx.themes.register({
id: "forest", id: 'forest',
name: "Forest Green 🌲", name: 'Forest Green 🌲',
kind: "dark", kind: 'dark',
css: ` css: `
body.plugin-my-plugin-forest { body.plugin-my-plugin-forest {
background: #1a2f23; background: #1a2f23;
@@ -671,14 +691,14 @@ ctx.themes.register({
--mx-uc-7: hsl(135, 60%, 70%); --mx-uc-7: hsl(135, 60%, 70%);
--mx-uc-8: hsl(155, 60%, 70%); --mx-uc-8: hsl(155, 60%, 70%);
} }
` `,
}); });
``` ```
#### Unregister Theme #### Unregister Theme
```javascript ```javascript
ctx.themes.unregister("my-theme"); ctx.themes.unregister('my-theme');
``` ```
#### API Reference #### API Reference
@@ -699,6 +719,7 @@ interface PluginTheme {
``` ```
**Notes:** **Notes:**
- CSS is injected once when the plugin loads (not per theme change) - CSS is injected once when the plugin loads (not per theme change)
- Theme IDs are automatically prefixed with `plugin-{pluginId}-` to avoid conflicts - Theme IDs are automatically prefixed with `plugin-{pluginId}-` to avoid conflicts
- Theme class names follow the pattern: `.plugin-{pluginId}-{themeId}` - Theme class names follow the pattern: `.plugin-{pluginId}-{themeId}`
@@ -717,19 +738,19 @@ Hook into raw Matrix events for advanced functionality.
```javascript ```javascript
// Room messages // Room messages
ctx.matrix.on("m.room.message", (event) => { ctx.matrix.on('m.room.message', (event) => {
const content = event.getContent(); const content = event.getContent();
ctx.log('Message:', content.body); ctx.log('Message:', content.body);
}); });
// Membership changes // Membership changes
ctx.matrix.on("m.room.member", (event) => { ctx.matrix.on('m.room.member', (event) => {
const content = event.getContent(); const content = event.getContent();
ctx.log('Membership:', content.membership); ctx.log('Membership:', content.membership);
}); });
// Timeline events // Timeline events
ctx.matrix.on("Room.timeline", (event) => { ctx.matrix.on('Room.timeline', (event) => {
if (event.getType() === 'm.room.message') { if (event.getType() === 'm.room.message') {
const sender = event.getSender(); const sender = event.getSender();
ctx.log('Timeline event from:', sender); ctx.log('Timeline event from:', sender);
@@ -737,7 +758,7 @@ ctx.matrix.on("Room.timeline", (event) => {
}); });
// Sync state // Sync state
ctx.matrix.on("sync", (state, prevState) => { ctx.matrix.on('sync', (state, prevState) => {
ctx.log('Sync state:', state); ctx.log('Sync state:', state);
}); });
``` ```
@@ -749,10 +770,10 @@ const handler = (event) => {
ctx.log('Event received'); ctx.log('Event received');
}; };
ctx.matrix.on("m.room.message", handler); ctx.matrix.on('m.room.message', handler);
// Later... // Later...
ctx.matrix.off("m.room.message", handler); ctx.matrix.off('m.room.message', handler);
``` ```
#### API Reference #### API Reference
@@ -765,6 +786,7 @@ interface MatrixEventsAPI {
``` ```
**Common Event Types:** **Common Event Types:**
- `m.room.message` - Room messages - `m.room.message` - Room messages
- `m.room.member` - Membership changes - `m.room.member` - Membership changes
- `m.room.name` - Room name changes - `m.room.name` - Room name changes
@@ -788,7 +810,7 @@ const intervalId = ctx.timers.setInterval(() => {
// Do something periodically // Do something periodically
const stats = { const stats = {
timestamp: Date.now(), timestamp: Date.now(),
setting: ctx.settings.get('theme') setting: ctx.settings.get('theme'),
}; };
ctx.log('Stats:', stats); ctx.log('Stats:', stats);
}, 30000); }, 30000);
@@ -805,7 +827,7 @@ const timeoutId = ctx.timers.setTimeout(() => {
ctx.notify({ ctx.notify({
title: 'Reminder', title: 'Reminder',
body: 'This is a delayed notification', body: 'This is a delayed notification',
type: 'info' type: 'info',
}); });
}, 10000); // 10 seconds }, 10000); // 10 seconds
@@ -845,7 +867,7 @@ ctx.notify({
title: 'Plugin Alert', title: 'Plugin Alert',
body: 'Something important happened!', body: 'Something important happened!',
type: 'info', // 'info' | 'success' | 'error' | 'warning' type: 'info', // 'info' | 'success' | 'error' | 'warning'
duration: 5000 // milliseconds (optional) duration: 5000, // milliseconds (optional)
}); });
``` ```
@@ -856,30 +878,28 @@ ctx.notify({
ctx.notify({ ctx.notify({
title: 'Success', title: 'Success',
body: 'Operation completed successfully!', body: 'Operation completed successfully!',
type: 'success' type: 'success',
}); });
// Error notification // Error notification
ctx.notify({ ctx.notify({
title: 'Error', title: 'Error',
body: 'Something went wrong', body: 'Something went wrong',
type: 'error' type: 'error',
}); });
// Warning // Warning
ctx.notify({ ctx.notify({
title: 'Warning', title: 'Warning',
body: 'This action cannot be undone', body: 'This action cannot be undone',
type: 'warning' type: 'warning',
}); });
``` ```
#### API Reference #### API Reference
```typescript ```typescript
type NotificationFunction = ( type NotificationFunction = (options: NotificationOptions | string) => void;
options: NotificationOptions | string
) => void;
interface NotificationOptions { interface NotificationOptions {
title: string; title: string;
@@ -923,6 +943,7 @@ interface PluginContext {
``` ```
**Note:** All logs are visible in: **Note:** All logs are visible in:
- Browser console (F12) - Browser console (F12)
- Plugin logs panel (Settings → Plugins → Logs) - coming soon - Plugin logs panel (Settings → Plugins → Logs) - coming soon
@@ -939,7 +960,7 @@ module.exports = {
// ... onLoad, onUnload ... // ... onLoad, onUnload ...
exports: { exports: {
version: "1.0.0", version: '1.0.0',
utils: { utils: {
greet: (name) => `Hello, ${name}!`, greet: (name) => `Hello, ${name}!`,
@@ -947,11 +968,11 @@ module.exports = {
processText: (text) => text.toUpperCase(), processText: (text) => text.toUpperCase(),
getStats: () => ({ getStats: () => ({
version: "1.0.0", version: '1.0.0',
features: ['commands', 'settings'] features: ['commands', 'settings'],
}) }),
} },
} },
}; };
``` ```
@@ -1018,7 +1039,7 @@ ctx.log('Sync state:', syncState);
// Send custom event // Send custom event
await ctx.matrixClient.sendEvent(roomId, 'm.room.message', { await ctx.matrixClient.sendEvent(roomId, 'm.room.message', {
msgtype: 'm.text', msgtype: 'm.text',
body: 'Hello from plugin!' body: 'Hello from plugin!',
}); });
``` ```
@@ -1043,8 +1064,8 @@ Here's a complete plugin that demonstrates all features:
* Example Plugin - All Features * Example Plugin - All Features
*/ */
module.exports = { module.exports = {
name: "Example Plugin", name: 'Example Plugin',
version: "1.0.0", version: '1.0.0',
dependencies: {}, dependencies: {},
onLoad: async (ctx) => { onLoad: async (ctx) => {
@@ -1052,16 +1073,16 @@ module.exports = {
// === COMMANDS === // === COMMANDS ===
ctx.commands.register({ ctx.commands.register({
name: "hello", name: 'hello',
description: "Say hello", description: 'Say hello',
run: () => "Hello, world!" run: () => 'Hello, world!',
}); });
ctx.commands.register({ ctx.commands.register({
name: "greet", name: 'greet',
description: "Greet someone", description: 'Greet someone',
args: ["name"], args: ['name'],
run: ({ name }) => `Hello, ${name}!` run: ({ name }) => `Hello, ${name}!`,
}); });
// === INTERCEPTORS === // === INTERCEPTORS ===
@@ -1078,7 +1099,7 @@ module.exports = {
ctx.messages.onReceive((msg) => { ctx.messages.onReceive((msg) => {
// Track keywords // Track keywords
const keywords = ctx.settings.get('keywords') || ''; const keywords = ctx.settings.get('keywords') || '';
keywords.split(',').forEach(keyword => { keywords.split(',').forEach((keyword) => {
if (msg.content.includes(keyword.trim())) { if (msg.content.includes(keyword.trim())) {
ctx.notify(`Keyword detected: ${keyword}`); ctx.notify(`Keyword detected: ${keyword}`);
} }
@@ -1088,45 +1109,45 @@ module.exports = {
// === SETTINGS === // === SETTINGS ===
ctx.settings.define({ ctx.settings.define({
addEmoji: { addEmoji: {
type: "boolean", type: 'boolean',
label: "Add Emoji", label: 'Add Emoji',
description: "Add sparkles to messages", description: 'Add sparkles to messages',
default: false default: false,
}, },
keywords: { keywords: {
type: "string", type: 'string',
label: "Track Keywords", label: 'Track Keywords',
description: "Comma-separated keywords to track", description: 'Comma-separated keywords to track',
default: "important,urgent" default: 'important,urgent',
}, },
theme: { theme: {
type: "select", type: 'select',
label: "Theme", label: 'Theme',
options: [ options: [
{ value: "light", label: "Light" }, { value: 'light', label: 'Light' },
{ value: "dark", label: "Dark" } { value: 'dark', label: 'Dark' },
], ],
default: "dark" default: 'dark',
} },
}); });
// === THEMES === // === THEMES ===
ctx.themes.register({ ctx.themes.register({
id: "example-theme", id: 'example-theme',
name: "Example Theme", name: 'Example Theme',
kind: "dark", kind: 'dark',
colors: { colors: {
background: "#1a1a2e", background: '#1a1a2e',
surface: "#16213e", surface: '#16213e',
primary: "#0f3460", primary: '#0f3460',
secondary: "#533483", secondary: '#533483',
onBackground: "#ffffff", onBackground: '#ffffff',
onSurface: "#e0e0e0" onSurface: '#e0e0e0',
} },
}); });
// === MATRIX EVENTS === // === MATRIX EVENTS ===
ctx.matrix.on("m.room.message", (event) => { ctx.matrix.on('m.room.message', (event) => {
const content = event.getContent(); const content = event.getContent();
if (content.body?.includes('example')) { if (content.body?.includes('example')) {
ctx.log('Keyword found in message'); ctx.log('Keyword found in message');
@@ -1142,13 +1163,13 @@ module.exports = {
ctx.notify({ ctx.notify({
title: 'Example Plugin', title: 'Example Plugin',
body: 'Plugin loaded successfully!', body: 'Plugin loaded successfully!',
type: 'success' type: 'success',
}); });
// === EXPORTS === // === EXPORTS ===
this.exports = { this.exports = {
version: "1.0.0", version: '1.0.0',
greet: (name) => `Hello, ${name}!` greet: (name) => `Hello, ${name}!`,
}; };
ctx.log('✅ Plugin loaded'); ctx.log('✅ Plugin loaded');
@@ -1158,7 +1179,7 @@ module.exports = {
console.log('Plugin unloaded'); console.log('Plugin unloaded');
}, },
exports: null exports: null,
}; };
``` ```
@@ -1179,10 +1200,10 @@ onLoad: async (ctx) => {
ctx.notify({ ctx.notify({
title: 'Plugin Error', title: 'Plugin Error',
body: error.message, body: error.message,
type: 'error' type: 'error',
}); });
} }
} };
``` ```
### Cleanup ### Cleanup
@@ -1196,7 +1217,7 @@ onUnload: async () => {
// Settings are persisted automatically // Settings are persisted automatically
console.log('Plugin unloaded'); console.log('Plugin unloaded');
} };
``` ```
### Settings Validation ### Settings Validation
@@ -1205,7 +1226,7 @@ Validate settings before use:
```javascript ```javascript
const maxRetries = ctx.settings.get('maxRetries') || 3; const maxRetries = ctx.settings.get('maxRetries') || 3;
const keywords = (ctx.settings.get('keywords') || '').split(',').filter(k => k.trim()); const keywords = (ctx.settings.get('keywords') || '').split(',').filter((k) => k.trim());
``` ```
### Logging ### Logging
+44 -45
View File
@@ -16,7 +16,7 @@ Buttons render in two visual styles depending on location — **nav list rows**
These render as full-width list entries matching the style of built-in items like "Create Room" and "Message Search": These render as full-width list entries matching the style of built-in items like "Create Room" and "Message Search":
| Location | Where it appears | | Location | Where it appears |
|---|---| | ----------------- | ----------------------------------------------------------------------- |
| `channel-list` | Space channel list, below Lobby and Message Search | | `channel-list` | Space channel list, below Lobby and Message Search |
| `home-section` | Home panel, inside the Rooms category above the room list | | `home-section` | Home panel, inside the Rooms category above the room list |
| `direct-messages` | Direct Messages panel, below "Create Chat" and above the CHATS dropdown | | `direct-messages` | Direct Messages panel, below "Create Chat" and above the CHATS dropdown |
@@ -26,7 +26,7 @@ These render as full-width list entries matching the style of built-in items lik
These render as compact icon buttons inline with other toolbar/header controls: These render as compact icon buttons inline with other toolbar/header controls:
| Location | Where it appears | | Location | Where it appears |
|---|---| | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `text-composer-toolbar` | Message composer toolbar (alongside emoji, sticker buttons) | | `text-composer-toolbar` | Message composer toolbar (alongside emoji, sticker buttons) |
| `composer-actions` | Left side of the composer, beside the `+` attach button | | `composer-actions` | Left side of the composer, beside the `+` attach button |
| `room-header` | Top room header bar, before the ⋮ menu button | | `room-header` | Top room header bar, before the ⋮ menu button |
@@ -55,13 +55,13 @@ module.exports = {
icon: '🎨', icon: '🎨',
onClick: () => { onClick: () => {
context.log('Button clicked!'); context.log('Button clicked!');
} },
}); });
}, },
onUnload: () => { onUnload: () => {
// Buttons are automatically cleaned up on plugin unload // Buttons are automatically cleaned up on plugin unload
} },
}; };
``` ```
@@ -80,8 +80,8 @@ context.ui.registerButton({
position: { position: {
before: 'emoji-picker-button', // Place before emoji picker before: 'emoji-picker-button', // Place before emoji picker
// OR // OR
after: 'sticker-button' // Place after sticker button after: 'sticker-button', // Place after sticker button
} },
}); });
``` ```
@@ -97,8 +97,8 @@ context.ui.registerButton({
icon: '1️⃣', icon: '1️⃣',
position: { position: {
group: 'my-plugin-tools', group: 'my-plugin-tools',
order: 1 // Lower numbers appear first order: 1, // Lower numbers appear first
} },
}); });
context.ui.registerButton({ context.ui.registerButton({
@@ -108,8 +108,8 @@ context.ui.registerButton({
icon: '2️⃣', icon: '2️⃣',
position: { position: {
group: 'my-plugin-tools', group: 'my-plugin-tools',
order: 2 order: 2,
} },
}); });
``` ```
@@ -126,8 +126,8 @@ context.ui.registerButton({
position: { position: {
group: 'my-tools', group: 'my-tools',
after: 'emoji-picker-button', after: 'emoji-picker-button',
order: 1 order: 1,
} },
}); });
context.ui.registerButton({ context.ui.registerButton({
@@ -137,8 +137,8 @@ context.ui.registerButton({
icon: '🔨', icon: '🔨',
position: { position: {
group: 'my-tools', group: 'my-tools',
order: 2 order: 2,
} },
}); });
``` ```
@@ -156,7 +156,7 @@ module.exports = {
location: 'direct-messages', location: 'direct-messages',
label: 'Favourites', label: 'Favourites',
icon: '⭐', icon: '⭐',
onClick: () => context.log('Favourites clicked!') onClick: () => context.log('Favourites clicked!'),
}); });
// Nav list row — appears in the space channel list // Nav list row — appears in the space channel list
@@ -165,7 +165,7 @@ module.exports = {
location: 'channel-list', location: 'channel-list',
label: 'Quick Access', label: 'Quick Access',
icon: '⚡', icon: '⚡',
onClick: () => context.log('Quick access clicked!') onClick: () => context.log('Quick access clicked!'),
}); });
// Icon button — appears in the message composer toolbar // Icon button — appears in the message composer toolbar
@@ -176,9 +176,9 @@ module.exports = {
icon: '𝐁', icon: '𝐁',
position: { position: {
group: 'custom-formatting', group: 'custom-formatting',
order: 1 order: 1,
}, },
onClick: () => context.log('Bold clicked!') onClick: () => context.log('Bold clicked!'),
}); });
// Icon button — appears in the room header // Icon button — appears in the room header
@@ -188,7 +188,7 @@ module.exports = {
label: 'Special Search', label: 'Special Search',
icon: '🔍', icon: '🔍',
position: { after: 'search-button' }, position: { after: 'search-button' },
onClick: () => context.log('Special search clicked!') onClick: () => context.log('Special search clicked!'),
}); });
// Sidebar icon — appears above Explore and above Search // Sidebar icon — appears above Explore and above Search
@@ -197,13 +197,13 @@ module.exports = {
location: 'sidebar-actions', location: 'sidebar-actions',
label: 'Plugin Panel', label: 'Plugin Panel',
icon: '🧩', icon: '🧩',
onClick: () => context.log('Plugin panel clicked!') onClick: () => context.log('Plugin panel clicked!'),
}); });
}, },
onUnload: () => { onUnload: () => {
// All registered buttons are automatically cleaned up // All registered buttons are automatically cleaned up
} },
}; };
``` ```
@@ -228,13 +228,12 @@ const button: UIButtonDefinition = {
position: { position: {
group: 'my-tools', group: 'my-tools',
after: 'emoji-picker', after: 'emoji-picker',
order: 1 order: 1,
}, },
onClick: () => console.log('Clicked!') onClick: () => console.log('Clicked!'),
}; };
``` ```
## Basic Usage ## Basic Usage
### Simple Button ### Simple Button
@@ -252,13 +251,13 @@ module.exports = {
icon: '🎨', icon: '🎨',
onClick: () => { onClick: () => {
context.log('Button clicked!'); context.log('Button clicked!');
} },
}); });
}, },
onUnload: () => { onUnload: () => {
// Buttons are automatically cleaned up on plugin unload // Buttons are automatically cleaned up on plugin unload
} },
}; };
``` ```
@@ -277,8 +276,8 @@ context.ui.registerButton({
position: { position: {
before: 'emoji-picker-button', // Place before emoji picker before: 'emoji-picker-button', // Place before emoji picker
// OR // OR
after: 'sticker-button' // Place after sticker button after: 'sticker-button', // Place after sticker button
} },
}); });
``` ```
@@ -294,8 +293,8 @@ context.ui.registerButton({
icon: '1️⃣', icon: '1️⃣',
position: { position: {
group: 'my-plugin-tools', group: 'my-plugin-tools',
order: 1 // Lower numbers appear first order: 1, // Lower numbers appear first
} },
}); });
context.ui.registerButton({ context.ui.registerButton({
@@ -305,8 +304,8 @@ context.ui.registerButton({
icon: '2️⃣', icon: '2️⃣',
position: { position: {
group: 'my-plugin-tools', group: 'my-plugin-tools',
order: 2 order: 2,
} },
}); });
``` ```
@@ -323,8 +322,8 @@ context.ui.registerButton({
position: { position: {
group: 'my-tools', group: 'my-tools',
after: 'emoji-picker-button', after: 'emoji-picker-button',
order: 1 order: 1,
} },
}); });
context.ui.registerButton({ context.ui.registerButton({
@@ -334,8 +333,8 @@ context.ui.registerButton({
icon: '🔨', icon: '🔨',
position: { position: {
group: 'my-tools', group: 'my-tools',
order: 2 order: 2,
} },
}); });
``` ```
@@ -353,7 +352,7 @@ module.exports = {
location: 'direct-messages', location: 'direct-messages',
label: 'Favourites', label: 'Favourites',
icon: '⭐', icon: '⭐',
onClick: () => context.log('Favourites clicked!') onClick: () => context.log('Favourites clicked!'),
}); });
// Nav list row — appears in the space channel list // Nav list row — appears in the space channel list
@@ -362,7 +361,7 @@ module.exports = {
location: 'channel-list', location: 'channel-list',
label: 'Quick Access', label: 'Quick Access',
icon: '⚡', icon: '⚡',
onClick: () => context.log('Quick access clicked!') onClick: () => context.log('Quick access clicked!'),
}); });
// Icon button — appears in the message composer toolbar // Icon button — appears in the message composer toolbar
@@ -373,9 +372,9 @@ module.exports = {
icon: '𝐁', icon: '𝐁',
position: { position: {
group: 'custom-formatting', group: 'custom-formatting',
order: 1 order: 1,
}, },
onClick: () => context.log('Bold clicked!') onClick: () => context.log('Bold clicked!'),
}); });
// Icon button — appears in the room header // Icon button — appears in the room header
@@ -385,7 +384,7 @@ module.exports = {
label: 'Special Search', label: 'Special Search',
icon: '🔍', icon: '🔍',
position: { after: 'search-button' }, position: { after: 'search-button' },
onClick: () => context.log('Special search clicked!') onClick: () => context.log('Special search clicked!'),
}); });
// Sidebar icon — appears above Explore and above Search // Sidebar icon — appears above Explore and above Search
@@ -394,13 +393,13 @@ module.exports = {
location: 'sidebar-actions', location: 'sidebar-actions',
label: 'Plugin Panel', label: 'Plugin Panel',
icon: '🧩', icon: '🧩',
onClick: () => context.log('Plugin panel clicked!') onClick: () => context.log('Plugin panel clicked!'),
}); });
}, },
onUnload: () => { onUnload: () => {
// All registered buttons are automatically cleaned up // All registered buttons are automatically cleaned up
} },
}; };
``` ```
@@ -425,8 +424,8 @@ const button: UIButtonDefinition = {
position: { position: {
group: 'my-tools', group: 'my-tools',
after: 'emoji-picker', after: 'emoji-picker',
order: 1 order: 1,
}, },
onClick: () => console.log('Clicked!') onClick: () => console.log('Clicked!'),
}; };
``` ```
+28 -9
View File
@@ -5,18 +5,21 @@ All requested features have been implemented! 🎉
## ✅ Implemented Features ## ✅ Implemented Features
### 1. ✅ Enhanced Slash Commands ### 1. ✅ Enhanced Slash Commands
- **Simple commands**: `ctx.commands.register({ name: "shrug", run: () => "¯\\_(ツ)_/¯" })` - **Simple commands**: `ctx.commands.register({ name: "shrug", run: () => "¯\\_(ツ)_/¯" })`
- **Commands with args**: `ctx.commands.register({ name: "echo", args: ["text"], run: ({ text }) => text })` - **Commands with args**: `ctx.commands.register({ name: "echo", args: ["text"], run: ({ text }) => text })`
- Automatic argument parsing - Automatic argument parsing
- Execution API: `ctx.commands.execute(name, args)` - Execution API: `ctx.commands.execute(name, args)`
### 2. ✅ Message Interceptors ### 2. ✅ Message Interceptors
- **Before send**: `ctx.messages.onBeforeSend((msg) => { msg.content = "modified" })` - **Before send**: `ctx.messages.onBeforeSend((msg) => { msg.content = "modified" })`
- **On receive**: `ctx.messages.onReceive((msg) => { /* process */ })` - **On receive**: `ctx.messages.onReceive((msg) => { /* process */ })`
- Full MessageContext with content, roomId, metadata - Full MessageContext with content, roomId, metadata
- Async support for interceptors - Async support for interceptors
### 3. ✅ Custom Renderers & Button Registration ### 3. ✅ Custom Renderers & Button Registration
- **Register renderer**: `ctx.ui.registerRenderer("message", (msg, defaultRenderer) => { /* render */ })` - **Register renderer**: `ctx.ui.registerRenderer("message", (msg, defaultRenderer) => { /* render */ })`
- **Unregister renderer**: `ctx.ui.unregisterRenderer("message")` - **Unregister renderer**: `ctx.ui.unregisterRenderer("message")`
- **Register button**: `ctx.ui.registerButton({ id, location, label, icon, onClick })` - **Register button**: `ctx.ui.registerButton({ id, location, label, icon, onClick })`
@@ -29,6 +32,7 @@ All requested features have been implemented! 🎉
- See [PLUGIN_BUTTON_API.md](PLUGIN_BUTTON_API.md) for full reference - See [PLUGIN_BUTTON_API.md](PLUGIN_BUTTON_API.md) for full reference
### 4. ✅ Settings UI Per Plugin ### 4. ✅ Settings UI Per Plugin
- **Define schema**: `ctx.settings.define({ theme: { type: "select", options: [...] } })` - **Define schema**: `ctx.settings.define({ theme: { type: "select", options: [...] } })`
- **Supported types**: string, number, boolean, select, color - **Supported types**: string, number, boolean, select, color
- **Get/Set**: `ctx.settings.get(key)` / `ctx.settings.set(key, value)` - **Get/Set**: `ctx.settings.get(key)` / `ctx.settings.set(key, value)`
@@ -36,24 +40,28 @@ All requested features have been implemented! 🎉
- No JSON editing needed! - No JSON editing needed!
### 5. ✅ Hot Reload ### 5. ✅ Hot Reload
- **API**: `pluginRegistry.reloadPlugin(pluginId, newPlugin, newContext)` - **API**: `pluginRegistry.reloadPlugin(pluginId, newPlugin, newContext)`
- Auto-cleanup of old plugin resources - Auto-cleanup of old plugin resources
- Maintains enabled/disabled state - Maintains enabled/disabled state
- Dev-friendly workflow - Dev-friendly workflow
### 6. ✅ Dependency System ### 6. ✅ Dependency System
- **Declare**: `dependencies: { "paarrot.core-utils": "^1.0.0" }` - **Declare**: `dependencies: { "paarrot.core-utils": "^1.0.0" }`
- **Require**: `const utils = ctx.require("paarrot.utils")` - **Require**: `const utils = ctx.require("paarrot.utils")`
- Error handling for missing dependencies - Error handling for missing dependencies
- Plugin exports system - Plugin exports system
### 7. ✅ Raw Matrix Events Hook ### 7. ✅ Raw Matrix Events Hook
- **Full SDK access**: `ctx.matrix.on("m.room.message", (ev) => { })` - **Full SDK access**: `ctx.matrix.on("m.room.message", (ev) => { })`
- **Any event type**: Room.timeline, sync, RoomState.events, etc. - **Any event type**: Room.timeline, sync, RoomState.events, etc.
- Direct Matrix.js SDK integration - Direct Matrix.js SDK integration
- Power users will go nuts! - Power users will go nuts!
### 8. ✅ Background Tasks / Intervals ### 8. ✅ Background Tasks / Intervals
- **Interval**: `ctx.timers.setInterval(() => { /* cursed shit */ }, 10000)` - **Interval**: `ctx.timers.setInterval(() => { /* cursed shit */ }, 10000)`
- **Timeout**: `ctx.timers.setTimeout(() => { }, 5000)` - **Timeout**: `ctx.timers.setTimeout(() => { }, 5000)`
- **Clear**: `ctx.timers.clearInterval(id)` / `ctx.timers.clearTimeout(id)` - **Clear**: `ctx.timers.clearInterval(id)` / `ctx.timers.clearTimeout(id)`
@@ -61,12 +69,14 @@ All requested features have been implemented! 🎉
- Perfect for bots, reminders, auto-cleanup - Perfect for bots, reminders, auto-cleanup
### 9. ✅ Notifications API ### 9. ✅ Notifications API
- **Simple**: `ctx.notify("Oi")` - **Simple**: `ctx.notify("Oi")`
- **Advanced**: `ctx.notify({ title: "Oi", body: "New message from Steve", type: "info" })` - **Advanced**: `ctx.notify({ title: "Oi", body: "New message from Steve", type: "info" })`
- Action buttons support - Action buttons support
- Custom duration - Custom duration
### 10. ✅ Plugin Logs Panel ### 10. ✅ Plugin Logs Panel
- **Logging**: `ctx.log()`, `ctx.warn()`, `ctx.error()` - **Logging**: `ctx.log()`, `ctx.warn()`, `ctx.error()`
- Per-plugin log storage - Per-plugin log storage
- Visible in `pluginRegistry.getLogs(pluginId)` - Visible in `pluginRegistry.getLogs(pluginId)`
@@ -85,16 +95,19 @@ All requested features have been implemented! 🎉
## 📁 Files Changed ## 📁 Files Changed
### Core System ### Core System
- [`PluginAPI.ts`](cinny/src/app/features/settings/plugins/PluginAPI.ts) - Enhanced with all APIs - [`PluginAPI.ts`](cinny/src/app/features/settings/plugins/PluginAPI.ts) - Enhanced with all APIs
- [`PluginLoader.tsx`](cinny/src/app/features/settings/plugins/PluginLoader.tsx) - Complete rewrite with context creation - [`PluginLoader.tsx`](cinny/src/app/features/settings/plugins/PluginLoader.tsx) - Complete rewrite with context creation
- [`index.ts`](cinny/src/app/features/settings/plugins/index.ts) - Exports updated - [`index.ts`](cinny/src/app/features/settings/plugins/index.ts) - Exports updated
### Documentation ### Documentation
- [`PLUGIN_DEVELOPMENT.md`](cinny/src/app/features/settings/plugins/PLUGIN_DEVELOPMENT.md) - Comprehensive guide - [`PLUGIN_DEVELOPMENT.md`](cinny/src/app/features/settings/plugins/PLUGIN_DEVELOPMENT.md) - Comprehensive guide
- [`PLUGINS.md`](PLUGINS.md) - User guide - [`PLUGINS.md`](PLUGINS.md) - User guide
- [`example-plugin/index.js`](example-plugin/index.js) - Full-featured example - [`example-plugin/index.js`](example-plugin/index.js) - Full-featured example
### Integration ### Integration
- [`ClientRoot.tsx`](cinny/src/app/pages/client/ClientRoot.tsx) - PluginLoader integrated - [`ClientRoot.tsx`](cinny/src/app/pages/client/ClientRoot.tsx) - PluginLoader integrated
- [`main.js`](electron/main.js) - IPC handler for reading plugin code - [`main.js`](electron/main.js) - IPC handler for reading plugin code
- [`preload.js`](electron/preload.js) - readPluginCode API exposed - [`preload.js`](electron/preload.js) - readPluginCode API exposed
@@ -103,32 +116,36 @@ All requested features have been implemented! 🎉
## 🚀 Usage Examples ## 🚀 Usage Examples
### Command with Args ### Command with Args
```javascript ```javascript
ctx.commands.register({ ctx.commands.register({
name: "echo", name: 'echo',
args: ["text"], args: ['text'],
run: ({ text }) => text run: ({ text }) => text,
}); });
``` ```
### Message Interceptor ### Message Interceptor
```javascript ```javascript
ctx.messages.onBeforeSend((msg) => { ctx.messages.onBeforeSend((msg) => {
if (msg.content === "brb") { if (msg.content === 'brb') {
msg.content = "be right back ya legend"; msg.content = 'be right back ya legend';
} }
}); });
``` ```
### Custom Settings ### Custom Settings
```javascript ```javascript
ctx.settings.define({ ctx.settings.define({
theme: { type: "select", options: ["dark", "light"] }, theme: { type: 'select', options: ['dark', 'light'] },
spamFilter: { type: "boolean", default: true } spamFilter: { type: 'boolean', default: true },
}); });
``` ```
### Background Tasks ### Background Tasks
```javascript ```javascript
ctx.timers.setInterval(() => { ctx.timers.setInterval(() => {
// do cursed shit every 10s // do cursed shit every 10s
@@ -136,15 +153,17 @@ ctx.timers.setInterval(() => {
``` ```
### Raw Matrix Events ### Raw Matrix Events
```javascript ```javascript
ctx.matrix.on("m.room.message", (ev) => { ctx.matrix.on('m.room.message', (ev) => {
ctx.log('Message:', ev.getContent().body); ctx.log('Message:', ev.getContent().body);
}); });
``` ```
### Plugin Dependencies ### Plugin Dependencies
```javascript ```javascript
const utils = ctx.require("paarrot.utils"); const utils = ctx.require('paarrot.utils');
utils.doSomething(); utils.doSomething();
``` ```
+2 -2
View File
@@ -21,7 +21,7 @@
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | -------------- | --------------------- |
| `path/to/file` | <!-- what it does --> | | `path/to/file` | <!-- what it does --> |
## Data model ## Data model
@@ -29,7 +29,7 @@
<!-- Matrix state events, account data types, local storage keys. --> <!-- Matrix state events, account data types, local storage keys. -->
| Key / event | Scope | Shape | | Key / event | Scope | Shape |
|-------------|-------|-------| | ----------- | ----- | ----- |
| | | | | | | |
## Dependencies ## Dependencies
+1 -1
View File
@@ -26,7 +26,7 @@ tauri.ts → native notification APIs
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ---------------------------------------------------- | --------------------------------- |
| `cinny/capacitor.config.json` | Capacitor app id, web dir | | `cinny/capacitor.config.json` | Capacitor app id, web dir |
| `src-tauri/src/main.rs` | Tauri Android entry | | `src-tauri/src/main.rs` | Tauri Android entry |
| `cinny/src/app/utils/tauri.ts` | Platform detection, notifications | | `cinny/src/app/utils/tauri.ts` | Platform detection, notifications |
@@ -26,7 +26,7 @@ ClientRoot (authenticated)
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------------------ | ------------------------ |
| `cinny/src/app/pages/auth/login/Login.tsx` | Login hub | | `cinny/src/app/pages/auth/login/Login.tsx` | Login hub |
| `cinny/src/app/pages/auth/login/PasswordLoginForm.tsx` | Password login | | `cinny/src/app/pages/auth/login/PasswordLoginForm.tsx` | Password login |
| `cinny/src/app/pages/auth/login/TokenLogin.tsx` | Access token login | | `cinny/src/app/pages/auth/login/TokenLogin.tsx` | Access token login |
@@ -45,7 +45,7 @@ ClientRoot (authenticated)
## Data model ## Data model
| Key | Storage | Content | | Key | Storage | Content |
|-----|---------|---------| | --------------------------- | --------------------- | ---------------------------------------- |
| Session store | localStorage | access token, user id, device id, hs url | | Session store | localStorage | access token, user id, device id, hs url |
| `setAfterLoginRedirectPath` | sessionStorage/memory | deep link target after login | | `setAfterLoginRedirectPath` | sessionStorage/memory | deep link target after login |
@@ -25,7 +25,7 @@ Other clients / Profile.tsx
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ----------------------------------------------------- | ----------------------------- |
| `cinny/src/app/utils/imageMetadata.ts` | Unified embed/extract API | | `cinny/src/app/utils/imageMetadata.ts` | Unified embed/extract API |
| `cinny/src/app/utils/pngMetadata.ts` | PNG tEXt chunks | | `cinny/src/app/utils/pngMetadata.ts` | PNG tEXt chunks |
| `cinny/src/app/utils/jpegMetadata.ts` | JPEG XMP APP1 | | `cinny/src/app/utils/jpegMetadata.ts` | JPEG XMP APP1 |
@@ -38,7 +38,7 @@ Other clients / Profile.tsx
Metadata keys (embedded in binary image, not Matrix): Metadata keys (embedded in binary image, not Matrix):
| Key | Format | Notes | | Key | Format | Notes |
|-----|--------|-------| | --------------------- | ------------------- | ---------------- |
| `paarrot:color` | All | Accent color hex | | `paarrot:color` | All | Accent color hex |
| `paarrot:banner` | PNG (+ unified API) | Banner image URL | | `paarrot:banner` | PNG (+ unified API) | Banner image URL |
| `paarrot:borderColor` | PNG | Border accent | | `paarrot:borderColor` | PNG | Border accent |
@@ -28,7 +28,7 @@ tauri.ts / electron main
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ---------------------------------------------------------------------- | ------------------------------------------------------- |
| `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Favicon, notifications, API init, background sync hooks | | `cinny/src/app/pages/client/ClientNonUIFeatures.tsx` | Favicon, notifications, API init, background sync hooks |
| `cinny/src/app/utils/backgroundSync.ts` | Pushers, UnifiedPush, foreground state | | `cinny/src/app/utils/backgroundSync.ts` | Pushers, UnifiedPush, foreground state |
| `cinny/src/app/utils/tauri.ts` | Tauri/Capacitor notification helpers | | `cinny/src/app/utils/tauri.ts` | Tauri/Capacitor notification helpers |
@@ -39,7 +39,7 @@ tauri.ts / electron main
## Data model ## Data model
| Key | Storage | Purpose | | Key | Storage | Purpose |
|-----|---------|---------| | ------------------------- | ------------------- | ----------------- |
| `paarrot.unifiedpush.*` | localStorage prefix | UP endpoint state | | `paarrot.unifiedpush.*` | localStorage prefix | UP endpoint state |
| `com.paarrot.app.android` | Pusher app id base | Android pushers | | `com.paarrot.app.android` | Pusher app id base | Android pushers |
| Matrix pusher | Homeserver | HTTP push gateway | | Matrix pusher | Homeserver | HTTP push gateway |
@@ -28,7 +28,7 @@ SpecVersions in ClientRoot
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------------------- | ------------------------ |
| `cinny/src/app/components/title-bar/TitleBar.tsx` | Desktop title bar | | `cinny/src/app/components/title-bar/TitleBar.tsx` | Desktop title bar |
| `cinny/src/app/components/splash-screen/SplashScreen.tsx` | Splash | | `cinny/src/app/components/splash-screen/SplashScreen.tsx` | Splash |
| `cinny/src/app/pages/client/WelcomePage.tsx` | Welcome / download links | | `cinny/src/app/pages/client/WelcomePage.tsx` | Welcome / download links |
@@ -43,7 +43,7 @@ SpecVersions in ClientRoot
## Data model ## Data model
| Key | Storage | | Key | Storage |
|-----|---------| | -------------- | ---------------------------- |
| Sessions | multi-account in sessions.ts | | Sessions | multi-account in sessions.ts |
| electron-store | window bounds (main process) | | electron-store | window bounds (main process) |
@@ -27,7 +27,7 @@ Imported by room-settings and space-settings shells
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------------------- | ----------------------- |
| `cinny/src/app/features/common-settings/general/RoomProfile.tsx` | Name/topic/avatar | | `cinny/src/app/features/common-settings/general/RoomProfile.tsx` | Name/topic/avatar |
| `cinny/src/app/features/common-settings/general/RoomJoinRules.tsx` | Join rules | | `cinny/src/app/features/common-settings/general/RoomJoinRules.tsx` | Join rules |
| `cinny/src/app/features/common-settings/general/RoomEncryption.tsx` | E2E toggle | | `cinny/src/app/features/common-settings/general/RoomEncryption.tsx` | E2E toggle |
@@ -27,7 +27,7 @@ State: createRoomModal.ts, createSpaceModal.ts
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ---------------------------------------------------------- | ------------------------------------ |
| `cinny/src/app/features/create-room/CreateRoomModal.tsx` | Room create + sub-room parent update | | `cinny/src/app/features/create-room/CreateRoomModal.tsx` | Room create + sub-room parent update |
| `cinny/src/app/features/create-space/CreateSpaceModal.tsx` | Space create | | `cinny/src/app/features/create-space/CreateSpaceModal.tsx` | Space create |
| `cinny/src/app/features/create-chat/` | DM flows | | `cinny/src/app/features/create-chat/` | DM flows |
@@ -24,7 +24,7 @@ settings emojis-stickers + common-settings emojis
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------------------ | ------------------- |
| `cinny/src/app/plugins/custom-emoji/PackMetaReader.ts` | Read pack metadata | | `cinny/src/app/plugins/custom-emoji/PackMetaReader.ts` | Read pack metadata |
| `cinny/src/app/plugins/custom-emoji/PackImageReader.ts` | Single image | | `cinny/src/app/plugins/custom-emoji/PackImageReader.ts` | Single image |
| `cinny/src/app/plugins/custom-emoji/PackImagesReader.ts` | Bulk images | | `cinny/src/app/plugins/custom-emoji/PackImagesReader.ts` | Bulk images |
@@ -38,7 +38,7 @@ settings emojis-stickers + common-settings emojis
## Data model ## Data model
| Event | Purpose | | Event | Purpose |
|-------|---------| | ----------------------- | -------------------------------------- |
| `im.ponies.room_emotes` | Room emoji pack definition | | `im.ponies.room_emotes` | Room emoji pack definition |
| Image pack account data | User/global packs (see emoji-stickers) | | Image pack account data | User/global packs (see emoji-stickers) |
@@ -22,7 +22,7 @@ common-settings/developer-tools/
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ----------------------------------------------------------------------------- | -------------------- |
| `cinny/src/app/features/settings/developer-tools/DevelopTools.tsx` | User-level dev tools | | `cinny/src/app/features/settings/developer-tools/DevelopTools.tsx` | User-level dev tools |
| `cinny/src/app/features/settings/developer-tools/AccountData.tsx` | Account data viewer | | `cinny/src/app/features/settings/developer-tools/AccountData.tsx` | Account data viewer |
| `cinny/src/app/features/common-settings/developer-tools/DevelopTools.tsx` | Room dev tools entry | | `cinny/src/app/features/common-settings/developer-tools/DevelopTools.tsx` | Room dev tools entry |
@@ -25,7 +25,7 @@ mDirectAtom — direct room index
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ----------------------------------------------------- | --------------- |
| `cinny/src/app/pages/client/direct/Direct.tsx` | DM list | | `cinny/src/app/pages/client/direct/Direct.tsx` | DM list |
| `cinny/src/app/pages/client/direct/DirectCreate.tsx` | Create DM | | `cinny/src/app/pages/client/direct/DirectCreate.tsx` | Create DM |
| `cinny/src/app/pages/client/direct/useDirectRooms.ts` | List logic | | `cinny/src/app/pages/client/direct/useDirectRooms.ts` | List logic |
@@ -36,7 +36,7 @@ mDirectAtom — direct room index
## Data model ## Data model
| Key | Scope | | Key | Scope |
|-----|-------| | ---------- | ------------------------------------------ |
| `m.direct` | User account data — map userId → roomIds[] | | `m.direct` | User account data — map userId → roomIds[] |
## Dependencies ## Dependencies
@@ -25,7 +25,7 @@ useSecretStorage, useKeyBackup, useVerificationRequest hooks
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ---------------------------------------------------------- | --------------------- |
| `cinny/src/client/secretStorageKeys.ts` | SSSS key handling | | `cinny/src/client/secretStorageKeys.ts` | SSSS key handling |
| `cinny/src/app/features/settings/devices/Devices.tsx` | Device list | | `cinny/src/app/features/settings/devices/Devices.tsx` | Device list |
| `cinny/src/app/features/settings/devices/Verification.tsx` | Verification UI | | `cinny/src/app/features/settings/devices/Verification.tsx` | Verification UI |
@@ -41,7 +41,7 @@ useSecretStorage, useKeyBackup, useVerificationRequest hooks
## Data model ## Data model
| Store | Purpose | | Store | Purpose |
|-------|---------| | ------------------- | ----------------------------------------- |
| IndexedDB crypto | Olm account, Megolm sessions | | IndexedDB crypto | Olm account, Megolm sessions |
| SSSS | Cross-signing keys, backup key | | SSSS | Cross-signing keys, backup key |
| Matrix account data | `m.cross_signing.*`, `m.secret_storage.*` | | Matrix account data | `m.cross_signing.*`, `m.secret_storage.*` |
@@ -26,7 +26,7 @@ text-area plugin (legacy/plain areas in some UI)
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ----------------------------------------------- | ------------------------- |
| `cinny/src/app/components/editor/Editor.tsx` | Main Slate editor | | `cinny/src/app/components/editor/Editor.tsx` | Main Slate editor |
| `cinny/src/app/components/editor/Toolbar.tsx` | Formatting toolbar | | `cinny/src/app/components/editor/Toolbar.tsx` | Formatting toolbar |
| `cinny/src/app/components/editor/input.ts` | Parse into editor | | `cinny/src/app/components/editor/input.ts` | Parse into editor |
@@ -41,7 +41,7 @@ text-area plugin (legacy/plain areas in some UI)
## Data model ## Data model
| Key | Storage | | Key | Storage |
|-----|---------| | ------------------------------- | --------------------- |
| `roomIdToMsgDraftAtomFamily` | localStorage per room | | `roomIdToMsgDraftAtomFamily` | localStorage per room |
| `roomIdToUploadItemsAtomFamily` | pending uploads | | `roomIdToUploadItemsAtomFamily` | pending uploads |
@@ -26,7 +26,7 @@ preload / contextBridge → window.electron in renderer
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------- | ---------------------------- |
| `electron/main.js` | Main process entry | | `electron/main.js` | Main process entry |
| `electron/api-server.js` | Local HTTP API | | `electron/api-server.js` | Local HTTP API |
| `electron/preload.js` (if exists) | IPC bridge | | `electron/preload.js` (if exists) | IPC bridge |
@@ -39,7 +39,7 @@ preload / contextBridge → window.electron in renderer
## Data model ## Data model
| Store | Tool | Contents | | Store | Tool | Contents |
|-------|------|----------| | ---------------- | -------- | ------------------------- |
| `electron-store` | main.js | Window bounds, user prefs | | `electron-store` | main.js | Window bounds, user prefs |
| UserData | Electron | plugins, caches | | UserData | Electron | plugins, caches |
@@ -22,7 +22,7 @@ useRoomWideEmbedFilters (room state)
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ----------------------------------------------------------------- | ----------------------------- |
| `cinny/src/app/hooks/useRoomEmbedFilters.ts` | Hooks, types, combine logic | | `cinny/src/app/hooks/useRoomEmbedFilters.ts` | Hooks, types, combine logic |
| `cinny/src/types/matrix/room.ts` | `StateEvent.RoomEmbedFilters` | | `cinny/src/types/matrix/room.ts` | `StateEvent.RoomEmbedFilters` |
| `cinny/src/app/features/room/ThreadView.tsx` | Consumer | | `cinny/src/app/features/room/ThreadView.tsx` | Consumer |
@@ -34,7 +34,7 @@ useRoomWideEmbedFilters (room state)
## Data model ## Data model
| Key | Scope | Content | | Key | Scope | Content |
|-----|-------|---------| | ------------------------------- | ---------------------------- | -------------------------------- |
| `im.paarrot.embed_filters` | Room account data (per user) | `{ disabledPatterns: string[] }` | | `im.paarrot.embed_filters` | Room account data (per user) | `{ disabledPatterns: string[] }` |
| `im.paarrot.room.embed_filters` | Room state | `{ disabledPatterns: string[] }` | | `im.paarrot.room.embed_filters` | Room state | `{ disabledPatterns: string[] }` |
@@ -25,7 +25,7 @@ Settings / common-settings EmojisStickers pages
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | -------------------------------------------------------------------- | --------------------------- |
| `cinny/src/app/hooks/useEmojiUsage.ts` | Usage stats in account data | | `cinny/src/app/hooks/useEmojiUsage.ts` | Usage stats in account data |
| `cinny/src/app/utils/telegramStickerImport.ts` | Telegram Bot API import | | `cinny/src/app/utils/telegramStickerImport.ts` | Telegram Bot API import |
| `cinny/src/app/features/settings/emojis-stickers/TelegramImport.tsx` | Import UI | | `cinny/src/app/features/settings/emojis-stickers/TelegramImport.tsx` | Import UI |
@@ -39,7 +39,7 @@ Settings / common-settings EmojisStickers pages
## Data model ## Data model
| Key | Scope | Content | | Key | Scope | Content |
|-----|-------|---------| | -------------------------- | ----------------- | ----------------------------------- |
| `paarrot.favemojis` | User account data | Emoji usage counts | | `paarrot.favemojis` | User account data | Emoji usage counts |
| `cinny_telegram_bot_token` | localStorage | Telegram bot token (TelegramImport) | | `cinny_telegram_bot_token` | localStorage | Telegram bot token (TelegramImport) |
| `im.ponies.room_emotes` | Room state | Standard Matrix emoji packs | | `im.ponies.room_emotes` | Room state | Standard Matrix emoji packs |
+1 -1
View File
@@ -25,7 +25,7 @@ client/explore/
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------- | -------------------- |
| `cinny/src/app/pages/client/explore/Explore.tsx` | Explore hub | | `cinny/src/app/pages/client/explore/Explore.tsx` | Explore hub |
| `cinny/src/app/pages/client/explore/Server.tsx` | Server directory | | `cinny/src/app/pages/client/explore/Server.tsx` | Server directory |
| `cinny/src/app/pages/client/explore/Featured.tsx` | Featured list | | `cinny/src/app/pages/client/explore/Featured.tsx` | Featured list |
+2 -2
View File
@@ -28,7 +28,7 @@ Routing: `getSpaceDefaultPath` + `shouldShowForumLobby` in path utils / room uti
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------- | -------------------------------- |
| `cinny/src/app/features/forum/ForumFeedPage.tsx` | Main feed page | | `cinny/src/app/features/forum/ForumFeedPage.tsx` | Main feed page |
| `cinny/src/app/features/forum/ForumSpaceLayout.tsx` | Layout shell | | `cinny/src/app/features/forum/ForumSpaceLayout.tsx` | Layout shell |
| `cinny/src/app/features/forum/ForumAwareSpaceLayout.tsx` | Forum vs non-forum switch | | `cinny/src/app/features/forum/ForumAwareSpaceLayout.tsx` | Forum vs non-forum switch |
@@ -45,7 +45,7 @@ Routing: `getSpaceDefaultPath` + `shouldShowForumLobby` in path utils / room uti
## Data model ## Data model
| Signal | Purpose | | Signal | Purpose |
|--------|---------| | ----------------------------------- | ------------------------------------ |
| `m.room.create` `type: m.forum` | Matrix forum room type | | `m.room.create` `type: m.forum` | Matrix forum room type |
| `im.paarrot.room.kind: forum_space` | Paarrot forum classification | | `im.paarrot.room.kind: forum_space` | Paarrot forum classification |
| `com.matrixsso.title` on messages | Forum post title (legacy/custom) | | `com.matrixsso.title` on messages | Forum post title (legacy/custom) |
@@ -22,7 +22,7 @@ useAsyncSearch or similar for filtering
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | -------------------------------------------------- | ---------------- |
| `cinny/src/app/features/search/Search.tsx` | Modal UI | | `cinny/src/app/features/search/Search.tsx` | Modal UI |
| `cinny/src/app/state/searchModal.ts` | Open/close state | | `cinny/src/app/state/searchModal.ts` | Open/close state |
| `cinny/src/app/pages/client/sidebar/SearchTab.tsx` | Sidebar entry | | `cinny/src/app/pages/client/sidebar/SearchTab.tsx` | Sidebar entry |
@@ -30,7 +30,7 @@ useAsyncSearch or similar for filtering
## Data model ## Data model
| Key | Storage | | Key | Storage |
|-----|---------| | ------------------ | ------- |
| `searchModal` atom | memory | | `searchModal` atom | memory |
## Dependencies ## Dependencies
@@ -25,7 +25,7 @@ DirectTab.tsx → useDirectRooms.ts
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------- | ----------------------------------- |
| `cinny/src/app/pages/client/home/Home.tsx` | Home room list UI | | `cinny/src/app/pages/client/home/Home.tsx` | Home room list UI |
| `cinny/src/app/pages/client/home/useHomeRooms.ts` | Room list logic + Paarrot room kind | | `cinny/src/app/pages/client/home/useHomeRooms.ts` | Room list logic + Paarrot room kind |
| `cinny/src/app/pages/client/SidebarNav.tsx` | Sidebar tab bar | | `cinny/src/app/pages/client/SidebarNav.tsx` | Sidebar tab bar |
@@ -43,7 +43,7 @@ DirectTab.tsx → useDirectRooms.ts
## Data model ## Data model
| Source | Data | | Source | Data |
|--------|------| | ---------------------- | ------------------------------- |
| `allRoomsAtom` | Joined rooms | | `allRoomsAtom` | Joined rooms |
| `roomToUnreadAtom` | Badge state | | `roomToUnreadAtom` | Badge state |
| `mDirectAtom` | DM room mapping | | `mDirectAtom` | DM room mapping |
@@ -23,7 +23,7 @@ ClientRoomsNotificationPreferences.tsx — bulk prefs
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------------------------- | ------------------ |
| `cinny/src/app/pages/client/inbox/Inbox.tsx` | Inbox layout | | `cinny/src/app/pages/client/inbox/Inbox.tsx` | Inbox layout |
| `cinny/src/app/pages/client/inbox/Invites.tsx` | Invites UI | | `cinny/src/app/pages/client/inbox/Invites.tsx` | Invites UI |
| `cinny/src/app/pages/client/inbox/Notifications.tsx` | Notifications list | | `cinny/src/app/pages/client/inbox/Notifications.tsx` | Notifications list |
@@ -35,7 +35,7 @@ ClientRoomsNotificationPreferences.tsx — bulk prefs
## Data model ## Data model
| Source | Data | | Source | Data |
|--------|------| | ------------ | --------------------------------------- |
| Sync | `m.room.member` invite membership | | Sync | `m.room.member` invite membership |
| Account data | push rules, per-room notification prefs | | Account data | push rules, per-room notification prefs |
@@ -23,7 +23,7 @@ Route: _JOIN_PATH in Router.tsx
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | -------------------------------------------------------------------- | -------------------- |
| `cinny/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx` | Preview + join UI | | `cinny/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx` | Preview + join UI |
| `cinny/src/app/components/RoomSummaryLoader.tsx` | Fetch room preview | | `cinny/src/app/components/RoomSummaryLoader.tsx` | Fetch room preview |
| `cinny/src/app/hooks/useRoomNavigate.ts` | Post-join navigation | | `cinny/src/app/hooks/useRoomNavigate.ts` | Post-join navigation |
@@ -24,7 +24,7 @@ Space route → Lobby.tsx (SpaceCardLobby)
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ---------------------------------------------------- | --------------------------------------- |
| `cinny/src/app/features/lobby/Lobby.tsx` | Main lobby view | | `cinny/src/app/features/lobby/Lobby.tsx` | Main lobby view |
| `cinny/src/app/features/lobby/LobbyHeader.tsx` | Space header | | `cinny/src/app/features/lobby/LobbyHeader.tsx` | Space header |
| `cinny/src/app/features/lobby/LobbyHero.tsx` | Hero banner area | | `cinny/src/app/features/lobby/LobbyHero.tsx` | Hero banner area |
@@ -40,7 +40,7 @@ Space route → Lobby.tsx (SpaceCardLobby)
## Data model ## Data model
| Event / field | Purpose | | Event / field | Purpose |
|---------------|---------| | ------------------------------ | ----------------------------------------------- |
| `m.space.child` | Child room membership + `order` | | `m.space.child` | Child room membership + `order` |
| `im.paarrot.sub_rooms` | Paarrot nested children (see sub-rooms handoff) | | `im.paarrot.sub_rooms` | Paarrot nested children (see sub-rooms handoff) |
| `im.paarrot.room.kind` | e.g. `forum_space` for forum behavior | | `im.paarrot.room.kind` | e.g. `forum_space` for forum behavior |
+2 -2
View File
@@ -26,7 +26,7 @@ Navigation for room changes uses `setPaarrotNavigate()` registered from the Reac
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ---------------------------------------------------- | -------------------------------------------------------- |
| `electron/api-server.js` | Express routes, IPC bridge to renderer | | `electron/api-server.js` | Express routes, IPC bridge to renderer |
| `electron/main.js` | Starts `PaarrotAPIServer` with the main window | | `electron/main.js` | Starts `PaarrotAPIServer` with the main window |
| `cinny/src/app/paarrot-api.ts` | Action handlers (mute, deafen, channel, message, status) | | `cinny/src/app/paarrot-api.ts` | Action handlers (mute, deafen, channel, message, status) |
@@ -41,7 +41,7 @@ No persistent storage. Actions read/write ephemeral app state (current room, cal
### IPC actions (renderer) ### IPC actions (renderer)
| Action | Params | Returns | | Action | Params | Returns |
|--------|--------|---------| | ------------------------------ | --------------------- | -------------------------------------------- |
| `get-status` | — | mute, deafen, currentRoom, connected, userId | | `get-status` | — | mute, deafen, currentRoom, connected, userId |
| `toggle-mute` / `set-mute` | `{ muted? }` | `{ muted }` | | `toggle-mute` / `set-mute` | `{ muted? }` | `{ muted }` |
| `toggle-deafen` / `set-deafen` | `{ deafened? }` | `{ deafened }` | | `toggle-deafen` / `set-deafen` | `{ deafened? }` | `{ deafened }` |
@@ -26,7 +26,7 @@ initMatrix.ts
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------- | --------------------------------------------- |
| `cinny/src/client/initMatrix.ts` | createClient, start/stop, logout, cache clear | | `cinny/src/client/initMatrix.ts` | createClient, start/stop, logout, cache clear |
| `cinny/src/client/secretStorageKeys.ts` | SSSS / secret storage callbacks | | `cinny/src/client/secretStorageKeys.ts` | SSSS / secret storage callbacks |
| `cinny/src/app/pages/client/ClientRoot.tsx` | Bootstrap, providers, title bar | | `cinny/src/app/pages/client/ClientRoot.tsx` | Bootstrap, providers, title bar |
@@ -38,7 +38,7 @@ initMatrix.ts
## Data model ## Data model
| Store | Backend | Purpose | | Store | Backend | Purpose |
|-------|---------|---------| | ---------------------- | ------------- | ------------------- |
| IndexedDB sync store | matrix-js-sdk | Room timeline cache | | IndexedDB sync store | matrix-js-sdk | Room timeline cache |
| IndexedDB crypto store | matrix-js-sdk | Olm/Megolm keys | | IndexedDB crypto store | matrix-js-sdk | Olm/Megolm keys |
| Session | localStorage | Auth credentials | | Session | localStorage | Auth credentials |
@@ -27,7 +27,7 @@ image-viewer/, video-viewer/ — fullscreen media
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------------------- | ----------------------------- |
| `cinny/src/app/components/upload-card/UploadCardRenderer.tsx` | Upload UI | | `cinny/src/app/components/upload-card/UploadCardRenderer.tsx` | Upload UI |
| `cinny/src/app/state/upload.ts` | Upload state | | `cinny/src/app/state/upload.ts` | Upload state |
| `cinny/src/app/state/room/roomInputDrafts.ts` | `TUploadItem` | | `cinny/src/app/state/room/roomInputDrafts.ts` | `TUploadItem` |
@@ -25,7 +25,7 @@ msgContent.ts — content type detection
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ---------------------------------------------------- | ------------------------ |
| `cinny/src/app/components/RenderMessageContent.tsx` | Main render entry | | `cinny/src/app/components/RenderMessageContent.tsx` | Main render entry |
| `cinny/src/app/plugins/react-custom-html-parser.tsx` | HTML → React | | `cinny/src/app/plugins/react-custom-html-parser.tsx` | HTML → React |
| `cinny/src/app/plugins/markdown/` | Markdown rules + parsers | | `cinny/src/app/plugins/markdown/` | Markdown rules + parsers |
@@ -23,7 +23,7 @@ Router may mount search under client routes
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------------------- | ------------ |
| `cinny/src/app/features/message-search/MessageSearch.tsx` | Main UI | | `cinny/src/app/features/message-search/MessageSearch.tsx` | Main UI |
| `cinny/src/app/features/message-search/useMessageSearch.ts` | Search logic | | `cinny/src/app/features/message-search/useMessageSearch.ts` | Search logic |
| `cinny/src/app/features/message-search/SearchInput.tsx` | Query field | | `cinny/src/app/features/message-search/SearchInput.tsx` | Query field |
+1 -1
View File
@@ -23,7 +23,7 @@ Plugin folder (index.js + plugin-metadata.json)
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------------- | ------------------------------------- |
| `cinny/src/app/features/settings/plugins/PluginLoader.tsx` | Load/enable/disable plugins | | `cinny/src/app/features/settings/plugins/PluginLoader.tsx` | Load/enable/disable plugins |
| `cinny/src/app/features/settings/plugins/PluginAPI.ts` | Re-exports plugin-manager + app hooks | | `cinny/src/app/features/settings/plugins/PluginAPI.ts` | Re-exports plugin-manager + app hooks |
| `cinny/src/app/features/settings/plugins/Plugins.tsx` | Settings UI (installed + marketplace) | | `cinny/src/app/features/settings/plugins/Plugins.tsx` | Settings UI (installed + marketplace) |
+2 -2
View File
@@ -24,7 +24,7 @@ Bot → state im.paarrot.ui
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------------------------------ | ------------------------------------------------------------------ |
| `cinny/src/types/matrix/room.ts` | `StateEvent.PaarrotUi`, `MessageEvent.PaarrotUiAction`, node types | | `cinny/src/types/matrix/room.ts` | `StateEvent.PaarrotUi`, `MessageEvent.PaarrotUiAction`, node types |
| `cinny/src/app/utils/room.ts` | `getPaarrotUiContent`, `hasRoomAppUi` | | `cinny/src/app/utils/room.ts` | `getPaarrotUiContent`, `hasRoomAppUi` |
| `cinny/src/app/features/room/Room.tsx` | Takeover branch + Show chat / Show app | | `cinny/src/app/features/room/Room.tsx` | Takeover branch + Show chat / Show app |
@@ -35,7 +35,7 @@ Bot → state im.paarrot.ui
## Data model ## Data model
| Event | Kind | Content | | Event | Kind | Content |
|-------|------|---------| | ---------------------- | ------------ | --------------------------------------------------------- |
| `im.paarrot.ui` | state (`""`) | `{ version, title?, css?, root }` | | `im.paarrot.ui` | state (`""`) | `{ version, title?, css?, root }` |
| `im.paarrot.ui.action` | timeline | `{ action, component_id, value?, values?, ui_event_id? }` | | `im.paarrot.ui.action` | timeline | `{ action, component_id, value?, values?, ui_event_id? }` |
+1 -1
View File
@@ -26,7 +26,7 @@ Used by Home.tsx, space sidebars, forum sidebars
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------------- | ----------------- |
| `cinny/src/app/features/room-nav/RoomNavItem.tsx` | Main room row | | `cinny/src/app/features/room-nav/RoomNavItem.tsx` | Main room row |
| `cinny/src/app/features/room-nav/RoomNavCategoryButton.tsx` | Category header | | `cinny/src/app/features/room-nav/RoomNavCategoryButton.tsx` | Category header |
| `cinny/src/app/features/room-nav/UnjoinedSubRoomItem.tsx` | Unjoined sub-room | | `cinny/src/app/features/room-nav/UnjoinedSubRoomItem.tsx` | Unjoined sub-room |
@@ -24,7 +24,7 @@ roomSettings.ts atom — which page open
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------------------- | -------------------- |
| `cinny/src/app/features/room-settings/RoomSettings.tsx` | Settings shell | | `cinny/src/app/features/room-settings/RoomSettings.tsx` | Settings shell |
| `cinny/src/app/features/room-settings/general/` | General tab | | `cinny/src/app/features/room-settings/general/` | General tab |
| `cinny/src/app/features/room-settings/permissions/` | Permissions | | `cinny/src/app/features/room-settings/permissions/` | Permissions |
@@ -28,7 +28,7 @@ Hooks: useVirtualPaginator, useRoomLatestRenderedEvent, useMarkAsRead
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ---------------------------------------------------------------- | ----------------------- |
| `cinny/src/app/features/room/Room.tsx` | Room entry | | `cinny/src/app/features/room/Room.tsx` | Room entry |
| `cinny/src/app/features/room/RoomView.tsx` | Main layout | | `cinny/src/app/features/room/RoomView.tsx` | Main layout |
| `cinny/src/app/features/room/RoomTimeline.tsx` | Timeline | | `cinny/src/app/features/room/RoomTimeline.tsx` | Timeline |
@@ -48,7 +48,7 @@ Hooks: useVirtualPaginator, useRoomLatestRenderedEvent, useMarkAsRead
## Data model ## Data model
| Source | Data | | Source | Data |
|--------|------| | ------------------------------- | ---------------------------------------- |
| Matrix sync | `m.room.message`, edits, reactions, pins | | Matrix sync | `m.room.message`, edits, reactions, pins |
| Room account data | drafts (`roomInputDrafts`) | | Room account data | drafts (`roomInputDrafts`) |
| `im.paarrot.embed_filters` | Personal embed blocks | | `im.paarrot.embed_filters` | Personal embed blocks |
@@ -25,7 +25,7 @@ Router.tsx — route tree + loaders/guards
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------- | -------------------------- |
| `cinny/src/app/pages/Router.tsx` | Full route tree | | `cinny/src/app/pages/Router.tsx` | Full route tree |
| `cinny/src/app/pages/paths.ts` | Path constants | | `cinny/src/app/pages/paths.ts` | Path constants |
| `cinny/src/app/pages/pathUtils.ts` | Path builder utilities | | `cinny/src/app/pages/pathUtils.ts` | Path builder utilities |
@@ -41,7 +41,7 @@ Router.tsx — route tree + loaders/guards
## Data model ## Data model
| Key | Purpose | | Key | Purpose |
|-----|---------| | ---------------------- | ------------------------ |
| `navToActivePath` atom | Per-context last URL | | `navToActivePath` atom | Per-context last URL |
| URL path params | roomId, spaceId, eventId | | URL path params | roomId, spaceId, eventId |
@@ -22,7 +22,7 @@ spaceSettings.ts atom
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------- | -------------- |
| `cinny/src/app/features/space-settings/SpaceSettings.tsx` | Settings shell | | `cinny/src/app/features/space-settings/SpaceSettings.tsx` | Settings shell |
| `cinny/src/app/features/space-settings/general/` | General tab | | `cinny/src/app/features/space-settings/general/` | General tab |
| `cinny/src/app/features/space-settings/permissions/` | Permissions | | `cinny/src/app/features/space-settings/permissions/` | Permissions |
@@ -23,7 +23,7 @@ ClientBindAtoms.tsx binds Matrix events → atom updates
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------- | ---------------------------- |
| `cinny/src/app/state/settings.ts` | User settings atom | | `cinny/src/app/state/settings.ts` | User settings atom |
| `cinny/src/app/state/sessions.ts` | Auth sessions | | `cinny/src/app/state/sessions.ts` | Auth sessions |
| `cinny/src/app/state/room-list/roomList.ts` | `allRoomsAtom`, ordering | | `cinny/src/app/state/room-list/roomList.ts` | `allRoomsAtom`, ordering |
@@ -45,7 +45,7 @@ ClientBindAtoms.tsx binds Matrix events → atom updates
Most state is **local only** (not Matrix). Exceptions: settings that also write account data (notification prefs via separate hooks). Most state is **local only** (not Matrix). Exceptions: settings that also write account data (notification prefs via separate hooks).
| Atom area | Persists? | | Atom area | Persists? |
|-----------|-----------| | --------------- | -------------------------- |
| settings | localStorage | | settings | localStorage |
| room list order | localStorage | | room list order | localStorage |
| drafts | localStorage | | drafts | localStorage |
+1 -1
View File
@@ -22,7 +22,7 @@ Stream Deck button press
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------------------- | -------------------------------- |
| `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/manifest.json` | Plugin manifest | | `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/manifest.json` | Plugin manifest |
| `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/plugin/index.js` | Action implementations | | `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/plugin/index.js` | Action implementations |
| `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/plugin/index.html` | Property inspector UI | | `streamdeck-plugin/com.paarrot.streamdeck.sdPlugin/plugin/index.html` | Property inspector UI |
+2 -2
View File
@@ -26,7 +26,7 @@ Room state: im.paarrot.sub_rooms { children: string[] }
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ------------------------------------------------------------- | ------------------------------------ |
| `cinny/src/app/hooks/useRoomSubRooms.ts` | Hook + `PaarrotSubRoomsContent` type | | `cinny/src/app/hooks/useRoomSubRooms.ts` | Hook + `PaarrotSubRoomsContent` type |
| `cinny/src/types/matrix/room.ts` | `StateEvent.PaarrotSubRooms` | | `cinny/src/types/matrix/room.ts` | `StateEvent.PaarrotSubRooms` |
| `cinny/src/app/pages/client/home/Home.tsx` | Renders nested list | | `cinny/src/app/pages/client/home/Home.tsx` | Renders nested list |
@@ -39,7 +39,7 @@ Room state: im.paarrot.sub_rooms { children: string[] }
## Data model ## Data model
| Event | State key | Content | | Event | State key | Content |
|-------|-----------|---------| | ---------------------- | ------------ | ---------------------------------------------------- |
| `im.paarrot.sub_rooms` | `""` (empty) | `{ children: string[] }` — room IDs in display order | | `im.paarrot.sub_rooms` | `""` (empty) | `{ children: string[] }` — room IDs in display order |
Power levels: treat like other state events; editors need `state_default` or explicit level for `im.paarrot.sub_rooms`. Power levels: treat like other state events; editors need `state_default` or explicit level for `im.paarrot.sub_rooms`.
@@ -25,7 +25,7 @@ vanilla-extract / folds tokens in colors.css.ts
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ---------------------------------------------------- | -------------------------------- |
| `cinny/src/app/pages/ThemeManager.tsx` | Route-level theme | | `cinny/src/app/pages/ThemeManager.tsx` | Route-level theme |
| `cinny/src/app/state/settings.ts` | Settings including theme | | `cinny/src/app/state/settings.ts` | Settings including theme |
| `cinny/src/app/hooks/useTheme.ts` | Theme hook | | `cinny/src/app/hooks/useTheme.ts` | Theme hook |
@@ -38,7 +38,7 @@ vanilla-extract / folds tokens in colors.css.ts
## Data model ## Data model
| Key | Storage | | Key | Storage |
|-----|---------| | -------------- | ------------------------------------------- |
| `settingsAtom` | theme, pageZoom, messageSpacing, emojiStyle | | `settingsAtom` | theme, pageZoom, messageSpacing, emojiStyle |
## Dependencies ## Dependencies
@@ -25,7 +25,7 @@ SettingsPages enum
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | ----------------------------------------------------- | ------------------------- |
| `cinny/src/app/features/settings/Settings.tsx` | Settings modal shell | | `cinny/src/app/features/settings/Settings.tsx` | Settings modal shell |
| `cinny/src/app/features/settings/general/General.tsx` | General prefs | | `cinny/src/app/features/settings/general/General.tsx` | General prefs |
| `cinny/src/app/features/settings/account/Profile.tsx` | Profile + avatar metadata | | `cinny/src/app/features/settings/account/Profile.tsx` | Profile + avatar metadata |
@@ -39,7 +39,7 @@ SettingsPages enum
## Data model ## Data model
| Key | Storage | | Key | Storage |
|-----|---------| | -------------- | --------------------------------------------- |
| `settingsAtom` | localStorage (theme, zoom, emoji style, etc.) | | `settingsAtom` | localStorage (theme, zoom, emoji style, etc.) |
| Profile | Matrix account data + avatar MXC | | Profile | Matrix account data + avatar MXC |
| Push rules | Homeserver account data | | Push rules | Homeserver account data |
+2 -2
View File
@@ -24,7 +24,7 @@ useCallService (CallProvider)
## Key files ## Key files
| Path | Role | | Path | Role |
|------|------| | --------------------------------------------------------------- | ------------------------------------- |
| `cinny/src/app/features/call/useCall.ts` | React context, global CallService ref | | `cinny/src/app/features/call/useCall.ts` | React context, global CallService ref |
| `cinny/src/app/features/call/CallService.ts` | Core call logic | | `cinny/src/app/features/call/CallService.ts` | Core call logic |
| `cinny/src/app/features/call/types.ts` | CallState, ActiveCall, events | | `cinny/src/app/features/call/types.ts` | CallState, ActiveCall, events |
@@ -40,7 +40,7 @@ useCallService (CallProvider)
## Data model ## Data model
| Key | Scope | Notes | | Key | Scope | Notes |
|-----|-------|-------| | -------------------------------- | ---------- | ------------------------- |
| `org.matrix.msc3401.call.member` | Room state | Call membership | | `org.matrix.msc3401.call.member` | Room state | Call membership |
| LiveKit JWT / room | Ephemeral | From homeserver RTC focus | | LiveKit JWT / room | Ephemeral | From homeserver RTC focus |
+139
View File
@@ -0,0 +1,139 @@
import { createRequire } from 'node:module';
import { fixupConfigRules } from '@eslint/compat';
import globals from 'globals';
import js from '@eslint/js';
import airbnb from 'eslint-config-airbnb';
import prettier from 'eslint-config-prettier';
import tsParser from '@typescript-eslint/parser';
import tsPlugin from '@typescript-eslint/eslint-plugin';
import importPlugin from 'eslint-plugin-import';
import jsxAllyPlugin from 'eslint-plugin-jsx-a11y';
import reactPlugin from 'eslint-plugin-react';
import reactHooksPlugin from 'eslint-plugin-react-hooks';
const require = createRequire(import.meta.url);
// Config entries without `files` only match .js/.mjs, so every entry needs the same file set.
const files = ['**/*.js', '**/*.mjs', '**/*.cjs', '**/*.ts', '**/*.tsx'];
// eslint-config-airbnb 19 is legacy-only: `extends` are paths to rule modules and flat config
// rejects `extends`/`env`/`parserOptions`, so take their rules and set the env here instead.
const airbnbRules = (config) =>
(config.extends || []).flatMap((p) => airbnbRules(require(p))).concat(config);
// Plugins are registered once (redefining a plugin is an error) and fixed up so the legacy
// rules that call context.getFilename still work.
export default [
...fixupConfigRules([
{
files,
plugins: {
react: reactPlugin,
'react-hooks': reactHooksPlugin,
'@typescript-eslint': tsPlugin,
import: importPlugin,
'jsx-a11y': jsxAllyPlugin,
},
languageOptions: {
parser: tsParser,
ecmaVersion: 'latest',
sourceType: 'module',
globals: { ...globals.browser, ...globals.es2021, JSX: 'readonly' },
},
},
]),
...[
js.configs.recommended,
reactPlugin.configs.flat.recommended,
reactHooksPlugin.configs.flat.recommended,
tsPlugin.configs['flat/eslint-recommended'],
tsPlugin.configs['flat/recommended'],
...airbnbRules(airbnb),
prettier,
{
rules: {
'linebreak-style': 0,
'no-underscore-dangle': 0,
'no-shadow': 'off',
'no-console': 'off',
// The build uses the automatic JSX runtime, so this rule asks for imports the code never needs.
'react/react-in-jsx-scope': 'off',
'import/prefer-default-export': 'off',
'import/extensions': 'off',
'import/no-unresolved': 'off',
'import/no-extraneous-dependencies': [
'error',
{
devDependencies: true,
},
],
'react/no-unstable-nested-components': ['error', { allowAsProps: true }],
'react/jsx-filename-extension': [
'error',
{
extensions: ['.tsx', '.jsx'],
},
],
'react/require-default-props': 'off',
'react/jsx-props-no-spreading': 'off',
'react-hooks/rules-of-hooks': 'error',
// The 9 findings were restructured to a reactive source where one exists. The 3 left have
// none: a 1s poll counter in useTheme.ts and a mount-only effect in RoomTimeline.tsx.
'react-hooks/exhaustive-deps': 'off',
// The build does not run React Compiler, so these rules report advice about a compiler
// that never runs. Keep the two rules above, which catch real bugs.
'react-hooks/set-state-in-effect': 'off',
'react-hooks/set-state-in-render': 'off',
'react-hooks/refs': 'off',
'react-hooks/immutability': 'off',
'react-hooks/incompatible-library': 'off',
'react-hooks/preserve-manual-memoization': 'off',
'react-hooks/purity': 'off',
'react-hooks/use-memo': 'off',
// Genuine shift and mask work in discordCollectibles.ts and cryptE2ERoomKeys.js.
'no-bitwise': 'off',
// 60 of the 61 findings are property mutations on objects the caller passes in, and the
// callers depend on the mutation. Reassigning the parameter itself is still a finding.
'no-param-reassign': ['error', { props: false }],
// The sequential awaits here are deliberate: the rate-limit delays in Permissions.tsx and
// the endpoint poll loop in backgroundSync.ts break if the awaits are parallelised.
'no-await-in-loop': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/no-shadow': 'error',
// The 14 findings left are vendored plugin API types that declare any, event keys chosen at
// runtime, and msgContent builders that cannot produce RoomMessageEventContent.
'@typescript-eslint/no-explicit-any': 'off',
// Matrix video events carry no caption field, so there is no caption source to read.
'jsx-a11y/media-has-caption': 'off',
// Prism tokens are not unique within a line, so the array index is the only key available.
'react/no-array-index-key': 'off',
},
},
].flatMap((config) =>
(Array.isArray(config) ? config : [config]).map((config) => ({
files,
rules: config.rules || {},
...(config.settings ? { settings: config.settings } : {}),
})),
),
// Type-only references (React.DragEvent, PermissionState) are not runtime globals, so no-undef
// has to be off for the TS files too, not just *.ts. The base no-unused-vars also double-fires on
// type-signature params and enum members, which @typescript-eslint/no-unused-vars handles instead.
{
files: ['**/*.ts', '**/*.tsx'],
rules: { 'no-undef': 'off', 'no-unused-vars': 'off' },
},
];
+7 -7
View File
@@ -1,10 +1,13 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<base href="./" /> <base href="./" />
<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, maximum-scale=1.0, viewport-fit=cover" /> <meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, viewport-fit=cover"
/>
<title>Paarrot</title> <title>Paarrot</title>
<meta name="name" content="Paarrot" /> <meta name="name" content="Paarrot" />
<meta name="author" content="Ajay Bura" /> <meta name="author" content="Ajay Bura" />
@@ -12,10 +15,7 @@
name="description" name="description"
content="A Matrix client where you can enjoy the conversation using simple, elegant and secure interface protected by e2ee with the power of open source." content="A Matrix client where you can enjoy the conversation using simple, elegant and secure interface protected by e2ee with the power of open source."
/> />
<meta <meta name="keywords" content="paarrot, matrix, matrix client, matrix.org, element" />
name="keywords"
content="paarrot, matrix, matrix client, matrix.org, element"
/>
<meta property="og:title" content="Paarrot" /> <meta property="og:title" content="Paarrot" />
<meta property="og:url" content="https://github.com/Paarrot/Paarrot-Desktop" /> <meta property="og:url" content="https://github.com/Paarrot/Paarrot-Desktop" />
@@ -90,7 +90,7 @@
href="./public/res/apple/apple-touch-icon-180x180.png" href="./public/res/apple/apple-touch-icon-180x180.png"
/> />
</head> </head>
<body id="appBody" style="background-color: #262626;"> <body id="appBody" style="background-color: #262626">
<script> <script>
window.global ||= window; window.global ||= window;
</script> </script>
+58 -70
View File
@@ -20,13 +20,6 @@
"@tanstack/react-query-devtools": "5.101.2", "@tanstack/react-query-devtools": "5.101.2",
"@tanstack/react-virtual": "3.14.5", "@tanstack/react-virtual": "3.14.5",
"@tauri-apps/api": "2.11.1", "@tauri-apps/api": "2.11.1",
"@tauri-apps/plugin-dialog": "2.7.1",
"@tauri-apps/plugin-fs": "2.5.1",
"@tauri-apps/plugin-http": "2.5.9",
"@tauri-apps/plugin-notification": "2.3.3",
"@tauri-apps/plugin-opener": "2",
"@tauri-apps/plugin-process": "2.3.1",
"@tauri-apps/plugin-updater": "2.10.1",
"@types/pako": "2.0.4", "@types/pako": "2.0.4",
"@vanilla-extract/css": "1.21.1", "@vanilla-extract/css": "1.21.1",
"@vanilla-extract/recipes": "0.5.7", "@vanilla-extract/recipes": "0.5.7",
@@ -85,6 +78,8 @@
}, },
"devDependencies": { "devDependencies": {
"@esbuild-plugins/node-globals-polyfill": "0.2.3", "@esbuild-plugins/node-globals-polyfill": "0.2.3",
"@eslint/compat": "2.1.1",
"@eslint/js": "10.0.1",
"@monaco-editor/react": "4.7.0", "@monaco-editor/react": "4.7.0",
"@rollup/plugin-inject": "5.0.5", "@rollup/plugin-inject": "5.0.5",
"@rollup/plugin-wasm": "6.2.2", "@rollup/plugin-wasm": "6.2.2",
@@ -109,6 +104,7 @@
"eslint-plugin-jsx-a11y": "6.10.2", "eslint-plugin-jsx-a11y": "6.10.2",
"eslint-plugin-react": "7.37.5", "eslint-plugin-react": "7.37.5",
"eslint-plugin-react-hooks": "7.1.1", "eslint-plugin-react-hooks": "7.1.1",
"globals": "17.13.0",
"monaco-editor": "0.52.2", "monaco-editor": "0.52.2",
"prettier": "3.9.4", "prettier": "3.9.4",
"typescript": "6.0.3", "typescript": "6.0.3",
@@ -2260,6 +2256,27 @@
"node": "^12.0.0 || ^14.0.0 || >=16.0.0" "node": "^12.0.0 || ^14.0.0 || >=16.0.0"
} }
}, },
"node_modules/@eslint/compat": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@eslint/compat/-/compat-2.1.1.tgz",
"integrity": "sha512-rMcy8GSrwNzcISX/BlTDY/GLB4eCopEuy9woIls3To+15OLxykZrxxq+WUcylCPCQ6F4MujjBM1DX5V1aqI3Vw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@eslint/core": "^1.2.1"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24"
},
"peerDependencies": {
"eslint": "^8.40 || 9 || 10"
},
"peerDependenciesMeta": {
"eslint": {
"optional": true
}
}
},
"node_modules/@eslint/config-array": { "node_modules/@eslint/config-array": {
"version": "0.23.5", "version": "0.23.5",
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz",
@@ -2340,6 +2357,27 @@
"node": "^20.19.0 || ^22.13.0 || >=24" "node": "^20.19.0 || ^22.13.0 || >=24"
} }
}, },
"node_modules/@eslint/js": {
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz",
"integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24"
},
"funding": {
"url": "https://eslint.org/donate"
},
"peerDependencies": {
"eslint": "^10.0.0"
},
"peerDependenciesMeta": {
"eslint": {
"optional": true
}
}
},
"node_modules/@eslint/object-schema": { "node_modules/@eslint/object-schema": {
"version": "3.0.5", "version": "3.0.5",
"resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz",
@@ -4035,69 +4073,6 @@
"url": "https://opencollective.com/tauri" "url": "https://opencollective.com/tauri"
} }
}, },
"node_modules/@tauri-apps/plugin-dialog": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-dialog/-/plugin-dialog-2.7.1.tgz",
"integrity": "sha512-OK1UBXYt+ojcmxMktzzuyonYIFta8CmAASpX+CA+DTGK24KlHjhYI6x2iOJ/TjZF4N7/ACK1oFmEOjIY9IhzOQ==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.11.0"
}
},
"node_modules/@tauri-apps/plugin-fs": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-fs/-/plugin-fs-2.5.1.tgz",
"integrity": "sha512-9Lz+Jopp6QyeEWhlpkMx4R/+P9HgR+AVAI4vOZhlT8Xaymtz8iVI/Ov984/XTqgJz/5gz5NretqPB/XEMS3NhQ==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.11.0"
}
},
"node_modules/@tauri-apps/plugin-http": {
"version": "2.5.9",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-http/-/plugin-http-2.5.9.tgz",
"integrity": "sha512-lCiY0+vs4HvIUSvZrBs8TC3TiCB0MOPRmiUjTq4prW7SlcJE2jdLeT6KBsJrT9Tlplufl7W1pY6SFAO3gCWxDA==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.11.0"
}
},
"node_modules/@tauri-apps/plugin-notification": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-notification/-/plugin-notification-2.3.3.tgz",
"integrity": "sha512-Zw+ZH18RJb41G4NrfHgIuofJiymusqN+q8fGUIIV7vyCH+5sSn5coqRv/MWB9qETsUs97vmU045q7OyseCV3Qg==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.8.0"
}
},
"node_modules/@tauri-apps/plugin-opener": {
"version": "2.5.3",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-opener/-/plugin-opener-2.5.3.tgz",
"integrity": "sha512-CCcUltXMOfUEArbf3db3kCE7Ggy1ExBEBl51Ko2ODJ6GDYHRp1nSNlQm5uNCFY5k7/ufaK5Ib3Du/Zir19IYQQ==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.8.0"
}
},
"node_modules/@tauri-apps/plugin-process": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-process/-/plugin-process-2.3.1.tgz",
"integrity": "sha512-nCa4fGVaDL/B9ai03VyPOjfAHRHSBz5v6F/ObsB73r/dA3MHHhZtldaDMIc0V/pnUw9ehzr2iEG+XkSEyC0JJA==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.8.0"
}
},
"node_modules/@tauri-apps/plugin-updater": {
"version": "2.10.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-updater/-/plugin-updater-2.10.1.tgz",
"integrity": "sha512-NFYMg+tWOZPJdzE/PpFj2qfqwAWwNS3kXrb1tm1gnBJ9mYzZ4WDRrwy8udzWoAnfGCHLuePNLY1WVCNHnh3eRA==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.10.1"
}
},
"node_modules/@trickfilm400/rollup-plugin-off-main-thread": { "node_modules/@trickfilm400/rollup-plugin-off-main-thread": {
"version": "3.0.0-pre1", "version": "3.0.0-pre1",
"resolved": "https://registry.npmjs.org/@trickfilm400/rollup-plugin-off-main-thread/-/rollup-plugin-off-main-thread-3.0.0-pre1.tgz", "resolved": "https://registry.npmjs.org/@trickfilm400/rollup-plugin-off-main-thread/-/rollup-plugin-off-main-thread-3.0.0-pre1.tgz",
@@ -7332,6 +7307,19 @@
"url": "https://github.com/sponsors/isaacs" "url": "https://github.com/sponsors/isaacs"
} }
}, },
"node_modules/globals": {
"version": "17.13.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-17.13.0.tgz",
"integrity": "sha512-RwMTC61u7hrG3ZJMkZQOK4JLJrKS8QtoTii63EmWvFXHqycY9FObBJQCbsLxSO8kjKhWE5kV1GC+Vb1g3RI0Zg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/globalthis": { "node_modules/globalthis": {
"version": "1.0.4", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",
+4 -9
View File
@@ -14,8 +14,7 @@
"check:eslint": "eslint src/*", "check:eslint": "eslint src/*",
"check:prettier": "prettier --check .", "check:prettier": "prettier --check .",
"fix:prettier": "prettier --write .", "fix:prettier": "prettier --write .",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit"
"playground": "vite"
}, },
"keywords": [], "keywords": [],
"author": "Ajay Bura", "author": "Ajay Bura",
@@ -32,13 +31,6 @@
"@tanstack/react-query-devtools": "5.101.2", "@tanstack/react-query-devtools": "5.101.2",
"@tanstack/react-virtual": "3.14.5", "@tanstack/react-virtual": "3.14.5",
"@tauri-apps/api": "2.11.1", "@tauri-apps/api": "2.11.1",
"@tauri-apps/plugin-dialog": "2.7.1",
"@tauri-apps/plugin-fs": "2.5.1",
"@tauri-apps/plugin-http": "2.5.9",
"@tauri-apps/plugin-notification": "2.3.3",
"@tauri-apps/plugin-opener": "2",
"@tauri-apps/plugin-process": "2.3.1",
"@tauri-apps/plugin-updater": "2.10.1",
"@types/pako": "2.0.4", "@types/pako": "2.0.4",
"@vanilla-extract/css": "1.21.1", "@vanilla-extract/css": "1.21.1",
"@vanilla-extract/recipes": "0.5.7", "@vanilla-extract/recipes": "0.5.7",
@@ -97,6 +89,8 @@
}, },
"devDependencies": { "devDependencies": {
"@esbuild-plugins/node-globals-polyfill": "0.2.3", "@esbuild-plugins/node-globals-polyfill": "0.2.3",
"@eslint/compat": "2.1.1",
"@eslint/js": "10.0.1",
"@monaco-editor/react": "4.7.0", "@monaco-editor/react": "4.7.0",
"@rollup/plugin-inject": "5.0.5", "@rollup/plugin-inject": "5.0.5",
"@rollup/plugin-wasm": "6.2.2", "@rollup/plugin-wasm": "6.2.2",
@@ -121,6 +115,7 @@
"eslint-plugin-jsx-a11y": "6.10.2", "eslint-plugin-jsx-a11y": "6.10.2",
"eslint-plugin-react": "7.37.5", "eslint-plugin-react": "7.37.5",
"eslint-plugin-react-hooks": "7.1.1", "eslint-plugin-react-hooks": "7.1.1",
"globals": "17.13.0",
"monaco-editor": "0.52.2", "monaco-editor": "0.52.2",
"prettier": "3.9.4", "prettier": "3.9.4",
"typescript": "6.0.3", "typescript": "6.0.3",
-149
View File
@@ -1,149 +0,0 @@
import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import type { Plugin, ViteDevServer } from 'vite';
export type LiveTsxApi = {
getSource: () => string;
setSource: (source: string) => void;
};
const ALLOWED_PREFIXES = ['src/app/components/', 'src/app/features/'];
function resolveAppSourceFile(projectRoot: string, relPath: string): string | null {
const normalized = relPath.replace(/\\/g, '/').replace(/^\/+/, '');
if (normalized.includes('..') || path.isAbsolute(normalized)) return null;
if (!ALLOWED_PREFIXES.some((p) => normalized.startsWith(p))) return null;
if (!/\.(tsx|ts)$/.test(normalized)) return null;
const abs = path.resolve(projectRoot, normalized);
const root = path.resolve(projectRoot);
if (!abs.startsWith(root + path.sep) && abs !== root) return null;
return abs;
}
function readBody(req: NodeJS.ReadableStream): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
req.on('data', (c) => chunks.push(c));
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function bumpLivePreview(server: ViteDevServer | undefined) {
if (!server) return;
server.ws.send({
type: 'custom',
event: 'playground:live-updated',
data: { revision: Date.now() },
});
}
export function liveTsxPlugin(projectRoot: string, initialSource: string): Plugin {
const liveFile = path.resolve(projectRoot, '.cache/playground-live.tsx');
fs.mkdirSync(path.dirname(liveFile), { recursive: true });
fs.writeFileSync(liveFile, initialSource, 'utf8');
let source = initialSource;
let server: ViteDevServer | undefined;
const api: LiveTsxApi = {
getSource: () => source,
setSource: (next) => {
source = next;
fs.writeFileSync(liveFile, next, 'utf8');
if (!server) return;
for (const m of server.moduleGraph.urlToModuleMap.values()) {
if (m.file === liveFile) server.moduleGraph.invalidateModule(m);
}
const byId = server.moduleGraph.getModuleById(liveFile);
if (byId) server.moduleGraph.invalidateModule(byId);
bumpLivePreview(server);
},
};
return {
name: 'playground-live-tsx',
configureServer(devServer) {
server = devServer;
(devServer as ViteDevServer & { playgroundLive?: LiveTsxApi }).playgroundLive = api;
devServer.middlewares.use('/__playground/live', (req, res, next) => {
if (req.method === 'GET') {
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end(source);
return;
}
if (req.method === 'POST') {
void readBody(req).then((body) => {
api.setSource(body);
res.statusCode = 204;
res.end();
});
return;
}
next();
});
// Read/write real Cinny component sources (strings, markup, etc.).
devServer.middlewares.use('/__playground/source', (req, res, next) => {
const url = new URL(req.url ?? '', 'http://playground.local');
const rel = url.searchParams.get('path') ?? '';
const abs = resolveAppSourceFile(projectRoot, rel);
if (!abs) {
res.statusCode = 400;
res.end('Invalid or disallowed path');
return;
}
if (req.method === 'GET') {
if (!fs.existsSync(abs)) {
res.statusCode = 404;
res.end('Not found');
return;
}
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end(fs.readFileSync(abs, 'utf8'));
return;
}
if (req.method === 'POST') {
void readBody(req).then((body) => {
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, body, 'utf8');
const mod =
server?.moduleGraph.getModuleById(abs) ??
[...(server?.moduleGraph.urlToModuleMap.values() ?? [])].find((m) => m.file === abs);
if (mod && server) server.moduleGraph.invalidateModule(mod);
bumpLivePreview(server);
res.statusCode = 204;
res.end();
});
return;
}
next();
});
},
resolveId(id) {
const clean = id.split('?')[0];
if (
clean === '/@playground/live.tsx' ||
clean === 'virtual:playground-live' ||
clean.endsWith('/.cache/playground-live.tsx')
) {
return liveFile;
}
return undefined;
},
};
}
export function readDefaultLiveSource(projectRoot: string): string {
return fs.readFileSync(path.join(projectRoot, 'src/playground/defaultLive.tsx'), 'utf8');
}
export function projectRootDir(): string {
return path.dirname(fileURLToPath(import.meta.url));
}
-12
View File
@@ -1,12 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Component Playground</title>
</head>
<body style="margin:0;background:#0f1115;color:#e8eaed">
<div id="root"></div>
<script type="module" src="./src/playground/main.tsx?v=react-dedupe-1"></script>
</body>
</html>
+857 -1
View File
File diff suppressed because one or more lines are too long
-1
View File
@@ -12,7 +12,6 @@ summary: Add Discord-style profile effects, nameplates, and avatar decorations t
- The catalog now comes from a public git, and no Discord token is required in Paarrot for the cosmetics. - The catalog now comes from a public git, and no Discord token is required in Paarrot for the cosmetics.
- Profile-effect previews play their intro and loop animations, with a mini profile preview for each effect. - Profile-effect previews play their intro and loop animations, with a mini profile preview for each effect.
![Discord Cosmetics 1](./images/discordcosmetics1.png) ![Discord Cosmetics 2](./images/discordcosmetics2.png) ![Discord Cosmetics 1](./images/discordcosmetics1.png) ![Discord Cosmetics 2](./images/discordcosmetics2.png)
## Profile presentation ## Profile presentation
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
# Files one open Gitea issue per rule key, deduped by the marker line in the issue body.
# Never exits non-zero: findings are reported, not enforced.
set -u
API_BASE="${API_BASE:?API_BASE is required}"
REPO="${REPO:?REPO is required}"
TOKEN="${TOKEN:?TOKEN is required}"
SHA="${SHA:-}"
BASE="${WEB_BASE:-${API_BASE%/api/v1}}"
LABEL="ci-checks"
SHOW="${SHOW:-50}"
cd "$(dirname "$0")/.."
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
FINDINGS="$WORK/findings.tsv"
: > "$FINDINGS"
# key<TAB>violation, one line per finding.
npx eslint src --format json > "$WORK/eslint.json" || true
jq -r --arg root "$PWD" '.[] | .filePath as $f | .messages[] | select(.ruleId) | "eslint/" + .ruleId + "\t" + (($f | ltrimstr($root + "/")) + ":" + (.line | tostring))' "$WORK/eslint.json" >> "$FINDINGS"
npx prettier --check . > "$WORK/prettier.log" 2>&1 || true
# Prettier forces colour in CI, so strip the ANSI codes before matching.
sed -E 's/\x1b\[[0-9;]*m//g' "$WORK/prettier.log" | sed -nE 's/^\[warn\] (.*)$/prettier\t\1/p' >> "$FINDINGS"
npx tsc --noEmit > "$WORK/tsc.log" 2>&1 || true
sed -E 's/\x1b\[[0-9;]*m//g' "$WORK/tsc.log" | sed -nE 's/^(.*)\(([0-9]+),([0-9]+)\): error (TS[0-9]+):.*/tsc\/\4\t\1(\2,\3)/p' >> "$FINDINGS"
api() { # api METHOD PATH [JSON] -> response body on stdout, non-zero on HTTP failure
local method=$1 path=$2 data=${3-} code
code=$(curl -sS -o "$WORK/resp" -w '%{http_code}' -X "$method" \
-H "Authorization: token $TOKEN" -H 'Content-Type: application/json' \
${data:+-d "$data"} "$API_BASE/repos/$REPO$path") || return 1
case "$code" in
200 | 201) cat "$WORK/resp" ;;
*) echo "HTTP $code $method $path: $(cat "$WORK/resp")" >&2; return 1 ;;
esac
}
body() { # body KEY HASH VIOLATIONS_FILE
printf '<!-- ci-check: %s -->\n<!-- ci-check-hash: %s -->\n\n`%s`: %d violations.\n\n```text\n' \
"$1" "$2" "$1" "$(wc -l < "$3")"
head -n "$SHOW" "$3"
printf '```\n'
}
LABEL_ID=$(api GET "/labels?limit=100" | jq -r --arg n "$LABEL" '[.[] | select(.name == $n) | .id] | first // empty')
if [ -z "$LABEL_ID" ]; then
LABEL_ID=$(api POST "/labels" "$(jq -n --arg n "$LABEL" '{name: $n, color: "006060"}')" | jq -r '.id')
fi
# Gitea caps per_page at 50, so paging is required or dedupe misses issues past the first page.
# Accumulate as JSONL: passing the accumulated set as a jq program argument overflows argv.
OPEN="$WORK/open.jsonl"
: > "$OPEN"
for page in 1 2 3 4 5 6 7 8; do
api GET "/issues?state=open&limit=50&page=$page" | jq -c --arg l "$LABEL" '[.[] | select((.labels // []) | any(.name == $l))]' > "$WORK/page.json"
n=$(jq -r 'length' "$WORK/page.json")
[ -z "$n" ] && break
jq -c '.[]' "$WORK/page.json" >> "$OPEN"
[ "$n" -lt 50 ] && break
done
for key in $(cut -f1 "$FINDINGS" | sort -u); do
vf="$WORK/violations.tsv"
awk -F'\t' -v k="$key" '$1 == k' "$FINDINGS" | sort > "$vf"
hash=$(sha256sum < "$vf" | cut -d' ' -f1)
row=$(jq -c --arg k "$key" 'select((.body // "") | contains("<!-- ci-check: " + $k + " -->"))' "$OPEN" | head -1)
if [ -z "$row" ]; then
api POST "/issues" "$(jq -n --arg t "ci-check: $key" --arg b "$(body "$key" "$hash" "$vf")" --argjson l "$LABEL_ID" '{title: $t, body: $b, labels: [$l]}')" > /dev/null
elif ! echo "$row" | jq -e --arg h "$hash" '(.body // "") | contains("<!-- ci-check-hash: " + $h + " -->")' > /dev/null; then
api PATCH "/issues/$(jq -r '.number' <<< "$row")" "$(jq -n --arg b "$(body "$key" "$hash" "$vf")" '{body: $b}')" > /dev/null
fi
done
jq -r '[((.body // "") | capture("<!-- ci-check: (?<k>[^ ]+) -->").k), .number] | @tsv' "$OPEN" > "$WORK/keys.tsv"
while IFS=$'\t' read -r key number; do
if ! grep -qF -- "$key"$'\t' "$FINDINGS"; then
if [ -n "$SHA" ]; then
api POST "/issues/$number/comments" "$(jq -n --arg b "Fixed in [$(printf '%s' "$SHA" | cut -c1-7)]($BASE/$REPO/commit/$SHA)." '{body: $b}')" > /dev/null
fi
api PATCH "/issues/$number" '{"state": "closed"}' > /dev/null
fi
done < "$WORK/keys.tsv"
exit 0
+1 -3
View File
@@ -106,9 +106,7 @@ function main() {
} }
fs.writeFileSync(MANIFEST_PATH, json, 'utf8'); fs.writeFileSync(MANIFEST_PATH, json, 'utf8');
console.log( console.log(`[update-manifest] wrote manifest.json (${manifest.older.length} older version(s))`);
`[update-manifest] wrote manifest.json (${manifest.older.length} older version(s))`
);
} }
main(); main();
+16 -4
View File
@@ -1,7 +1,19 @@
import React, { FormEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import React, { FormEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Text, IconButton, Input, Button, TextArea, color, Spinner, Chip, Scroll, config } from 'folds'; import {
import { Icon, Icons } from './icons'; Box,
Text,
IconButton,
Input,
Button,
TextArea,
color,
Spinner,
Chip,
Scroll,
config,
} from 'folds';
import { MatrixError } from 'matrix-js-sdk'; import { MatrixError } from 'matrix-js-sdk';
import { Icon, Icons } from './icons';
import { Cursor } from '../plugins/text-area'; import { Cursor } from '../plugins/text-area';
import { syntaxErrorPosition } from '../utils/dom'; import { syntaxErrorPosition } from '../utils/dom';
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
@@ -41,7 +53,7 @@ function AccountDataEdit({
const { handleKeyDown, operations, getTarget } = useTextAreaCodeEditor( const { handleKeyDown, operations, getTarget } = useTextAreaCodeEditor(
textAreaRef, textAreaRef,
EDITOR_INTENT_SPACE_COUNT EDITOR_INTENT_SPACE_COUNT,
); );
const [submitState, submit] = useAsyncCallback<void, MatrixError, [string, object]>(submitChange); const [submitState, submit] = useAsyncCallback<void, MatrixError, [string, object]>(submitChange);
@@ -263,7 +275,7 @@ export function AccountDataEditor({
const contentJSONStr = useMemo( const contentJSONStr = useMemo(
() => JSON.stringify(data.content, null, EDITOR_INTENT_SPACE_COUNT), () => JSON.stringify(data.content, null, EDITOR_INTENT_SPACE_COUNT),
[data.content] [data.content],
); );
return ( return (
+6 -6
View File
@@ -24,7 +24,7 @@ export function AngleSelector({
onChange, onChange,
size = 80, size = 80,
disabled = false, disabled = false,
}: AngleSelectorProps): JSX.Element { }: AngleSelectorProps): React.JSX.Element {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const [isDragging, setIsDragging] = useState(false); const [isDragging, setIsDragging] = useState(false);
@@ -52,7 +52,7 @@ export function AngleSelector({
return Math.round(angle); return Math.round(angle);
}, },
[value] [value],
); );
/** /**
@@ -67,7 +67,7 @@ export function AngleSelector({
const newAngle = calculateAngle(e.clientX, e.clientY); const newAngle = calculateAngle(e.clientX, e.clientY);
onChange(newAngle); onChange(newAngle);
}, },
[disabled, calculateAngle, onChange] [disabled, calculateAngle, onChange],
); );
/** /**
@@ -79,7 +79,7 @@ export function AngleSelector({
const newAngle = calculateAngle(e.clientX, e.clientY); const newAngle = calculateAngle(e.clientX, e.clientY);
onChange(newAngle); onChange(newAngle);
}, },
[isDragging, disabled, calculateAngle, onChange] [isDragging, disabled, calculateAngle, onChange],
); );
/** /**
@@ -90,7 +90,7 @@ export function AngleSelector({
}, []); }, []);
// Calculate line endpoint position // Calculate line endpoint position
const lineLength = (size / 2) - 8; const lineLength = size / 2 - 8;
const radians = ((value - 90) * Math.PI) / 180; const radians = ((value - 90) * Math.PI) / 180;
const lineX = Math.cos(radians) * lineLength; const lineX = Math.cos(radians) * lineLength;
const lineY = Math.sin(radians) * lineLength; const lineY = Math.sin(radians) * lineLength;
@@ -160,7 +160,7 @@ export function AngleSelector({
{/* Cardinal direction markers */} {/* Cardinal direction markers */}
{[0, 90, 180, 270].map((deg) => { {[0, 90, 180, 270].map((deg) => {
const markerRadians = ((deg - 90) * Math.PI) / 180; const markerRadians = ((deg - 90) * Math.PI) / 180;
const markerDist = (size / 2) - 3; const markerDist = size / 2 - 3;
const markerX = Math.cos(markerRadians) * markerDist; const markerX = Math.cos(markerRadians) * markerDist;
const markerY = Math.sin(markerRadians) * markerDist; const markerY = Math.sin(markerRadians) * markerDist;
return ( return (
+1 -1
View File
@@ -42,7 +42,7 @@ export function AnimatedOutlet() {
const location = useLocation(); const location = useLocation();
const transitionKey = useMemo( const transitionKey = useMemo(
() => getOutletTransitionKey(location.pathname), () => getOutletTransitionKey(location.pathname),
[location.pathname] [location.pathname],
); );
return ( return (
+1 -1
View File
@@ -45,7 +45,7 @@ export function AuthFlowsLoader({ fallback, error, children }: AuthFlowsLoaderPr
}; };
return authFlows; return authFlows;
}, [mx]) }, [mx]),
); );
useEffect(() => { useEffect(() => {
+17 -3
View File
@@ -1,9 +1,23 @@
import React, { MouseEventHandler, useCallback, useState } from 'react'; import React, { MouseEventHandler, useCallback, useState } from 'react';
import { useAtom } from 'jotai'; import { useAtom } from 'jotai';
import { CryptoApi, KeyBackupInfo } from 'matrix-js-sdk/lib/crypto-api'; import { CryptoApi, KeyBackupInfo } from 'matrix-js-sdk/lib/crypto-api';
import { Badge, Box, Button, color, config, IconButton, Menu, percent, PopOut, ProgressBar, RectCords, Spinner, Text } from 'folds'; import {
import { Icon, Icons } from './icons'; Badge,
Box,
Button,
color,
config,
IconButton,
Menu,
percent,
PopOut,
ProgressBar,
RectCords,
Spinner,
Text,
} from 'folds';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from './icons';
import { BackupProgressStatus, backupRestoreProgressAtom } from '../state/backupRestore'; import { BackupProgressStatus, backupRestoreProgressAtom } from '../state/backupRestore';
import { InfoCard } from './info-card'; import { InfoCard } from './info-card';
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback'; import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
@@ -142,7 +156,7 @@ export function BackupRestoreTile({ crypto }: BackupRestoreTileProps) {
setRestoreProgress(progress); setRestoreProgress(progress);
}, },
}); });
}, [crypto, setRestoreProgress]) }, [crypto, setRestoreProgress]),
); );
const handleRestore = () => { const handleRestore = () => {
+3 -3
View File
@@ -6,8 +6,8 @@ type ConfirmPasswordMatchProps = {
children: ( children: (
match: boolean, match: boolean,
doMatch: () => void, doMatch: () => void,
passRef: RefObject<HTMLInputElement>, passRef: RefObject<HTMLInputElement | null>,
confPassRef: RefObject<HTMLInputElement> confPassRef: RefObject<HTMLInputElement | null>,
) => ReactNode; ) => ReactNode;
}; };
export function ConfirmPasswordMatch({ initialValue, children }: ConfirmPasswordMatchProps) { export function ConfirmPasswordMatch({ initialValue, children }: ConfirmPasswordMatchProps) {
@@ -28,7 +28,7 @@ export function ConfirmPasswordMatch({ initialValue, children }: ConfirmPassword
{ {
wait: 500, wait: 500,
immediate: false, immediate: false,
} },
); );
return children(match, doMatch, passRef, confPassRef); return children(match, doMatch, passRef, confPassRef);
+14 -3
View File
@@ -6,9 +6,21 @@ import {
} from 'matrix-js-sdk/lib/crypto-api'; } from 'matrix-js-sdk/lib/crypto-api';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react'; import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import { VerificationMethod } from 'matrix-js-sdk/lib/types'; import { VerificationMethod } from 'matrix-js-sdk/lib/types';
import { Box, Button, config, Dialog, Header, IconButton, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text } from 'folds'; import {
import { Icon, Icons } from './icons'; Box,
Button,
config,
Dialog,
Header,
IconButton,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
} from 'folds';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from './icons';
import { import {
useVerificationRequestPhase, useVerificationRequestPhase,
useVerificationRequestReceived, useVerificationRequestReceived,
@@ -124,7 +136,6 @@ function CompareEmoji({ sasData }: { sasData: ShowSasCallbacks }) {
> >
{sasData.sas.emoji?.map(([emoji, name], index) => ( {sasData.sas.emoji?.map(([emoji, name], index) => (
<Box <Box
// eslint-disable-next-line react/no-array-index-key
key={`${emoji}${name}${index}`} key={`${emoji}${name}${index}`}
direction="Column" direction="Column"
gap="100" gap="100"
+10 -10
View File
@@ -1,9 +1,9 @@
import React, { FormEventHandler, forwardRef, useCallback, useState } from 'react'; import React, { FormEventHandler, forwardRef, useCallback, useState } from 'react';
import { Dialog, Header, Box, Text, IconButton, config, Button, Chip, color, Spinner } from 'folds'; import { Dialog, Header, Box, Text, IconButton, config, Button, Chip, color, Spinner } from 'folds';
import { Icon, Icons } from './icons';
import FileSaver from 'file-saver'; import FileSaver from 'file-saver';
import to from 'await-to-js'; import to from 'await-to-js';
import { AuthDict, IAuthData, MatrixError, UIAuthCallback } from 'matrix-js-sdk'; import { AuthDict, IAuthData, MatrixError, UIAuthCallback } from 'matrix-js-sdk';
import { Icon, Icons } from './icons';
import { PasswordInput } from './password-input'; import { PasswordInput } from './password-input';
import { ContainerColor } from '../styles/ContainerColor.css'; import { ContainerColor } from '../styles/ContainerColor.css';
import { copyToClipboard } from '../utils/dom'; import { copyToClipboard } from '../utils/dom';
@@ -15,7 +15,7 @@ import { useAlive } from '../hooks/useAlive';
import { UseStateProvider } from './UseStateProvider'; import { UseStateProvider } from './UseStateProvider';
type UIACallback<T> = ( type UIACallback<T> = (
authDict: AuthDict | null authDict: AuthDict | null,
) => Promise<[IAuthData, undefined] | [undefined, T]>; ) => Promise<[IAuthData, undefined] | [undefined, T]>;
type PerformAction<T> = (authDict: AuthDict | null) => Promise<T>; type PerformAction<T> = (authDict: AuthDict | null) => Promise<T>;
@@ -30,7 +30,7 @@ function makeUIAAction<T>(
authData: IAuthData, authData: IAuthData,
performAction: PerformAction<T>, performAction: PerformAction<T>,
resolve: (data: T) => void, resolve: (data: T) => void,
reject: (error?: any) => void reject: (error?: unknown) => void,
): UIAAction<T> { ): UIAAction<T> {
const action: UIAAction<T> = { const action: UIAAction<T> = {
authData, authData,
@@ -79,7 +79,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
setNextAuthData(authData); setNextAuthData(authData);
} }
}, },
[uiaAction, alive] [uiaAction, alive],
); );
const resetUIA = useCallback(() => { const resetUIA = useCallback(() => {
@@ -106,7 +106,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
(err) => { (err) => {
resetUIA(); resetUIA();
reject(err); reject(err);
} },
); );
if (alive()) { if (alive()) {
setUIAAction(action); setUIAAction(action);
@@ -118,7 +118,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
reject(error); reject(error);
}); });
}), }),
[alive, resetUIA] [alive, resetUIA],
); );
const [setupState, setup] = useAsyncCallback<void, Error, [string | undefined]>( const [setupState, setup] = useAsyncCallback<void, Error, [string | undefined]>(
@@ -147,8 +147,8 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
onComplete(recoveryKeyData.encodedPrivateKey); onComplete(recoveryKeyData.encodedPrivateKey);
}, },
[mx, onComplete, authUploadDeviceSigningKeys] [mx, onComplete, authUploadDeviceSigningKeys],
) ),
); );
const loading = setupState.status === AsyncStatus.Loading; const loading = setupState.status === AsyncStatus.Loading;
@@ -302,7 +302,7 @@ export const DeviceVerificationSetup = forwardRef<HTMLDivElement, DeviceVerifica
</Box> </Box>
</Dialog> </Dialog>
); );
} },
); );
type DeviceVerificationResetProps = { type DeviceVerificationResetProps = {
onCancel: () => void; onCancel: () => void;
@@ -359,5 +359,5 @@ export const DeviceVerificationReset = forwardRef<HTMLDivElement, DeviceVerifica
)} )}
</Dialog> </Dialog>
); );
} },
); );
+49
View File
@@ -0,0 +1,49 @@
import FocusTrap from 'focus-trap-react';
import { useAtom } from 'jotai';
import { Box, Button, Dialog, Overlay, OverlayBackdrop, OverlayCenter, config, Text } from 'folds';
import { dialogAtom } from '../state/dialog';
import { stopPropagation } from '../utils/keyboard';
export function DialogHost() {
const [dialog, setDialog] = useAtom(dialogAtom);
if (!dialog) return null;
const close = (answer: boolean) => {
setDialog(null);
dialog.resolve(answer);
};
return (
<Overlay open backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => close(false),
clickOutsideDeactivates: true,
escapeDeactivates: stopPropagation,
}}
>
<Dialog variant="Surface">
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
<Text priority="400" style={{ whiteSpace: 'pre-line' }}>
{dialog.message}
</Text>
<Box direction="Row" gap="200">
{dialog.confirm && (
<Button variant="Secondary" onClick={() => close(false)} radii="300">
<Text size="B300">Cancel</Text>
</Button>
)}
<Button variant="Primary" onClick={() => close(dialog.confirm)} radii="300">
<Text size="B300">{dialog.confirm ? 'Confirm' : 'OK'}</Text>
</Button>
</Box>
</Box>
</Dialog>
</FocusTrap>
</OverlayCenter>
</Overlay>
);
}
+5 -5
View File
@@ -1,8 +1,8 @@
import React, { MouseEventHandler, useCallback, useMemo, useState } from 'react'; import React, { MouseEventHandler, useCallback, useMemo, useState } from 'react';
import { config, Box, MenuItem, Text, RectCords, PopOut, Menu, Button, Spinner } from 'folds'; import { config, Box, MenuItem, Text, RectCords, PopOut, Menu, Button, Spinner } from 'folds';
import { Icon, Icons, IconSrc } from './icons';
import { JoinRule } from 'matrix-js-sdk'; import { JoinRule } from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { Icon, Icons, IconSrc } from './icons';
import { stopPropagation } from '../utils/keyboard'; import { stopPropagation } from '../utils/keyboard';
export type ExtraJoinRules = 'knock_restricted'; export type ExtraJoinRules = 'knock_restricted';
@@ -19,7 +19,7 @@ export const useRoomJoinRuleIcon = (): JoinRuleIcons =>
[JoinRule.Public]: Icons.HashGlobe, [JoinRule.Public]: Icons.HashGlobe,
[JoinRule.Private]: Icons.HashLock, [JoinRule.Private]: Icons.HashLock,
}), }),
[] [],
); );
export const useSpaceJoinRuleIcon = (): JoinRuleIcons => export const useSpaceJoinRuleIcon = (): JoinRuleIcons =>
useMemo( useMemo(
@@ -31,7 +31,7 @@ export const useSpaceJoinRuleIcon = (): JoinRuleIcons =>
[JoinRule.Public]: Icons.SpaceGlobe, [JoinRule.Public]: Icons.SpaceGlobe,
[JoinRule.Private]: Icons.SpaceLock, [JoinRule.Private]: Icons.SpaceLock,
}), }),
[] [],
); );
type JoinRuleLabels = Record<ExtendedJoinRules, string>; type JoinRuleLabels = Record<ExtendedJoinRules, string>;
@@ -45,7 +45,7 @@ export const useRoomJoinRuleLabel = (): JoinRuleLabels =>
[JoinRule.Public]: 'Public', [JoinRule.Public]: 'Public',
[JoinRule.Private]: 'Invite Only', [JoinRule.Private]: 'Invite Only',
}), }),
[] [],
); );
type JoinRulesSwitcherProps<T extends ExtendedJoinRules[]> = { type JoinRulesSwitcherProps<T extends ExtendedJoinRules[]> = {
@@ -77,7 +77,7 @@ export function JoinRulesSwitcher<T extends ExtendedJoinRules[]>({
setCords(undefined); setCords(undefined);
onChange(selectedRule); onChange(selectedRule);
}, },
[onChange] [onChange],
); );
return ( return (
+3 -3
View File
@@ -21,13 +21,13 @@ export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
const verificationStatus = useDeviceVerificationStatus( const verificationStatus = useDeviceVerificationStatus(
mx.getCrypto(), mx.getCrypto(),
mx.getSafeUserId(), mx.getSafeUserId(),
mx.getDeviceId() ?? undefined mx.getDeviceId() ?? undefined,
); );
const [logoutState, logout] = useAsyncCallback<void, Error, []>( const [logoutState, logout] = useAsyncCallback<void, Error, []>(
useCallback(async () => { useCallback(async () => {
await logoutClient(mx); await logoutClient(mx);
}, [mx]) }, [mx]),
); );
const ongoingLogout = logoutState.status === AsyncStatus.Loading; const ongoingLogout = logoutState.status === AsyncStatus.Loading;
@@ -85,5 +85,5 @@ export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
</Box> </Box>
</Dialog> </Dialog>
); );
} },
); );
+4 -4
View File
@@ -1,7 +1,7 @@
import React, { MouseEventHandler, ReactNode, useCallback, useState } from 'react'; import React, { MouseEventHandler, ReactNode, useCallback, useState } from 'react';
import { Box, Text, Chip, RectCords, PopOut, Menu, config, MenuItem, color } from 'folds'; import { Box, Text, Chip, RectCords, PopOut, Menu, config, MenuItem, color } from 'folds';
import { Icon, Icons } from './icons';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from './icons';
import { stopPropagation } from '../utils/keyboard'; import { stopPropagation } from '../utils/keyboard';
import { SettingTile } from './setting-tile'; import { SettingTile } from './setting-tile';
import { SecretStorageKeyContent } from '../../types/matrix/accountData'; import { SecretStorageKeyContent } from '../../types/matrix/accountData';
@@ -115,7 +115,7 @@ export function ManualVerificationTile({
const [method, setMethod] = useState( const [method, setMethod] = useState(
hasPassphrase hasPassphrase
? ManualVerificationMethod.RecoveryPassphrase ? ManualVerificationMethod.RecoveryPassphrase
: ManualVerificationMethod.RecoveryKey : ManualVerificationMethod.RecoveryKey,
); );
const verifyAndRestoreBackup = useCallback( const verifyAndRestoreBackup = useCallback(
@@ -132,11 +132,11 @@ export function ManualVerificationTile({
await crypto.loadSessionBackupPrivateKeyFromSecretStorage(); await crypto.loadSessionBackupPrivateKeyFromSecretStorage();
}, },
[mx, secretStorageKeyId] [mx, secretStorageKeyId],
); );
const [verifyState, handleDecodedRecoveryKey] = useAsyncCallback<void, Error, [Uint8Array]>( const [verifyState, handleDecodedRecoveryKey] = useAsyncCallback<void, Error, [Uint8Array]>(
verifyAndRestoreBackup verifyAndRestoreBackup,
); );
const verifying = verifyState.status === AsyncStatus.Loading; const verifying = verifyState.status === AsyncStatus.Loading;
+19 -6
View File
@@ -1,10 +1,23 @@
/* eslint-disable no-param-reassign */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import React, { FormEventHandler, MouseEventHandler, useEffect, useRef, useState } from 'react'; import React, { FormEventHandler, MouseEventHandler, useEffect, useRef, useState } from 'react';
import classNames from 'classnames'; import classNames from 'classnames';
import { Box, Button, Chip, Header, IconButton, Input, Menu, PopOut, RectCords, Scroll, Spinner, Text, as, config } from 'folds'; import {
import { Icon, Icons } from '../icons'; Box,
Button,
Chip,
Header,
IconButton,
Input,
Menu,
PopOut,
RectCords,
Scroll,
Spinner,
Text,
as,
config,
} from 'folds';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../icons';
import { saveMediaBlob } from '../../utils/saveMedia'; import { saveMediaBlob } from '../../utils/saveMedia';
import * as css from './PdfViewer.css'; import * as css from './PdfViewer.css';
import { AsyncStatus } from '../../hooks/useAsyncCallback'; import { AsyncStatus } from '../../hooks/useAsyncCallback';
@@ -27,7 +40,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
const [pdfJSState, loadPdfJS] = usePdfJSLoader(); const [pdfJSState, loadPdfJS] = usePdfJSLoader();
const [docState, loadPdfDocument] = usePdfDocumentLoader( const [docState, loadPdfDocument] = usePdfDocumentLoader(
pdfJSState.status === AsyncStatus.Success ? pdfJSState.data : undefined, pdfJSState.status === AsyncStatus.Success ? pdfJSState.data : undefined,
src src,
); );
const isLoading = const isLoading =
pdfJSState.status === AsyncStatus.Loading || docState.status === AsyncStatus.Loading; pdfJSState.status === AsyncStatus.Loading || docState.status === AsyncStatus.Loading;
@@ -247,5 +260,5 @@ export const PdfViewer = as<'div', PdfViewerProps>(
)} )}
</Box> </Box>
); );
} },
); );
+20 -17
View File
@@ -25,7 +25,14 @@ import {
VideoContent, VideoContent,
VideoFrameThumbnail, VideoFrameThumbnail,
} from './message'; } from './message';
import { UrlPreviewCard, UrlPreviewHolder, YouTubeEmbed, isYouTubeUrl, TikTokEmbed, isTikTokUrl, GiphyEmbed, isGiphyUrl } from './url-preview'; import {
UrlPreviewCard,
UrlPreviewHolder,
YouTubeEmbed,
isYouTubeUrl,
GiphyEmbed,
isGiphyUrl,
} from './url-preview';
import { Image, MediaControl, Video } from './media'; import { Image, MediaControl, Video } from './media';
import { ImageViewer } from './image-viewer'; import { ImageViewer } from './image-viewer';
import { VideoViewer } from './video-viewer'; import { VideoViewer } from './video-viewer';
@@ -53,7 +60,7 @@ type RenderMessageContentProps = {
onJumboEmojiClick?: ( onJumboEmojiClick?: (
targetEventId: string, targetEventId: string,
body: string, body: string,
event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement> event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>,
) => void; ) => void;
}; };
export function RenderMessageContent({ export function RenderMessageContent({
@@ -79,9 +86,8 @@ export function RenderMessageContent({
// Separate special URLs from generic ones // Separate special URLs from generic ones
const youtubeUrls = filteredUrls.filter(isYouTubeUrl); const youtubeUrls = filteredUrls.filter(isYouTubeUrl);
const tiktokUrls = filteredUrls.filter(isTikTokUrl);
const giphyUrls = filteredUrls.filter(isGiphyUrl); const giphyUrls = filteredUrls.filter(isGiphyUrl);
const otherUrls = filteredUrls.filter((url) => !isYouTubeUrl(url) && !isTikTokUrl(url) && !isGiphyUrl(url)); const otherUrls = filteredUrls.filter((url) => !isYouTubeUrl(url) && !isGiphyUrl(url));
return ( return (
<> <>
@@ -89,10 +95,6 @@ export function RenderMessageContent({
{youtubeUrls.map((url) => ( {youtubeUrls.map((url) => (
<YouTubeEmbed key={url} url={url} /> <YouTubeEmbed key={url} url={url} />
))} ))}
{/* Render TikTok embeds */}
{tiktokUrls.map((url) => (
<TikTokEmbed key={url} url={url} />
))}
{/* Render Giphy embeds */} {/* Render Giphy embeds */}
{giphyUrls.map((url) => ( {giphyUrls.map((url) => (
<GiphyEmbed key={url} url={url} /> <GiphyEmbed key={url} url={url} />
@@ -177,9 +179,10 @@ export function RenderMessageContent({
const customRendererEarly = pluginRegistry.getRenderer('message'); const customRendererEarly = pluginRegistry.getRenderer('message');
if (customRendererEarly) { if (customRendererEarly) {
try { try {
const contentEarly = getContent();
const messageDataEarly = { const messageDataEarly = {
msgtype: msgType, msgtype: msgType,
...getContent(), ...(typeof contentEarly === 'object' && contentEarly !== null ? contentEarly : {}),
}; };
const customContentEarly = customRendererEarly(messageDataEarly, () => null); const customContentEarly = customRendererEarly(messageDataEarly, () => null);
if (customContentEarly) { if (customContentEarly) {
@@ -276,7 +279,8 @@ export function RenderMessageContent({
renderAsFile={renderFile} renderAsFile={renderFile}
renderVideoContent={({ body, info, mimeType, url, encInfo, ...props }) => { renderVideoContent={({ body, info, mimeType, url, encInfo, ...props }) => {
const hasValidThumbnail = const hasValidThumbnail =
(typeof info.thumbnail_file?.url === 'string' || typeof info.thumbnail_url === 'string') && (typeof info.thumbnail_file?.url === 'string' ||
typeof info.thumbnail_url === 'string') &&
typeof info.thumbnail_info?.mimetype === 'string'; typeof info.thumbnail_info?.mimetype === 'string';
return ( return (
@@ -290,7 +294,8 @@ export function RenderMessageContent({
{...props} {...props}
renderThumbnail={ renderThumbnail={
mediaAutoLoad mediaAutoLoad
? () => hasValidThumbnail ? ( ? () =>
hasValidThumbnail ? (
<ThumbnailContent <ThumbnailContent
info={info} info={info}
renderImage={(src) => ( renderImage={(src) => (
@@ -354,19 +359,17 @@ export function RenderMessageContent({
console.log('[RenderMessageContent] customRenderer function:', typeof customRenderer); console.log('[RenderMessageContent] customRenderer function:', typeof customRenderer);
if (customRenderer) { if (customRenderer) {
try { try {
const content = getContent();
const messageData = { const messageData = {
msgtype: msgType, msgtype: msgType,
...getContent(), ...(typeof content === 'object' && content !== null ? content : {}),
}; };
console.log('[RenderMessageContent] Calling customRenderer with msgtype:', msgType); console.log('[RenderMessageContent] Calling customRenderer with msgtype:', msgType);
console.log('[RenderMessageContent] messageData:', messageData); console.log('[RenderMessageContent] messageData:', messageData);
const customContent = customRenderer( const customContent = customRenderer(messageData, () => {
messageData,
() => {
console.log('[RenderMessageContent] defaultRenderer called'); console.log('[RenderMessageContent] defaultRenderer called');
return null; return null;
} });
);
console.log('[RenderMessageContent] customRenderer returned:', customContent); console.log('[RenderMessageContent] customRenderer returned:', customContent);
console.log('[RenderMessageContent] customContent type:', typeof customContent); console.log('[RenderMessageContent] customContent type:', typeof customContent);
if (customContent) { if (customContent) {
@@ -1,7 +1,7 @@
import { Box, config, Menu, MenuItem, PopOut, RectCords, Text } from 'folds'; import { Box, config, Menu, MenuItem, PopOut, RectCords, Text } from 'folds';
import { Icon } from './icons';
import React, { MouseEventHandler, ReactNode, useMemo, useState } from 'react'; import React, { MouseEventHandler, ReactNode, useMemo, useState } from 'react';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { Icon } from './icons';
import { stopPropagation } from '../utils/keyboard'; import { stopPropagation } from '../utils/keyboard';
import { import {
getRoomNotificationModeIcon, getRoomNotificationModeIcon,
@@ -18,7 +18,7 @@ const useRoomNotificationModes = (): RoomNotificationMode[] =>
RoomNotificationMode.SpecialMessages, RoomNotificationMode.SpecialMessages,
RoomNotificationMode.Mute, RoomNotificationMode.Mute,
], ],
[] [],
); );
const useRoomNotificationModeStr = (): Record<RoomNotificationMode, string> => const useRoomNotificationModeStr = (): Record<RoomNotificationMode, string> =>
@@ -29,7 +29,7 @@ const useRoomNotificationModeStr = (): Record<RoomNotificationMode, string> =>
[RoomNotificationMode.SpecialMessages]: 'Mention & Keywords', [RoomNotificationMode.SpecialMessages]: 'Mention & Keywords',
[RoomNotificationMode.Mute]: 'Mute', [RoomNotificationMode.Mute]: 'Mute',
}), }),
[] [],
); );
type NotificationModeSwitcherProps = { type NotificationModeSwitcherProps = {
@@ -38,7 +38,7 @@ type NotificationModeSwitcherProps = {
children: ( children: (
handleOpen: MouseEventHandler<HTMLButtonElement>, handleOpen: MouseEventHandler<HTMLButtonElement>,
opened: boolean, opened: boolean,
changing: boolean changing: boolean,
) => ReactNode; ) => ReactNode;
}; };
export function RoomNotificationModeSwitcher({ export function RoomNotificationModeSwitcher({
+18 -19
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom'; import { useLocation } from 'react-router-dom';
import { style } from '@vanilla-extract/css'; import { keyframes, style } from '@vanilla-extract/css';
const transitionContainer = style({ const transitionContainer = style({
position: 'relative', position: 'relative',
@@ -14,10 +14,7 @@ const transitionContent = style({
height: '100%', height: '100%',
}); });
const animateIn = style({ const routeFadeSlideIn = keyframes({
animation: 'routeFadeSlideIn 0.25s cubic-bezier(0.4, 0, 0.2, 1)',
'@keyframes': {
routeFadeSlideIn: {
from: { from: {
opacity: 0, opacity: 0,
transform: 'translateX(12px)', transform: 'translateX(12px)',
@@ -26,14 +23,13 @@ const animateIn = style({
opacity: 1, opacity: 1,
transform: 'translateX(0)', transform: 'translateX(0)',
}, },
},
},
}); });
const animateOut = style({ const animateIn = style({
animation: 'routeFadeSlideOut 0.2s cubic-bezier(0.4, 0, 0.2, 1) forwards', animation: `${routeFadeSlideIn} 0.25s cubic-bezier(0.4, 0, 0.2, 1)`,
'@keyframes': { });
routeFadeSlideOut: {
const routeFadeSlideOut = keyframes({
from: { from: {
opacity: 1, opacity: 1,
transform: 'translateX(0)', transform: 'translateX(0)',
@@ -42,8 +38,10 @@ const animateOut = style({
opacity: 0, opacity: 0,
transform: 'translateX(-12px)', transform: 'translateX(-12px)',
}, },
}, });
},
const animateOut = style({
animation: `${routeFadeSlideOut} 0.2s cubic-bezier(0.4, 0, 0.2, 1) forwards`,
}); });
interface RouteTransitionProps { interface RouteTransitionProps {
@@ -57,7 +55,7 @@ export function RouteTransition({ children }: RouteTransitionProps) {
const location = useLocation(); const location = useLocation();
const [displayLocation, setDisplayLocation] = useState(location); const [displayLocation, setDisplayLocation] = useState(location);
const [transitionStage, setTransitionStage] = useState<'entering' | 'exiting' | 'idle'>('idle'); const [transitionStage, setTransitionStage] = useState<'entering' | 'exiting' | 'idle'>('idle');
const timeoutRef = useRef<ReturnType<typeof setTimeout>>(); const timeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => { useEffect(() => {
if (location.pathname !== displayLocation.pathname) { if (location.pathname !== displayLocation.pathname) {
@@ -88,11 +86,12 @@ export function RouteTransition({ children }: RouteTransitionProps) {
}; };
}, [location, displayLocation]); }, [location, displayLocation]);
const className = transitionStage === 'entering' let className = transitionContent;
? `${transitionContent} ${animateIn}` if (transitionStage === 'entering') {
: transitionStage === 'exiting' className = `${transitionContent} ${animateIn}`;
? `${transitionContent} ${animateOut}` } else if (transitionStage === 'exiting') {
: transitionContent; className = `${transitionContent} ${animateOut}`;
}
return ( return (
<div className={transitionContainer}> <div className={transitionContainer}>
+14 -7
View File
@@ -1,6 +1,7 @@
import React, { FormEventHandler, useCallback } from 'react'; import React, { FormEventHandler, useCallback } from 'react';
import { Box, Text, Button, Spinner, color } from 'folds'; import { Box, Text, Button, Spinner, color } from 'folds';
import { decodeRecoveryKey, deriveRecoveryKeyFromPassphrase } from 'matrix-js-sdk/lib/crypto-api'; import { decodeRecoveryKey, deriveRecoveryKeyFromPassphrase } from 'matrix-js-sdk/lib/crypto-api';
import { SecretStorageKeyDescriptionAesV1 } from 'matrix-js-sdk/lib/secret-storage';
import { PasswordInput } from './password-input'; import { PasswordInput } from './password-input';
import { import {
SecretStorageKeyContent, SecretStorageKeyContent,
@@ -36,10 +37,13 @@ export function SecretStorageRecoveryPassphrase({
passphrase, passphrase,
salt, salt,
iterations, iterations,
bits bits,
); );
const match = await mx.secretStorage.checkKey(decodedRecoveryKey, keyContent as any); const match = await mx.secretStorage.checkKey(
decodedRecoveryKey,
keyContent as SecretStorageKeyDescriptionAesV1,
);
if (!match) { if (!match) {
throw new Error('Invalid recovery passphrase.'); throw new Error('Invalid recovery passphrase.');
@@ -47,8 +51,8 @@ export function SecretStorageRecoveryPassphrase({
return decodedRecoveryKey; return decodedRecoveryKey;
}, },
[mx, keyContent] [mx, keyContent],
) ),
); );
const drivingKey = driveKeyState.status === AsyncStatus.Loading; const drivingKey = driveKeyState.status === AsyncStatus.Loading;
@@ -131,7 +135,10 @@ export function SecretStorageRecoveryKey({
async (recoveryKey) => { async (recoveryKey) => {
const decodedRecoveryKey = decodeRecoveryKey(recoveryKey); const decodedRecoveryKey = decodeRecoveryKey(recoveryKey);
const match = await mx.secretStorage.checkKey(decodedRecoveryKey, keyContent as any); const match = await mx.secretStorage.checkKey(
decodedRecoveryKey,
keyContent as SecretStorageKeyDescriptionAesV1,
);
if (!match) { if (!match) {
throw new Error('Invalid recovery key.'); throw new Error('Invalid recovery key.');
@@ -139,8 +146,8 @@ export function SecretStorageRecoveryKey({
return decodedRecoveryKey; return decodedRecoveryKey;
}, },
[mx, keyContent] [mx, keyContent],
) ),
); );
const drivingKey = driveKeyState.status === AsyncStatus.Loading; const drivingKey = driveKeyState.status === AsyncStatus.Loading;
+2 -2
View File
@@ -34,7 +34,7 @@ export function ServerConfigsLoader({ children }: ServerConfigsLoaderProps) {
if (authMetadata) { if (authMetadata) {
try { try {
validatedAuthMetadata = validateAuthMetadata(authMetadata); validatedAuthMetadata = validateAuthMetadata(authMetadata);
} catch (e) { } catch {
// Server returned auth metadata but it failed validation — ignore silently. // Server returned auth metadata but it failed validation — ignore silently.
} }
} }
@@ -44,7 +44,7 @@ export function ServerConfigsLoader({ children }: ServerConfigsLoaderProps) {
mediaConfig, mediaConfig,
authMetadata: validatedAuthMetadata, authMetadata: validatedAuthMetadata,
}; };
}, [mx]) }, [mx]),
); );
const configs: ServerConfigs = const configs: ServerConfigs =
@@ -21,7 +21,7 @@ export function SpaceChildDirectsProvider({
const childDirects = useSpaceChildren( const childDirects = useSpaceChildren(
allRoomsAtom, allRoomsAtom,
spaceId, spaceId,
useChildDirectScopeFactory(mx, mDirects, roomToParents) useChildDirectScopeFactory(mx, mDirects, roomToParents),
); );
return children(childDirects); return children(childDirects);
@@ -21,7 +21,7 @@ export function SpaceChildRoomsProvider({
const childRooms = useSpaceChildren( const childRooms = useSpaceChildren(
allRoomsAtom, allRoomsAtom,
spaceId, spaceId,
useChildRoomScopeFactory(mx, mDirects, roomToParents) useChildRoomScopeFactory(mx, mDirects, roomToParents),
); );
return children(childRooms); return children(childRooms);
+2 -2
View File
@@ -15,7 +15,7 @@ export function SpecVersionsLoader({
children, children,
}: SpecVersionsLoaderProps) { }: SpecVersionsLoaderProps) {
const [state, load] = useAsyncCallback( const [state, load] = useAsyncCallback(
useCallback(() => specVersions(fetch, baseUrl), [baseUrl]) useCallback(() => specVersions(fetch, baseUrl), [baseUrl]),
); );
const [ignoreError, setIgnoreError] = useState(false); const [ignoreError, setIgnoreError] = useState(false);
@@ -38,6 +38,6 @@ export function SpecVersionsLoader({
? state.data ? state.data
: { : {
versions: [], versions: [],
} },
); );
} }
+12 -2
View File
@@ -1,7 +1,17 @@
import React, { ReactNode } from 'react'; import React, { ReactNode } from 'react';
import { Overlay, OverlayBackdrop, Box, config, Text, TooltipProvider, Tooltip, Chip, IconButton } from 'folds'; import {
import { Icons, Icon } from './icons'; Overlay,
OverlayBackdrop,
Box,
config,
Text,
TooltipProvider,
Tooltip,
Chip,
IconButton,
} from 'folds';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { Icons, Icon } from './icons';
export type UIAFlowOverlayProps = { export type UIAFlowOverlayProps = {
currentStep: number; currentStep: number;
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Avatar, Box, MenuItem, Text, config } from 'folds'; import { Avatar, Box, MenuItem, Text, config } from 'folds';
import { Icon, Icons } from '../icons';
import { useAtomValue } from 'jotai'; import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../icons';
import { sessionsAtom, Session } from '../../state/sessions'; import { sessionsAtom, Session } from '../../state/sessions';
import { setLocalStorageItem } from '../../state/utils/atomWithLocalStorage'; import { setLocalStorageItem } from '../../state/utils/atomWithLocalStorage';
import { getMxIdServer, mxcUrlToHttp } from '../../utils/matrix'; import { getMxIdServer, mxcUrlToHttp } from '../../utils/matrix';
@@ -26,7 +26,7 @@ function OtherSessionAvatar({ session }: { session: Session }) {
try { try {
const res = await fetch( const res = await fetch(
`${session.baseUrl}/_matrix/client/v3/profile/${encodeURIComponent(session.userId)}`, `${session.baseUrl}/_matrix/client/v3/profile/${encodeURIComponent(session.userId)}`,
{ headers: { Authorization: `Bearer ${session.accessToken}` } } { headers: { Authorization: `Bearer ${session.accessToken}` } },
); );
if (!res.ok) return; if (!res.ok) return;
const data = await res.json(); const data = await res.json();
@@ -34,7 +34,7 @@ function OtherSessionAvatar({ session }: { session: Session }) {
const match = (data.avatar_url as string).match(/^mxc:\/\/([^/]+)\/(.+)$/); const match = (data.avatar_url as string).match(/^mxc:\/\/([^/]+)\/(.+)$/);
if (match) { if (match) {
setSrc( setSrc(
`${session.baseUrl}/_matrix/media/v3/thumbnail/${match[1]}/${match[2]}?width=32&height=32&method=crop` `${session.baseUrl}/_matrix/media/v3/thumbnail/${match[1]}/${match[2]}?width=32&height=32&method=crop`,
); );
} }
} }
@@ -68,16 +68,16 @@ const deleteAllMatrixDatabases = async (): Promise<void> => {
// Try to get all databases if the API is available // Try to get all databases if the API is available
try { try {
if ('databases' in indexedDB) { if ('databases' in indexedDB) {
const allDbs = await (indexedDB as any).databases(); const allDbs = await indexedDB.databases();
const matrixDbs = allDbs const matrixDbs = allDbs
.map((db: any) => db.name) .map((db) => db.name)
.filter((name: string) => .filter(
name && ( (name): name is string =>
name.startsWith('matrix-js-sdk') || typeof name === 'string' &&
(name.startsWith('matrix-js-sdk') ||
name.includes('@@') || name.includes('@@') ||
name.startsWith('sync@@') || name.startsWith('sync@@') ||
name.startsWith('crypto@@') name.startsWith('crypto@@')),
)
); );
dbsToDelete.push(...matrixDbs); dbsToDelete.push(...matrixDbs);
console.log('[AccountSwitcher] Found Matrix databases:', matrixDbs); console.log('[AccountSwitcher] Found Matrix databases:', matrixDbs);
@@ -89,7 +89,7 @@ const deleteAllMatrixDatabases = async (): Promise<void> => {
// Delete each database with timeout // Delete each database with timeout
const deletePromises = dbsToDelete.map(async (dbName) => { const deletePromises = dbsToDelete.map(async (dbName) => {
try { try {
const deletePromise = new Promise<void>((resolve, reject) => { const deletePromise = new Promise<void>((resolve) => {
const request = indexedDB.deleteDatabase(dbName); const request = indexedDB.deleteDatabase(dbName);
request.onsuccess = () => { request.onsuccess = () => {
console.log(`[AccountSwitcher] ✅ Deleted database: ${dbName}`); console.log(`[AccountSwitcher] ✅ Deleted database: ${dbName}`);
@@ -129,7 +129,7 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) {
const useAuthentication = useMediaAuthentication(); const useAuthentication = useMediaAuthentication();
const currentProfile = useUserProfile(currentUserId ?? ''); const currentProfile = useUserProfile(currentUserId ?? '');
const currentAvatarUrl = currentProfile.avatarUrl const currentAvatarUrl = currentProfile.avatarUrl
? mxcUrlToHttp(mx, currentProfile.avatarUrl, useAuthentication, 32, 32, 'crop') ?? undefined ? (mxcUrlToHttp(mx, currentProfile.avatarUrl, useAuthentication, 32, 32, 'crop') ?? undefined)
: undefined; : undefined;
const handleSwitchAccount = async (session: Session) => { const handleSwitchAccount = async (session: Session) => {
@@ -155,7 +155,9 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) {
await deleteAllMatrixDatabases(); await deleteAllMatrixDatabases();
// Small delay to ensure cleanup is complete // Small delay to ensure cleanup is complete
await new Promise(resolve => setTimeout(resolve, 100)); await new Promise((resolve) => {
setTimeout(resolve, 100);
});
// Reload the page to initialize the new session // Reload the page to initialize the new session
console.log('[AccountSwitcher] Reloading page...'); console.log('[AccountSwitcher] Reloading page...');
@@ -168,12 +170,15 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) {
} }
// Filter out other sessions (not current) // Filter out other sessions (not current)
const otherSessions = sessions.filter(s => s.userId !== currentUserId); const otherSessions = sessions.filter((s) => s.userId !== currentUserId);
const hasMultipleAccounts = sessions.length > 1; const hasMultipleAccounts = sessions.length > 1;
return ( return (
<Box direction="Column" gap="200"> <Box direction="Column" gap="200">
<Text size="L400" style={{ paddingInline: config.space.S200, paddingBlock: config.space.S100 }}> <Text
size="L400"
style={{ paddingInline: config.space.S200, paddingBlock: config.space.S100 }}
>
{hasMultipleAccounts ? 'Switch Account' : 'Accounts'} {hasMultipleAccounts ? 'Switch Account' : 'Accounts'}
</Text> </Text>
@@ -16,7 +16,7 @@ export const AuthenticatedAvatarImage = forwardRef<HTMLImageElement, Authenticat
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication); const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
return <AvatarImage ref={ref} {...props} src={authenticatedSrc} />; return <AvatarImage ref={ref} {...props} src={authenticatedSrc} />;
} },
); );
AuthenticatedAvatarImage.displayName = 'AuthenticatedAvatarImage'; AuthenticatedAvatarImage.displayName = 'AuthenticatedAvatarImage';
@@ -1,9 +1,8 @@
import React, { ImgHTMLAttributes, forwardRef, useEffect, useState } from 'react'; import React, { ImgHTMLAttributes, forwardRef } from 'react';
import { useAuthenticatedMediaUrl } from '../../hooks/useAuthenticatedMediaUrl'; import { useAuthenticatedMediaUrl } from '../../hooks/useAuthenticatedMediaUrl';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
export interface AuthenticatedMediaProps export interface AuthenticatedMediaProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {
extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {
/** The source URL of the media (may be an authenticated media URL) */ /** The source URL of the media (may be an authenticated media URL) */
src?: string; src?: string;
/** Override for authentication - if not provided, uses useMediaAuthentication hook */ /** Override for authentication - if not provided, uses useMediaAuthentication hook */
@@ -16,13 +15,13 @@ export interface AuthenticatedMediaProps
* and renders them as blob URLs. * and renders them as blob URLs.
*/ */
export const AuthenticatedMedia = forwardRef<HTMLImageElement, AuthenticatedMediaProps>( export const AuthenticatedMedia = forwardRef<HTMLImageElement, AuthenticatedMediaProps>(
({ src, useAuthentication: useAuthOverride, ...props }, ref) => { ({ src, alt, useAuthentication: useAuthOverride, ...props }, ref) => {
const useAuthFromServer = useMediaAuthentication(); const useAuthFromServer = useMediaAuthentication();
const useAuthentication = useAuthOverride ?? useAuthFromServer; const useAuthentication = useAuthOverride ?? useAuthFromServer;
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication); const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
return <img ref={ref} {...props} src={authenticatedSrc} />; return <img ref={ref} alt={alt} {...props} src={authenticatedSrc} />;
} },
); );
AuthenticatedMedia.displayName = 'AuthenticatedMedia'; AuthenticatedMedia.displayName = 'AuthenticatedMedia';
@@ -31,15 +30,15 @@ AuthenticatedMedia.displayName = 'AuthenticatedMedia';
* A simpler authenticated img component for use in places like custom HTML parsers. * A simpler authenticated img component for use in places like custom HTML parsers.
* This component handles its own authentication state. * This component handles its own authentication state.
*/ */
export interface AuthenticatedImgProps extends ImgHTMLAttributes<HTMLImageElement> {} export type AuthenticatedImgProps = ImgHTMLAttributes<HTMLImageElement>;
export const AuthenticatedImg = forwardRef<HTMLImageElement, AuthenticatedImgProps>( export const AuthenticatedImg = forwardRef<HTMLImageElement, AuthenticatedImgProps>(
({ src, ...props }, ref) => { ({ src, alt, ...props }, ref) => {
const useAuthentication = useMediaAuthentication(); const useAuthentication = useMediaAuthentication();
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication); const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
return <img ref={ref} {...props} src={authenticatedSrc} />; return <img ref={ref} alt={alt} {...props} src={authenticatedSrc} />;
} },
); );
AuthenticatedImg.displayName = 'AuthenticatedImg'; AuthenticatedImg.displayName = 'AuthenticatedImg';
@@ -1,5 +1,18 @@
import { Box, Button, Chip, config, Input, Line, Menu, MenuItem, PopOut, RectCords, Scroll, Text, toRem } from 'folds'; import {
import { Icon, Icons } from '../icons'; Box,
Button,
Chip,
config,
Input,
Line,
Menu,
MenuItem,
PopOut,
RectCords,
Scroll,
Text,
toRem,
} from 'folds';
import { isKeyHotkey } from 'is-hotkey'; import { isKeyHotkey } from 'is-hotkey';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import React, { import React, {
@@ -9,6 +22,7 @@ import React, {
useMemo, useMemo,
useState, useState,
} from 'react'; } from 'react';
import { Icon, Icons } from '../icons';
import { getMxIdLocalPart, getMxIdServer, isUserId } from '../../utils/matrix'; import { getMxIdLocalPart, getMxIdServer, isUserId } from '../../utils/matrix';
import { useDirectUsers } from '../../hooks/useDirectUsers'; import { useDirectUsers } from '../../hooks/useDirectUsers';
import { SettingTile } from '../setting-tile'; import { SettingTile } from '../setting-tile';
@@ -20,7 +34,7 @@ import { highlightText, makeHighlightRegex } from '../../plugins/react-custom-ht
export const useAdditionalCreators = (defaultCreators?: string[]) => { export const useAdditionalCreators = (defaultCreators?: string[]) => {
const mx = useMatrixClient(); const mx = useMatrixClient();
const [additionalCreators, setAdditionalCreators] = useState<string[]>( const [additionalCreators, setAdditionalCreators] = useState<string[]>(
() => defaultCreators?.filter((id) => id !== mx.getSafeUserId()) ?? [] () => defaultCreators?.filter((id) => id !== mx.getSafeUserId()) ?? [],
); );
const addAdditionalCreator = (userId: string) => { const addAdditionalCreator = (userId: string) => {
@@ -75,12 +89,12 @@ export function AdditionalCreatorInput({
const [validUserId, setValidUserId] = useState<string>(); const [validUserId, setValidUserId] = useState<string>();
const filteredUsers = useMemo( const filteredUsers = useMemo(
() => directUsers.filter((userId) => !additionalCreators.includes(userId)), () => directUsers.filter((userId) => !additionalCreators.includes(userId)),
[directUsers, additionalCreators] [directUsers, additionalCreators],
); );
const [result, search, resetSearch] = useAsyncSearch( const [result, search, resetSearch] = useAsyncSearch(
filteredUsers, filteredUsers,
getUserIdString, getUserIdString,
SEARCH_OPTIONS SEARCH_OPTIONS,
); );
const queryHighlighRegex = result?.query ? makeHighlightRegex([result.query]) : undefined; const queryHighlighRegex = result?.query ? makeHighlightRegex([result.query]) : undefined;
@@ -8,8 +8,8 @@ import React, {
} from 'react'; } from 'react';
import { MatrixError } from 'matrix-js-sdk'; import { MatrixError } from 'matrix-js-sdk';
import { Box, color, Input, Spinner, Text, toRem } from 'folds'; import { Box, color, Input, Spinner, Text, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import { isKeyHotkey } from 'is-hotkey'; import { isKeyHotkey } from 'is-hotkey';
import { Icon, Icons } from '../icons';
import { getMxIdServer } from '../../utils/matrix'; import { getMxIdServer } from '../../utils/matrix';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { replaceSpaceWithDash } from '../../utils/common'; import { replaceSpaceWithDash } from '../../utils/common';
@@ -43,9 +43,9 @@ export function CreateRoomAliasInput({ disabled }: { disabled?: boolean }) {
throw e; throw e;
} }
}, },
[mx] [mx],
), ),
setAliasAvail setAliasAvail,
); );
const aliasAvailable: boolean | undefined = const aliasAvailable: boolean | undefined =
aliasAvail.status === AsyncStatus.Success ? aliasAvail.data : undefined; aliasAvail.status === AsyncStatus.Success ? aliasAvail.data : undefined;
@@ -1,7 +1,7 @@
import React, { MouseEventHandler, useState } from 'react'; import React, { MouseEventHandler, useState } from 'react';
import { Box, Button, Chip, config, Menu, PopOut, RectCords, Text, toRem } from 'folds'; import { Box, Button, Chip, config, Menu, PopOut, RectCords, Text, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../icons';
import { SettingTile } from '../setting-tile'; import { SettingTile } from '../setting-tile';
import { SequenceCard } from '../sequence-card'; import { SequenceCard } from '../sequence-card';
import { stopPropagation } from '../../utils/keyboard'; import { stopPropagation } from '../../utils/keyboard';
+9 -8
View File
@@ -1,4 +1,5 @@
import { import {
EventType,
ICreateRoomOpts, ICreateRoomOpts,
ICreateRoomStateEvent, ICreateRoomStateEvent,
JoinRule, JoinRule,
@@ -6,7 +7,7 @@ import {
RestrictedAllowType, RestrictedAllowType,
Room, Room,
} from 'matrix-js-sdk'; } from 'matrix-js-sdk';
import { RoomJoinRulesEventContent } from 'matrix-js-sdk/lib/types'; import { RoomJoinRulesEventContent, SpaceChildEventContent } from 'matrix-js-sdk/lib/types';
import { CreateRoomKind } from './CreateRoomKindSelector'; import { CreateRoomKind } from './CreateRoomKindSelector';
import { RoomType, StateEvent } from '../../../types/matrix/room'; import { RoomType, StateEvent } from '../../../types/matrix/room';
import { getViaServers } from '../../plugins/via-servers'; import { getViaServers } from '../../plugins/via-servers';
@@ -15,9 +16,9 @@ import { getMxIdServer } from '../../utils/matrix';
export const createRoomCreationContent = ( export const createRoomCreationContent = (
type: RoomType | undefined, type: RoomType | undefined,
allowFederation: boolean, allowFederation: boolean,
additionalCreators: string[] | undefined additionalCreators: string[] | undefined,
): object => { ): object => {
const content: Record<string, any> = {}; const content: Record<string, unknown> = {};
if (typeof type === 'string') { if (typeof type === 'string') {
content.type = type; content.type = type;
} }
@@ -34,7 +35,7 @@ export const createRoomCreationContent = (
export const createRoomJoinRulesState = ( export const createRoomJoinRulesState = (
kind: CreateRoomKind, kind: CreateRoomKind,
parent: Room | undefined, parent: Room | undefined,
knock: boolean knock: boolean,
) => { ) => {
let content: RoomJoinRulesEventContent = { let content: RoomJoinRulesEventContent = {
join_rule: knock ? JoinRule.Knock : JoinRule.Invite, join_rule: knock ? JoinRule.Knock : JoinRule.Invite,
@@ -134,7 +135,7 @@ export const createRoom = async (mx: MatrixClient, data: CreateRoomData): Promis
creation_content: createRoomCreationContent( creation_content: createRoomCreationContent(
data.type, data.type,
data.allowFederation, data.allowFederation,
data.additionalCreators data.additionalCreators,
), ),
initial_state: initialState, initial_state: initialState,
}; };
@@ -144,13 +145,13 @@ export const createRoom = async (mx: MatrixClient, data: CreateRoomData): Promis
if (data.parent) { if (data.parent) {
await mx.sendStateEvent( await mx.sendStateEvent(
data.parent.roomId, data.parent.roomId,
StateEvent.SpaceChild as any, EventType.SpaceChild,
{ {
auto_join: false, auto_join: false,
suggested: false, suggested: false,
via: [getMxIdServer(mx.getUserId() ?? '') ?? ''], via: [getMxIdServer(mx.getUserId() ?? '') ?? ''],
}, } as SpaceChildEventContent,
result.room_id result.room_id,
); );
} }
@@ -59,7 +59,7 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
status_msg: statusText, status_msg: statusText,
}); });
onClose(); onClose();
}, [mx, presence?.presence, statusText, onClose]) }, [mx, presence?.presence, statusText, onClose]),
); );
/** /**
@@ -73,7 +73,7 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
}); });
setStatusText(''); setStatusText('');
onClose(); onClose();
}, [mx, presence?.presence, onClose]) }, [mx, presence?.presence, onClose]),
); );
/** /**
@@ -126,7 +126,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
placeholder="What's on your mind?" placeholder="What's on your mind?"
maxLength={100} maxLength={100}
autoFocus autoFocus
disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading} disabled={
saveState.status === AsyncStatus.Loading ||
clearState.status === AsyncStatus.Loading
}
/> />
{statusText.length > 0 && ( {statusText.length > 0 && (
<Text size="T200" priority="300"> <Text size="T200" priority="300">
@@ -135,7 +138,8 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
)} )}
</Box> </Box>
{(saveState.status === AsyncStatus.Error || clearState.status === AsyncStatus.Error) && ( {(saveState.status === AsyncStatus.Error ||
clearState.status === AsyncStatus.Error) && (
<Text size="T300" priority="400" style={{ color: 'var(--color-critical-main)' }}> <Text size="T300" priority="400" style={{ color: 'var(--color-critical-main)' }}>
Failed to update status. Please try again. Failed to update status. Please try again.
</Text> </Text>
@@ -146,7 +150,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
type="button" type="button"
variant="Secondary" variant="Secondary"
onClick={onClose} onClick={onClose}
disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading} disabled={
saveState.status === AsyncStatus.Loading ||
clearState.status === AsyncStatus.Loading
}
> >
<Text size="B400">Cancel</Text> <Text size="B400">Cancel</Text>
</Button> </Button>
@@ -156,7 +163,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
variant="Critical" variant="Critical"
fill="None" fill="None"
onClick={handleClear} onClick={handleClear}
disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading} disabled={
saveState.status === AsyncStatus.Loading ||
clearState.status === AsyncStatus.Loading
}
> >
<Text size="B400">Clear Status</Text> <Text size="B400">Clear Status</Text>
</Button> </Button>
@@ -164,7 +174,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
<Button <Button
type="submit" type="submit"
variant="Primary" variant="Primary"
disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading} disabled={
saveState.status === AsyncStatus.Loading ||
clearState.status === AsyncStatus.Loading
}
> >
<Text size="B400"> <Text size="B400">
{saveState.status === AsyncStatus.Loading ? 'Saving...' : 'Save'} {saveState.status === AsyncStatus.Loading ? 'Saving...' : 'Save'}
@@ -11,5 +11,5 @@ export const CutoutCard = as<'div', { variant?: TContainerColor }>(
{...props} {...props}
ref={ref} ref={ref}
/> />
) ),
); );
+20 -10
View File
@@ -1,12 +1,23 @@
import React, { MouseEventHandler, forwardRef, useMemo, useState } from 'react'; import React, { MouseEventHandler, forwardRef, useMemo, useState } from 'react';
import { useAtom, useAtomValue } from 'jotai'; import { useAtom, useAtomValue } from 'jotai';
import { Avatar, Box, Button, IconButton, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds'; import {
import { Icon, Icons } from '../icons'; Avatar,
Box,
Button,
IconButton,
Menu,
MenuItem,
PopOut,
RectCords,
Text,
config,
toRem,
} from 'folds';
import { useVirtualizer } from '@tanstack/react-virtual'; import { useVirtualizer } from '@tanstack/react-virtual';
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Icon, Icons } from '../icons';
import { useMatrixClient } from '../../hooks/useMatrixClient'; import { useMatrixClient } from '../../hooks/useMatrixClient';
import { factoryRoomIdByActivity } from '../../utils/sort';
import { import {
NavButton, NavButton,
NavCategory, NavCategory,
@@ -180,7 +191,7 @@ const DEFAULT_CATEGORY_ID = makeNavCategoryId('direct', 'direct');
* Props for the DirectList component * Props for the DirectList component
*/ */
export type DirectListProps = { export type DirectListProps = {
scrollRef: React.RefObject<HTMLDivElement>; scrollRef: React.RefObject<HTMLDivElement | null>;
showCreateButton?: boolean; showCreateButton?: boolean;
showCategoryHeader?: boolean; showCategoryHeader?: boolean;
}; };
@@ -203,15 +214,14 @@ export function DirectList({
const selectedRoomId = useSelectedRoom(); const selectedRoomId = useSelectedRoom();
const [closedCategories, setClosedCategories] = useAtom(useClosedNavCategoriesAtom()); const [closedCategories, setClosedCategories] = useAtom(useClosedNavCategoriesAtom());
const reorderTrigger = useRoomListReorder(mx, directs); const activityOrder = useRoomListReorder(mx, directs);
const sortedDirects = useMemo(() => { const sortedDirects = useMemo(() => {
const items = Array.from(directs).sort(factoryRoomIdByActivity(mx));
if (closedCategories.has(DEFAULT_CATEGORY_ID)) { if (closedCategories.has(DEFAULT_CATEGORY_ID)) {
return items.filter((rId) => roomToUnread.has(rId) || rId === selectedRoomId); return activityOrder.filter((rId) => roomToUnread.has(rId) || rId === selectedRoomId);
} }
return items; return activityOrder;
}, [mx, directs, closedCategories, roomToUnread, selectedRoomId, reorderTrigger]); }, [activityOrder, closedCategories, roomToUnread, selectedRoomId]);
const animationRef = useListReorderAnimation(sortedDirects); const animationRef = useListReorderAnimation(sortedDirects);
@@ -223,7 +233,7 @@ export function DirectList({
}); });
const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) => const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) =>
closedCategories.has(categoryId) closedCategories.has(categoryId),
); );
const noRoomToDisplay = directs.length === 0; const noRoomToDisplay = directs.length === 0;
+27 -24
View File
@@ -1,4 +1,3 @@
/* eslint-disable no-param-reassign */
import React, { import React, {
ClipboardEventHandler, ClipboardEventHandler,
KeyboardEventHandler, KeyboardEventHandler,
@@ -8,7 +7,15 @@ import React, {
useState, useState,
} from 'react'; } from 'react';
import { Box, Scroll, Text } from 'folds'; import { Box, Scroll, Text } from 'folds';
import { Descendant, Editor, createEditor, Element as SlateElement, Text as SlateText } from 'slate'; import {
DecoratedRange,
Descendant,
Editor,
NodeEntry,
createEditor,
Element as SlateElement,
Text as SlateText,
} from 'slate';
import { import {
Slate, Slate,
Editable, Editable,
@@ -23,7 +30,6 @@ import { RenderElement, RenderLeaf } from './Elements';
import { CustomElement } from './slate'; import { CustomElement } from './slate';
import * as css from './Editor.css'; import * as css from './Editor.css';
import { toggleKeyboardShortcut } from './keyboard'; import { toggleKeyboardShortcut } from './keyboard';
import { createCommandElement } from './utils';
const initialValue: CustomElement[] = [ const initialValue: CustomElement[] = [
{ {
@@ -37,7 +43,7 @@ const withInline = (editor: Editor): Editor => {
editor.isInline = (element) => editor.isInline = (element) =>
[BlockType.Mention, BlockType.Emoticon, BlockType.Link, BlockType.Command].includes( [BlockType.Mention, BlockType.Emoticon, BlockType.Link, BlockType.Command].includes(
element.type element.type,
) || isInline(element); ) || isInline(element);
return editor; return editor;
@@ -61,16 +67,15 @@ export const setCommandValidator = (validator: CommandValidatorFn) => {
commandValidator = validator; commandValidator = validator;
}; };
const withCommandAutoConvert = (editor: Editor): Editor => { const withCommandAutoConvert = (editor: Editor): Editor =>
// Removed auto-conversion on space to prevent focus issues // Removed auto-conversion on space to prevent focus issues
// Commands are now highlighted visually via decorations // Commands are now highlighted visually via decorations
// and executed when Enter is pressed // and executed when Enter is pressed
return editor; editor;
};
export const useEditor = (): Editor => { export const useEditor = (): Editor => {
const [editor] = useState(() => const [editor] = useState(() =>
withCommandAutoConvert(withInline(withVoid(withReact(withHistory(createEditor()))))) withCommandAutoConvert(withInline(withVoid(withReact(withHistory(createEditor()))))),
); );
return editor; return editor;
}; };
@@ -109,29 +114,25 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
onChange, onChange,
onPaste, onPaste,
}, },
ref ref,
) => { ) => {
const renderElement = useCallback( const renderElement = useCallback(
(props: RenderElementProps) => <RenderElement {...props} />, (props: RenderElementProps) => <RenderElement {...props} />,
[] [],
); );
const renderLeaf = useCallback((props: RenderLeafProps) => <RenderLeaf {...props} />, []); const renderLeaf = useCallback((props: RenderLeafProps) => <RenderLeaf {...props} />, []);
const decorate = useCallback(([node, path]: [any, number[]]) => { const decorate = useCallback(
const ranges: any[] = []; ([node, path]: NodeEntry) => {
const ranges: (DecoratedRange & { pendingCommand?: boolean })[] = [];
// Only decorate text nodes in the first paragraph // Only decorate text nodes in the first paragraph
if ( if (path.length === 2 && path[0] === 0 && path[1] === 0 && SlateText.isText(node)) {
path.length === 2 &&
path[0] === 0 &&
path[1] === 0 &&
SlateText.isText(node)
) {
const firstChild = editor.children[0]; const firstChild = editor.children[0];
if (SlateElement.isElement(firstChild) && firstChild.type === BlockType.Paragraph) { if (SlateElement.isElement(firstChild) && firstChild.type === BlockType.Paragraph) {
const [firstInline, secondInline] = firstChild.children; const [, secondInline] = firstChild.children;
// Don't decorate if we already have a CommandElement // Don't decorate if we already have a CommandElement
if (SlateElement.isElement(secondInline) && secondInline.type === BlockType.Command) { if (SlateElement.isElement(secondInline) && secondInline.type === BlockType.Command) {
@@ -139,7 +140,7 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
} }
// Check if the text matches /command pattern // Check if the text matches /command pattern
const text = node.text; const { text } = node;
const match = text.match(/^(\s*\/\w+)/); const match = text.match(/^(\s*\/\w+)/);
if (match && commandValidator) { if (match && commandValidator) {
@@ -159,7 +160,9 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
} }
return ranges; return ranges;
}, [editor]); },
[editor],
);
const handleKeydown: KeyboardEventHandler = useCallback( const handleKeydown: KeyboardEventHandler = useCallback(
(evt) => { (evt) => {
@@ -167,7 +170,7 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
const shortcutToggled = toggleKeyboardShortcut(editor, evt); const shortcutToggled = toggleKeyboardShortcut(editor, evt);
if (shortcutToggled) evt.preventDefault(); if (shortcutToggled) evt.preventDefault();
}, },
[editor, onKeyDown] [editor, onKeyDown],
); );
const renderPlaceholder = useCallback( const renderPlaceholder = useCallback(
@@ -179,7 +182,7 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
</Text> </Text>
</span> </span>
), ),
[] [],
); );
const scrollStyle = fillHeight const scrollStyle = fillHeight
@@ -239,5 +242,5 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
</Slate> </Slate>
</div> </div>
); );
} },
); );
+16 -2
View File
@@ -1,8 +1,22 @@
import FocusTrap from 'focus-trap-react'; import FocusTrap from 'focus-trap-react';
import { Badge, Box, config, IconButton, Line, Menu, PopOut, RectCords, Scroll, Text, Tooltip, TooltipProvider, toRem } from 'folds'; import {
import { Icon, Icons, IconSrc } from '../icons'; Badge,
Box,
config,
IconButton,
Line,
Menu,
PopOut,
RectCords,
Scroll,
Text,
Tooltip,
TooltipProvider,
toRem,
} from 'folds';
import React, { MouseEventHandler, ReactNode, useState } from 'react'; import React, { MouseEventHandler, ReactNode, useState } from 'react';
import { ReactEditor, useSlate } from 'slate-react'; import { ReactEditor, useSlate } from 'slate-react';
import { Icon, Icons, IconSrc } from '../icons';
import { import {
headingLevel, headingLevel,
isAnyMarkActive, isAnyMarkActive,
@@ -51,14 +51,14 @@ export function EmoticonAutocomplete({
const list: Array<EmoticonSearchItem> = []; const list: Array<EmoticonSearchItem> = [];
return list.concat( return list.concat(
imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)), imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)),
emojis emojis,
); );
}, [imagePacks]); }, [imagePacks]);
const [result, search, resetSearch] = useAsyncSearch( const [result, search, resetSearch] = useAsyncSearch(
searchList, searchList,
getEmoticonSearchStr, getEmoticonSearchStr,
SEARCH_OPTIONS SEARCH_OPTIONS,
); );
const autoCompleteEmoticon = result ? result.items.slice(0, 20) : recentEmoji; const autoCompleteEmoticon = result ? result.items.slice(0, 20) : recentEmoji;
@@ -1,9 +1,9 @@
import React, { KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect } from 'react'; import React, { KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect } from 'react';
import { Editor } from 'slate'; import { Editor } from 'slate';
import { Avatar, MenuItem, Text } from 'folds'; import { Avatar, MenuItem, Text } from 'folds';
import { Icon, Icons } from '../../icons';
import { JoinRule, MatrixClient } from 'matrix-js-sdk'; import { JoinRule, MatrixClient } from 'matrix-js-sdk';
import { useAtomValue } from 'jotai'; import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../icons';
import { createMentionElement, moveCursor, replaceWithElement } from '../utils'; import { createMentionElement, moveCursor, replaceWithElement } from '../utils';
import { getDirectRoomAvatarUrl, guessPerfectParent } from '../../../utils/room'; import { getDirectRoomAvatarUrl, guessPerfectParent } from '../../../utils/room';
@@ -94,9 +94,9 @@ export function RoomMentionAutocomplete({
if (alias) return [r.name, alias]; if (alias) return [r.name, alias];
return r.name; return r.name;
}, },
[mx] [mx],
), ),
SEARCH_OPTIONS SEARCH_OPTIONS,
); );
const autoCompleteRoomIds = result ? result.items.slice(0, 20) : allRooms.slice(0, 20); const autoCompleteRoomIds = result ? result.items.slice(0, 20) : allRooms.slice(0, 20);
@@ -107,7 +107,8 @@ export function RoomMentionAutocomplete({
}, [query.text, search, resetSearch]); }, [query.text, search, resetSearch]);
// Build space hierarchy path for a room // Build space hierarchy path for a room
const getSpacePath = useCallback((rId: string): string | null => { const getSpacePath = useCallback(
(rId: string): string | null => {
// Skip DMs // Skip DMs
if (mDirects.has(rId)) return null; if (mDirects.has(rId)) return null;
@@ -118,16 +119,17 @@ export function RoomMentionAutocomplete({
} }
const parentsList = Array.from(parents); const parentsList = Array.from(parents);
const [firstParent] = parentsList;
let chosenParent: string; let chosenParent: string;
if (parentsList.length === 1) { if (parentsList.length === 1) {
chosenParent = parentsList[0]; chosenParent = firstParent;
} else { } else {
const orphanParents = parentsList.filter(p => !roomToParents.has(p)); const orphanParents = parentsList.filter((p) => !roomToParents.has(p));
if (orphanParents.length > 0) { if (orphanParents.length > 0) {
chosenParent = guessPerfectParent(mx, currentRoomId, orphanParents) ?? orphanParents[0]; chosenParent = guessPerfectParent(mx, currentRoomId, orphanParents) ?? orphanParents[0];
} else { } else {
chosenParent = parentsList[0]; chosenParent = firstParent;
} }
} }
@@ -140,7 +142,9 @@ export function RoomMentionAutocomplete({
const parentChain = buildParentChain(rId); const parentChain = buildParentChain(rId);
return parentChain.length > 0 ? parentChain.join(' > ') : null; return parentChain.length > 0 ? parentChain.join(' > ') : null;
}, [mx, mDirects, roomToParents]); },
[mx, mDirects, roomToParents],
);
const handleAutocomplete: MentionAutoCompleteHandler = (roomAliasOrId, name) => { const handleAutocomplete: MentionAutoCompleteHandler = (roomAliasOrId, name) => {
const mentionRoom = mx.getRoom(roomAliasOrId); const mentionRoom = mx.getRoom(roomAliasOrId);
@@ -150,7 +154,7 @@ export function RoomMentionAutocomplete({
name.startsWith('#') ? name : `#${name}`, name.startsWith('#') ? name : `#${name}`,
roomId === roomAliasOrId || mx.getRoom(roomId)?.getCanonicalAlias() === roomAliasOrId, roomId === roomAliasOrId || mx.getRoom(roomId)?.getCanonicalAlias() === roomAliasOrId,
undefined, undefined,
viaServers viaServers,
); );
replaceWithElement(editor, query.range, mentionEl); replaceWithElement(editor, query.range, mentionEl);
moveCursor(editor, true); moveCursor(editor, true);
@@ -1,8 +1,8 @@
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, MenuItem, Text } from 'folds'; import { Avatar, MenuItem, Text } from 'folds';
import { Icon, Icons } from '../../icons';
import { MatrixClient, Room, RoomMember } from 'matrix-js-sdk'; import { MatrixClient, Room, RoomMember } from 'matrix-js-sdk';
import { Icon, Icons } from '../../icons';
import { AutocompleteQuery } from './autocompleteQuery'; import { AutocompleteQuery } from './autocompleteQuery';
import { AutocompleteMenu } from './AutocompleteMenu'; import { AutocompleteMenu } from './AutocompleteMenu';
@@ -99,7 +99,7 @@ export function UserMentionAutocomplete({
const [result, search, resetSearch] = useAsyncSearch(members, getRoomMemberStr, SEARCH_OPTIONS); const [result, search, resetSearch] = useAsyncSearch(members, getRoomMemberStr, SEARCH_OPTIONS);
const autoCompleteMembers = (result ? result.items.slice(0, 20) : members.slice(0, 20)).filter( const autoCompleteMembers = (result ? result.items.slice(0, 20) : members.slice(0, 20)).filter(
withAllowedMembership withAllowedMembership,
); );
useEffect(() => { useEffect(() => {
@@ -111,7 +111,7 @@ export function UserMentionAutocomplete({
const mentionEl = createMentionElement( const mentionEl = createMentionElement(
uId, uId,
name.startsWith('@') ? name : `@${name}`, name.startsWith('@') ? name : `@${name}`,
mx.getUserId() === uId || roomAliasOrId === uId mx.getUserId() === uId || roomAliasOrId === uId,
); );
replaceWithElement(editor, query.range, mentionEl); replaceWithElement(editor, query.range, mentionEl);
moveCursor(editor, true); moveCursor(editor, true);
@@ -22,7 +22,7 @@ export type AutocompleteQuery<TPrefix extends string> = {
export const getAutocompletePrefix = <TPrefix extends string>( export const getAutocompletePrefix = <TPrefix extends string>(
editor: Editor, editor: Editor,
queryRange: BaseRange, queryRange: BaseRange,
validPrefixes: readonly TPrefix[] validPrefixes: readonly TPrefix[],
): TPrefix | undefined => { ): TPrefix | undefined => {
const world = Editor.string(editor, queryRange); const world = Editor.string(editor, queryRange);
return validPrefixes.find((p) => world.startsWith(p)); return validPrefixes.find((p) => world.startsWith(p));
@@ -31,13 +31,13 @@ export const getAutocompletePrefix = <TPrefix extends string>(
export const getAutocompleteQueryText = ( export const getAutocompleteQueryText = (
editor: Editor, editor: Editor,
queryRange: BaseRange, queryRange: BaseRange,
prefix: string prefix: string,
): string => Editor.string(editor, queryRange).slice(prefix.length); ): string => Editor.string(editor, queryRange).slice(prefix.length);
export const getAutocompleteQuery = <TPrefix extends string>( export const getAutocompleteQuery = <TPrefix extends string>(
editor: Editor, editor: Editor,
queryRange: BaseRange, queryRange: BaseRange,
validPrefixes: readonly TPrefix[] validPrefixes: readonly TPrefix[],
): AutocompleteQuery<TPrefix> | undefined => { ): AutocompleteQuery<TPrefix> | undefined => {
const prefix = getAutocompletePrefix(editor, queryRange, validPrefixes); const prefix = getAutocompletePrefix(editor, queryRange, validPrefixes);
if (!prefix) return undefined; if (!prefix) return undefined;

Some files were not shown because too many files have changed in this diff Show More