Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4591f669b | ||
|
|
185970bc5a | ||
|
|
8cdf192b56 | ||
|
|
222927b558 | ||
|
|
b944456ab5 | ||
|
|
02bd356a89 | ||
|
|
3b3bf8abac | ||
|
|
22d5aea5e6 | ||
|
|
826fc46229 | ||
|
|
b93e4bcef9 | ||
|
|
1af491cabb | ||
|
|
449d0c740e | ||
|
|
a7495fc509 | ||
|
|
299da879fb | ||
|
|
f8fa1ca5ed | ||
|
|
5d15013a27 | ||
|
|
378b40fabe | ||
|
|
0d4f2e4a87 | ||
|
|
c907b0ba99 | ||
|
|
02c852e194 | ||
|
|
6e6213a43b | ||
|
|
5379eb046d |
No files matched your search
@@ -1,22 +1,31 @@
|
|||||||
- navigation "Settings sections":
|
- navigation "Settings sections":
|
||||||
- button "General" [pressed]:
|
- button "Account" [pressed]:
|
||||||
- img
|
|
||||||
- paragraph: General
|
|
||||||
- button "Account":
|
|
||||||
- img
|
- img
|
||||||
- paragraph: Account
|
- paragraph: Account
|
||||||
|
- button "Appearance":
|
||||||
|
- img
|
||||||
|
- paragraph: Appearance
|
||||||
|
- button "Messages":
|
||||||
|
- img
|
||||||
|
- paragraph: Messages
|
||||||
- button "Notifications":
|
- button "Notifications":
|
||||||
- img
|
- img
|
||||||
- paragraph: Notifications
|
- paragraph: Notifications
|
||||||
- button "Devices":
|
- button "Calls & audio":
|
||||||
- img
|
- img
|
||||||
- paragraph: Devices
|
- paragraph: Calls & audio
|
||||||
- button "Emojis & Stickers":
|
- button "Privacy & security":
|
||||||
- img
|
- img
|
||||||
- paragraph: Emojis & Stickers
|
- paragraph: Privacy & security
|
||||||
- button "Developer Tools":
|
- button "Data & storage":
|
||||||
- img
|
- img
|
||||||
- paragraph: Developer Tools
|
- paragraph: Data & storage
|
||||||
|
- button "Emojis & stickers":
|
||||||
|
- img
|
||||||
|
- paragraph: Emojis & stickers
|
||||||
|
- button "Advanced":
|
||||||
|
- img
|
||||||
|
- paragraph: Advanced
|
||||||
- button "About":
|
- button "About":
|
||||||
- img
|
- img
|
||||||
- paragraph: About
|
- paragraph: About
|
||||||
@@ -31,7 +31,7 @@ test.describe('key upload recovery (#201)', () => {
|
|||||||
expect(rejected).toBeGreaterThanOrEqual(3);
|
expect(rejected).toBeGreaterThanOrEqual(3);
|
||||||
|
|
||||||
await banner.getByRole('button', { name: 'Details' }).click();
|
await banner.getByRole('button', { name: 'Details' }).click();
|
||||||
await expect(banner).toContainText('Settings → Devices');
|
await expect(banner).toContainText('Settings → Privacy & security');
|
||||||
await expect(banner).toContainText('already exists');
|
await expect(banner).toContainText('already exists');
|
||||||
|
|
||||||
await banner.getByRole('button', { name: /Fix: sign out/ }).click();
|
await banner.getByRole('button', { name: /Fix: sign out/ }).click();
|
||||||
|
|||||||
@@ -415,6 +415,64 @@ test.describe('local homeserver regression', () => {
|
|||||||
.toBe(status);
|
.toBe(status);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('status: applies at once, quick changes fold into one write (slow-save report)', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
let lastOk = 0;
|
||||||
|
const sent: string[] = [];
|
||||||
|
await page.route(/\/presence\/[^/]+\/status/, (route) => {
|
||||||
|
if (route.request().method() !== 'PUT') return route.continue();
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - lastOk < 10_000) {
|
||||||
|
return route.fulfill({
|
||||||
|
status: 429,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({
|
||||||
|
errcode: 'M_LIMIT_EXCEEDED',
|
||||||
|
retry_after_ms: 10_000 - (now - lastOk),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
lastOk = now;
|
||||||
|
sent.push(JSON.parse(route.request().postData() ?? '{}').status_msg ?? '');
|
||||||
|
return route.continue();
|
||||||
|
});
|
||||||
|
await loginUI(page, alice);
|
||||||
|
await page.getByRole('button', { name: 'User Settings' }).click();
|
||||||
|
await page.getByText('Account', { exact: true }).first().click();
|
||||||
|
const input = page.getByLabel('Status message');
|
||||||
|
const save = input.locator('xpath=ancestor::form[1]').getByRole('button', { name: 'Save' });
|
||||||
|
|
||||||
|
// Use up the 10 s budget, then pick three quick statuses in a row.
|
||||||
|
await input.fill(uniq('first '));
|
||||||
|
await save.click();
|
||||||
|
await expect(save).toBeDisabled(); // applied: nothing left to save, no spinner wait
|
||||||
|
const quick = page.getByRole('group', { name: 'Quick statuses' });
|
||||||
|
await quick.getByRole('button', { name: /Lunch/ }).click();
|
||||||
|
await quick.getByRole('button', { name: /Watching/ }).click();
|
||||||
|
await quick.getByRole('button', { name: /AFK/ }).click();
|
||||||
|
await expect(input).toHaveValue('😴 AFK');
|
||||||
|
await expect(save).toBeDisabled();
|
||||||
|
await expect(page.getByText(/Status set\. Sharing it with others/)).toBeVisible();
|
||||||
|
|
||||||
|
await expect
|
||||||
|
.poll(
|
||||||
|
async () =>
|
||||||
|
(
|
||||||
|
await api<{ status_msg?: string }>(
|
||||||
|
'GET',
|
||||||
|
`/_matrix/client/v3/presence/${enc(alice.userId)}/status`,
|
||||||
|
alice.token,
|
||||||
|
)
|
||||||
|
).status_msg,
|
||||||
|
{ timeout: 30_000 },
|
||||||
|
)
|
||||||
|
.toBe('😴 AFK');
|
||||||
|
// The middle choices were superseded while waiting, never sent.
|
||||||
|
expect(sent.filter((m) => /Lunch|Watching/.test(m))).toEqual([]);
|
||||||
|
await expect(page.getByText(/Status set\. Sharing it with others/)).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
test('touch: long-press opens the message action sheet (#166)', async ({ browser }) => {
|
test('touch: long-press opens the message action sheet (#166)', async ({ browser }) => {
|
||||||
const ctx = await browser.newContext({ ...devices['Pixel 7'] });
|
const ctx = await browser.newContext({ ...devices['Pixel 7'] });
|
||||||
const page = await ctx.newPage();
|
const page = await ctx.newPage();
|
||||||
|
|||||||
@@ -75,7 +75,9 @@ test.describe('security nudge (#110, #123)', () => {
|
|||||||
await expect(strip(page)).toHaveCount(0);
|
await expect(strip(page)).toHaveCount(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('no key backup: "Set up key backup" opens Settings → Devices', async ({ page }) => {
|
test('no key backup: "Set up key backup" opens Settings → Privacy & security', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
test.setTimeout(150_000);
|
test.setTimeout(150_000);
|
||||||
await loginUI(page, user);
|
await loginUI(page, user);
|
||||||
await pastGrace(page);
|
await pastGrace(page);
|
||||||
@@ -83,7 +85,7 @@ test.describe('security nudge (#110, #123)', () => {
|
|||||||
const nudge = strip(page);
|
const nudge = strip(page);
|
||||||
await expect(nudge).toContainText("Your encryption keys aren't backed up");
|
await expect(nudge).toContainText("Your encryption keys aren't backed up");
|
||||||
await nudge.getByRole('button', { name: 'Set up' }).click();
|
await nudge.getByRole('button', { name: 'Set up' }).click();
|
||||||
await expect(page.getByText('Device Verification').first()).toBeVisible();
|
await expect(page.getByText('Device verification').first()).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a dismissed announcement no longer hides the nudge (#307)', async ({ page }) => {
|
test('a dismissed announcement no longer hides the nudge (#307)', async ({ page }) => {
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { ensureUser, hsReachable, loginUI, uniq } from './localHs';
|
||||||
|
|
||||||
|
// [Gitea #463] Search across all settings.
|
||||||
|
test.describe('settings search (#463)', () => {
|
||||||
|
test.beforeAll(async () => {
|
||||||
|
test.skip(!(await hsReachable()), 'local homeserver not running');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('finds a setting, opens its page and shows it', async ({ page }) => {
|
||||||
|
test.setTimeout(120_000);
|
||||||
|
const user = await ensureUser(uniq('ss'));
|
||||||
|
await loginUI(page, user);
|
||||||
|
await page.getByRole('button', { name: 'User Settings' }).click();
|
||||||
|
const dialog = page.getByRole('dialog').first();
|
||||||
|
const box = dialog.getByRole('textbox', { name: 'Search settings' });
|
||||||
|
|
||||||
|
// Ctrl+F focuses the box while settings are open (after the dialog has
|
||||||
|
// placed its own initial focus).
|
||||||
|
await expect(box).toBeVisible();
|
||||||
|
await page.waitForTimeout(800);
|
||||||
|
await page.keyboard.press('ControlOrMeta+f');
|
||||||
|
await expect(box).toBeFocused();
|
||||||
|
|
||||||
|
await box.fill('deafen');
|
||||||
|
const results = dialog.getByRole('list', { name: 'Matching settings' });
|
||||||
|
const first = results.getByRole('listitem').first();
|
||||||
|
await expect(first).toContainText('Push to deafen');
|
||||||
|
await expect(first).toContainText('Calls & audio');
|
||||||
|
await expect(dialog.getByRole('navigation', { name: 'Settings sections' })).toBeHidden();
|
||||||
|
await first.click();
|
||||||
|
await expect(dialog.getByText('Calls & audio', { exact: true }).last()).toBeVisible();
|
||||||
|
await expect(dialog.getByText('Push to deafen', { exact: true })).toBeInViewport();
|
||||||
|
await expect(dialog.getByRole('navigation', { name: 'Settings sections' })).toBeVisible();
|
||||||
|
|
||||||
|
// A description word finds it too; Enter picks the top result.
|
||||||
|
await box.fill('utm');
|
||||||
|
await expect(results.getByRole('listitem').first()).toContainText(
|
||||||
|
'Strip tracking parameters from links',
|
||||||
|
);
|
||||||
|
await box.press('Enter');
|
||||||
|
await expect(dialog.getByText('Strip tracking parameters from links')).toBeInViewport();
|
||||||
|
|
||||||
|
// No match, then Esc clears.
|
||||||
|
await box.fill('zzzz-nothing');
|
||||||
|
await expect(dialog.getByText(/No settings match/)).toBeVisible();
|
||||||
|
await box.press('Escape');
|
||||||
|
await expect(box).toHaveValue('');
|
||||||
|
await expect(dialog).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { test, expect, Page } from '@playwright/test';
|
||||||
|
import { HS, PASSWORD, api, ensureUser, hsReachable, loginUI, uniq } from './localHs';
|
||||||
|
|
||||||
|
// [Gitea #113] Sessions unused for 90+ days: a nudge (after the device-security
|
||||||
|
// one), and Review opens Settings → Devices with them ticked for sign-out.
|
||||||
|
// Synapse won't backdate last-seen, so the session list is served with one
|
||||||
|
// real extra session made 120 days old.
|
||||||
|
const DAY = 86_400_000;
|
||||||
|
|
||||||
|
const strip = (page: Page, text: RegExp) => page.getByRole('status').filter({ hasText: text });
|
||||||
|
|
||||||
|
async function pastGrace(page: Page) {
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const { deviceId } = JSON.parse(localStorage.getItem('cinny_session_v1') ?? '{}');
|
||||||
|
localStorage.setItem(
|
||||||
|
`lotus-security-nudge-${deviceId}`,
|
||||||
|
JSON.stringify({ firstSeen: Date.now() - 2 * 86_400_000, dismissals: {} }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await page.reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function settled(page: Page) {
|
||||||
|
await page
|
||||||
|
.getByText('Connecting...')
|
||||||
|
.first()
|
||||||
|
.waitFor({ timeout: 30_000 })
|
||||||
|
.catch(() => undefined);
|
||||||
|
await page.getByText('Connecting...').first().waitFor({ state: 'detached', timeout: 90_000 });
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe('stale sessions (#113)', () => {
|
||||||
|
test.beforeAll(async () => {
|
||||||
|
test.skip(!(await hsReachable()), 'local homeserver not running');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('nudge after the security one, Review ticks the old session, sign-out works', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
test.setTimeout(180_000);
|
||||||
|
const user = await ensureUser(uniq('ss'));
|
||||||
|
// Two extra sessions: one we'll make look 4 months old, one recent.
|
||||||
|
const login = (device: string) =>
|
||||||
|
api<{ device_id: string }>('POST', '/_matrix/client/v3/login', undefined, {
|
||||||
|
type: 'm.login.password',
|
||||||
|
identifier: { type: 'm.id.user', user: user.localpart },
|
||||||
|
password: PASSWORD,
|
||||||
|
device_id: device,
|
||||||
|
initial_device_display_name: device,
|
||||||
|
});
|
||||||
|
await login('OLDLAPTOP');
|
||||||
|
await login('RECENTPHONE');
|
||||||
|
await page.route(/\/_matrix\/client\/v3\/devices(\?.*)?$/, async (route) => {
|
||||||
|
const res = await route.fetch();
|
||||||
|
const body = await res.json();
|
||||||
|
for (const d of body.devices ?? []) {
|
||||||
|
if (d.device_id === 'OLDLAPTOP') d.last_seen_ts = Date.now() - 120 * DAY;
|
||||||
|
else d.last_seen_ts = Date.now() - DAY;
|
||||||
|
}
|
||||||
|
await route.fulfill({ response: res, json: body });
|
||||||
|
});
|
||||||
|
|
||||||
|
await loginUI(page, user);
|
||||||
|
await pastGrace(page);
|
||||||
|
await settled(page);
|
||||||
|
|
||||||
|
// A fresh account has no key backup: that nudge comes first.
|
||||||
|
const security = strip(page, /encryption keys/);
|
||||||
|
await expect(security).toBeVisible({ timeout: 30_000 });
|
||||||
|
await security.getByRole('button', { name: 'Not now' }).click();
|
||||||
|
|
||||||
|
const stale = strip(page, /a session you haven't used in 3 months/);
|
||||||
|
await expect(stale).toBeVisible({ timeout: 30_000 });
|
||||||
|
await stale.getByRole('button', { name: 'Review' }).click();
|
||||||
|
|
||||||
|
const dialog = page.getByRole('dialog').first();
|
||||||
|
await expect(dialog.getByText('Inactive for 3+ months')).toHaveCount(1);
|
||||||
|
await expect(dialog.getByText(/Logout from selected devices\. \(1 selected\)/)).toBeVisible();
|
||||||
|
|
||||||
|
// The sticky "Logout from selected devices" bar comes last.
|
||||||
|
await dialog.getByRole('button', { name: 'Logout', exact: true }).last().click();
|
||||||
|
await page.locator('input[name="passwordInput"]').fill(PASSWORD);
|
||||||
|
await page.getByRole('button', { name: 'Continue' }).click();
|
||||||
|
await expect(dialog.getByText(/Logout from selected devices/)).toHaveCount(0, {
|
||||||
|
timeout: 30_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { devices } = await api<{ devices: { device_id: string }[] }>(
|
||||||
|
'GET',
|
||||||
|
'/_matrix/client/v3/devices',
|
||||||
|
user.token,
|
||||||
|
);
|
||||||
|
const ids = devices.map((d) => d.device_id);
|
||||||
|
expect(ids).not.toContain('OLDLAPTOP');
|
||||||
|
expect(ids).toContain('RECENTPHONE');
|
||||||
|
expect(HS).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import { test, expect } from '@playwright/test';
|
||||||
|
import { api, ensureUser, hsReachable, loginUI, uniq } from './localHs';
|
||||||
|
|
||||||
|
// [Gitea #114] Export / import "your data": a round trip through the file, the
|
||||||
|
// merge summary, and the keep-mine / use-the-file's choice.
|
||||||
|
const enc = encodeURIComponent;
|
||||||
|
|
||||||
|
test.describe('your data (#114)', () => {
|
||||||
|
test.beforeAll(async () => {
|
||||||
|
test.skip(!(await hsReachable()), 'local homeserver not running');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('export, change things, import merges with the chosen conflict rule', async ({ page }) => {
|
||||||
|
test.setTimeout(150_000);
|
||||||
|
const user = await ensureUser(uniq('yd'));
|
||||||
|
const put = (type: string, content: unknown) =>
|
||||||
|
api(
|
||||||
|
'PUT',
|
||||||
|
`/_matrix/client/v3/user/${enc(user.userId)}/account_data/${type}`,
|
||||||
|
user.token,
|
||||||
|
content,
|
||||||
|
);
|
||||||
|
const get = (type: string) =>
|
||||||
|
api<Record<string, unknown>>(
|
||||||
|
'GET',
|
||||||
|
`/_matrix/client/v3/user/${enc(user.userId)}/account_data/${type}`,
|
||||||
|
user.token,
|
||||||
|
);
|
||||||
|
const bm = (eventId: string) => ({ roomId: '!r:localhost', eventId, savedAt: 1 });
|
||||||
|
await put('io.lotus.bookmarks', { bookmarks: [bm('$one'), bm('$two')] });
|
||||||
|
await put('io.lotus.user_notes', { '@friend:localhost': 'met at the LAN party' });
|
||||||
|
|
||||||
|
await loginUI(page, user);
|
||||||
|
await page
|
||||||
|
.getByText('Connecting...')
|
||||||
|
.first()
|
||||||
|
.waitFor({ state: 'detached', timeout: 90_000 })
|
||||||
|
.catch(() => undefined);
|
||||||
|
const openGeneral = async () => {
|
||||||
|
await page.getByRole('button', { name: 'User Settings' }).click();
|
||||||
|
await page.getByRole('dialog').getByText('Data & storage', { exact: true }).first().click();
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByText('Your data', { exact: true })
|
||||||
|
.scrollIntoViewIfNeeded();
|
||||||
|
};
|
||||||
|
await openGeneral();
|
||||||
|
|
||||||
|
// Export.
|
||||||
|
const [download] = await Promise.all([
|
||||||
|
page.waitForEvent('download'),
|
||||||
|
page.getByRole('dialog').getByRole('button', { name: 'Export', exact: true }).click(),
|
||||||
|
]);
|
||||||
|
const path = await download.path();
|
||||||
|
const file = JSON.parse(fs.readFileSync(path!, 'utf8'));
|
||||||
|
expect(file.format).toBe('lotus-chat-data');
|
||||||
|
expect(file.accountData['io.lotus.bookmarks'].bookmarks).toHaveLength(2);
|
||||||
|
expect(file.local.settings).toBeTruthy();
|
||||||
|
|
||||||
|
// Lose a bookmark, change the note.
|
||||||
|
await put('io.lotus.bookmarks', { bookmarks: [bm('$one')] });
|
||||||
|
await put('io.lotus.user_notes', { '@friend:localhost': 'changed my mind' });
|
||||||
|
await page.waitForTimeout(3000); // let sync deliver the new account data
|
||||||
|
|
||||||
|
const importFile = async () => {
|
||||||
|
await page
|
||||||
|
.locator('input[type="file"][aria-label="Lotus Chat data file"]')
|
||||||
|
.setInputFiles(path!);
|
||||||
|
await expect(page.getByRole('region', { name: 'Import summary' })).toBeVisible();
|
||||||
|
};
|
||||||
|
await importFile();
|
||||||
|
const summary = page.getByRole('region', { name: 'Import summary' });
|
||||||
|
await expect(summary).toContainText('Bookmarks: 1 new');
|
||||||
|
await expect(summary).toContainText('Private notes about people: 1 differ');
|
||||||
|
|
||||||
|
// Keep mine: the bookmark comes back, the note stays as it is now.
|
||||||
|
await summary.getByRole('button', { name: 'Import', exact: true }).click();
|
||||||
|
await expect(page.getByText('Imported.')).toBeVisible({ timeout: 20_000 });
|
||||||
|
expect(((await get('io.lotus.bookmarks')).bookmarks as unknown[]).length).toBe(2);
|
||||||
|
expect((await get('io.lotus.user_notes'))['@friend:localhost']).toBe('changed my mind');
|
||||||
|
|
||||||
|
// Again, using the file's: the note goes back.
|
||||||
|
await page.waitForTimeout(2000);
|
||||||
|
await importFile();
|
||||||
|
await summary.getByText("Use the file's").click();
|
||||||
|
await summary.getByRole('button', { name: 'Import', exact: true }).click();
|
||||||
|
await expect(page.getByText('Imported.')).toBeVisible({ timeout: 20_000 });
|
||||||
|
expect((await get('io.lotus.user_notes'))['@friend:localhost']).toBe('met at the LAN party');
|
||||||
|
|
||||||
|
// Wrong files are refused with a plain message.
|
||||||
|
fs.writeFileSync(`${path}.bad`, '{"format":"something-else"}');
|
||||||
|
await page
|
||||||
|
.locator('input[type="file"][aria-label="Lotus Chat data file"]')
|
||||||
|
.setInputFiles(`${path}.bad`);
|
||||||
|
await expect(page.getByText("This isn't a Lotus Chat data file.")).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
Generated
+26
-19
@@ -45,7 +45,7 @@
|
|||||||
"html-react-parser": "6.1.2",
|
"html-react-parser": "6.1.2",
|
||||||
"i18next": "26.2.0",
|
"i18next": "26.2.0",
|
||||||
"i18next-browser-languagedetector": "8.2.1",
|
"i18next-browser-languagedetector": "8.2.1",
|
||||||
"i18next-http-backend": "4.0.2",
|
"i18next-http-backend": "4.0.3",
|
||||||
"immer": "11.1.8",
|
"immer": "11.1.8",
|
||||||
"is-hotkey": "0.2.0",
|
"is-hotkey": "0.2.0",
|
||||||
"jotai": "2.20.0",
|
"jotai": "2.20.0",
|
||||||
@@ -70,7 +70,7 @@
|
|||||||
"react-i18next": "17.0.8",
|
"react-i18next": "17.0.8",
|
||||||
"react-range": "1.10.0",
|
"react-range": "1.10.0",
|
||||||
"react-router-dom": "7.18.3",
|
"react-router-dom": "7.18.3",
|
||||||
"sanitize-html": "2.17.7",
|
"sanitize-html": "2.18.1",
|
||||||
"slate": "0.124.1",
|
"slate": "0.124.1",
|
||||||
"slate-dom": "0.124.1",
|
"slate-dom": "0.124.1",
|
||||||
"slate-history": "0.113.1",
|
"slate-history": "0.113.1",
|
||||||
@@ -6057,6 +6057,7 @@
|
|||||||
"version": "4.3.1",
|
"version": "4.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
|
||||||
"integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
|
"integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
|
||||||
|
"dev": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
@@ -8168,9 +8169,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/i18next-http-backend": {
|
"node_modules/i18next-http-backend": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-4.0.3.tgz",
|
||||||
"integrity": "sha512-oay62dIB2kL7+WHzoUXBjWfL3+mwijD3pQkQkIEaRLhy6kjXxUhrRenV0gInwlCASAaJaDy94+XvYizK+cAGdA==",
|
"integrity": "sha512-B5GJysCsJwqiDQRpUcikWsut82Vmekix58WIyiCpYtxaZ/wY8kwJCicMRvVcMoIa1x84siiRl5vBt6iCBVO6zg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
@@ -8704,9 +8705,10 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/is-plain-object": {
|
"node_modules/is-plain-object": {
|
||||||
"version": "5.0.0",
|
"version": "5.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.1.0.tgz",
|
||||||
"integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==",
|
"integrity": "sha512-bUi/yjmtKYcRVUtWRGr0UA6xEFh2I6zWUwMrUXB3s7bmYCaZ8a+0ZsTRkrawh/mzlSD1Y0Ph8bp/U+TvBpWDNw==",
|
||||||
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
@@ -9207,14 +9209,20 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/launder": {
|
"node_modules/launder": {
|
||||||
"version": "1.7.1",
|
"version": "1.7.2",
|
||||||
"resolved": "https://registry.npmjs.org/launder/-/launder-1.7.1.tgz",
|
"resolved": "https://registry.npmjs.org/launder/-/launder-1.7.2.tgz",
|
||||||
"integrity": "sha512-mU6WRz5EusL9ZZuiZ5SO4Y6C0P9PAUR9iwdb6bzj4KDihm28DiHFw+/yk9DBH4f+Pv1wuzQ4e2jV3oQ7mkIqvw==",
|
"integrity": "sha512-DLg3HPnHUfBi5/MxMLmJD12dmlMpFEC2HgMW6vkZ/9JR0RU00kXoRGvDxAvFmdO0o610OA77i4FgNTLucmhDVg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"dayjs": "^1.11.7"
|
"dayjs": "^1.11.23"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/launder/node_modules/dayjs": {
|
||||||
|
"version": "1.11.23",
|
||||||
|
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
|
||||||
|
"integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/leven": {
|
"node_modules/leven": {
|
||||||
"version": "3.1.0",
|
"version": "3.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
|
||||||
@@ -11706,18 +11714,17 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/sanitize-html": {
|
"node_modules/sanitize-html": {
|
||||||
"version": "2.17.7",
|
"version": "2.18.1",
|
||||||
"resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.17.7.tgz",
|
"resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.18.1.tgz",
|
||||||
"integrity": "sha512-PGtEkc9cbnedU3s9TmzDbpsZ8w086g/0Q8k8/oIO1NLNU3i5k9yn835CrjJSajp1KMmkisbO1qPXxNKO3welAg==",
|
"integrity": "sha512-2X5lC8fYla8YaT8g73Nj+HcLWXan5dLyCWLgVvaOmfw7JI78IRsyNtIDytTHdn7hBQbIkCah7Zbmd5jabzeDig==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"deepmerge": "^4.2.2",
|
|
||||||
"escape-string-regexp": "^4.0.0",
|
"escape-string-regexp": "^4.0.0",
|
||||||
"htmlparser2": "^12.0.0",
|
"htmlparser2": "^12.0.0",
|
||||||
"is-plain-object": "^5.0.0",
|
"is-plain-object": "^5.1.0",
|
||||||
"launder": "^1.7.1",
|
"launder": "^1.7.2",
|
||||||
"parse-srcset": "^1.0.2",
|
"parse-srcset": "^1.0.2",
|
||||||
"postcss": "^8.3.11"
|
"postcss": "^8.5.27"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22.12.0"
|
"node": ">=22.12.0"
|
||||||
|
|||||||
+2
-2
@@ -72,7 +72,7 @@
|
|||||||
"html-react-parser": "6.1.2",
|
"html-react-parser": "6.1.2",
|
||||||
"i18next": "26.2.0",
|
"i18next": "26.2.0",
|
||||||
"i18next-browser-languagedetector": "8.2.1",
|
"i18next-browser-languagedetector": "8.2.1",
|
||||||
"i18next-http-backend": "4.0.2",
|
"i18next-http-backend": "4.0.3",
|
||||||
"immer": "11.1.8",
|
"immer": "11.1.8",
|
||||||
"is-hotkey": "0.2.0",
|
"is-hotkey": "0.2.0",
|
||||||
"jotai": "2.20.0",
|
"jotai": "2.20.0",
|
||||||
@@ -97,7 +97,7 @@
|
|||||||
"react-i18next": "17.0.8",
|
"react-i18next": "17.0.8",
|
||||||
"react-range": "1.10.0",
|
"react-range": "1.10.0",
|
||||||
"react-router-dom": "7.18.3",
|
"react-router-dom": "7.18.3",
|
||||||
"sanitize-html": "2.17.7",
|
"sanitize-html": "2.18.1",
|
||||||
"slate": "0.124.1",
|
"slate": "0.124.1",
|
||||||
"slate-dom": "0.124.1",
|
"slate-dom": "0.124.1",
|
||||||
"slate-history": "0.113.1",
|
"slate-history": "0.113.1",
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ import {
|
|||||||
useCallThemeSync,
|
useCallThemeSync,
|
||||||
useCallStart,
|
useCallStart,
|
||||||
} from '../hooks/useCallEmbed';
|
} from '../hooks/useCallEmbed';
|
||||||
import { callChatAtom, callEmbedAtom } from '../state/callEmbed';
|
import { callChatAtom, callEmbedAtom, immersiveCallAtom } from '../state/callEmbed';
|
||||||
import { toastQueueAtom } from '../state/toast';
|
import { toastQueueAtom } from '../state/toast';
|
||||||
import { CallEmbed, useCallControlState, useScreensharePromptOpen } from '../plugins/call';
|
import { CallEmbed, useCallControlState, useScreensharePromptOpen } from '../plugins/call';
|
||||||
import { hangupCallAndWait } from '../plugins/call/hangup';
|
import { hangupCallAndWait } from '../plugins/call/hangup';
|
||||||
@@ -954,6 +954,7 @@ export function CallEmbedProvider({ children }: CallEmbedProviderProps) {
|
|||||||
const inCallRoom = callEmbed && selectedRoom === callEmbed.roomId;
|
const inCallRoom = callEmbed && selectedRoom === callEmbed.roomId;
|
||||||
const callActive = callEmbed && joined;
|
const callActive = callEmbed && joined;
|
||||||
const callVisible = inCallRoom && callActive && !chatOnlyView;
|
const callVisible = inCallRoom && callActive && !chatOnlyView;
|
||||||
|
const immersiveCall = useAtomValue(immersiveCallAtom);
|
||||||
const pipMode = callActive && !inCallRoom;
|
const pipMode = callActive && !inCallRoom;
|
||||||
const pipPromptOpen = useScreensharePromptOpen(callEmbed?.control);
|
const pipPromptOpen = useScreensharePromptOpen(callEmbed?.control);
|
||||||
const { navigateRoom } = useRoomNavigate();
|
const { navigateRoom } = useRoomNavigate();
|
||||||
@@ -1458,7 +1459,13 @@ export function CallEmbedProvider({ children }: CallEmbedProviderProps) {
|
|||||||
...(pipMode
|
...(pipMode
|
||||||
? { background: color.Surface.Container }
|
? { background: color.Surface.Container }
|
||||||
: callVisible
|
: callVisible
|
||||||
? wallpaperStyle
|
? {
|
||||||
|
// [Gitea #126] Full screen: the frame is transparent, so give
|
||||||
|
// it an opaque base under the wallpaper or the room's
|
||||||
|
// sidebar / call bar show through.
|
||||||
|
...(immersiveCall ? { backgroundColor: color.Background.Container } : {}),
|
||||||
|
...wallpaperStyle,
|
||||||
|
}
|
||||||
: {}),
|
: {}),
|
||||||
}}
|
}}
|
||||||
ref={callEmbedRef}
|
ref={callEmbedRef}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import { useModalStyle } from '../hooks/useModalStyle';
|
|||||||
* cinny-desktop #5: the first time the window is closed, ask whether Lotus Chat
|
* cinny-desktop #5: the first time the window is closed, ask whether Lotus Chat
|
||||||
* should keep running in the tray (calls, messages, notifications) or quit —
|
* should keep running in the tray (calls, messages, notifications) or quit —
|
||||||
* and, in the same moment, whether it should start when you sign in. Asked
|
* and, in the same moment, whether it should start when you sign in. Asked
|
||||||
* once; changeable in Settings → General. The native side sends
|
* once; changeable in Settings → Desktop. The native side sends
|
||||||
* `lotus-close-requested` only while the choice is still "ask", and never
|
* `lotus-close-requested` only while the choice is still "ask", and never
|
||||||
* during a call (a call always goes to the tray).
|
* during a call (a call always goes to the tray).
|
||||||
*/
|
*/
|
||||||
@@ -149,7 +149,7 @@ export function CloseBehaviorPrompt() {
|
|||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
<Text size="T200" priority="300">
|
<Text size="T200" priority="300">
|
||||||
You can change this in Settings → General.
|
You can change this in Settings → Desktop.
|
||||||
</Text>
|
</Text>
|
||||||
</Box>
|
</Box>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
|
|||||||
import { ModalWide } from '../../../styles/Modal.css';
|
import { ModalWide } from '../../../styles/Modal.css';
|
||||||
import { validBlurHash } from '../../../utils/blurHash';
|
import { validBlurHash } from '../../../utils/blurHash';
|
||||||
import { useNearViewport } from '../../../hooks/useNearViewport';
|
import { useNearViewport } from '../../../hooks/useNearViewport';
|
||||||
|
import { whenMediaAuthReady } from '../../../../sw-session';
|
||||||
|
|
||||||
type RenderViewerProps = {
|
type RenderViewerProps = {
|
||||||
src: string;
|
src: string;
|
||||||
@@ -115,13 +116,24 @@ export const ImageContent = as<'div', ImageContentProps>(
|
|||||||
const handleLoad = () => {
|
const handleLoad = () => {
|
||||||
setLoad(true);
|
setLoad(true);
|
||||||
};
|
};
|
||||||
|
// An image requested before the service worker controls the page goes out
|
||||||
|
// without the access token and fails (first visit, just after an update).
|
||||||
|
// Retry once by itself when that's ready; only then offer "Retry".
|
||||||
|
const [attempt, setAttempt] = useState(0);
|
||||||
|
const autoRetried = useRef(false);
|
||||||
const handleError = () => {
|
const handleError = () => {
|
||||||
setLoad(false);
|
setLoad(false);
|
||||||
|
if (!autoRetried.current && !encInfo) {
|
||||||
|
autoRetried.current = true;
|
||||||
|
whenMediaAuthReady().then(() => setAttempt((n) => n + 1));
|
||||||
|
return;
|
||||||
|
}
|
||||||
setError(true);
|
setError(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRetry = () => {
|
const handleRetry = () => {
|
||||||
setError(false);
|
setError(false);
|
||||||
|
setAttempt((n) => n + 1);
|
||||||
loadSrc();
|
loadSrc();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -182,7 +194,7 @@ export const ImageContent = as<'div', ImageContentProps>(
|
|||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
{srcState.status === AsyncStatus.Success && (
|
{srcState.status === AsyncStatus.Success && (
|
||||||
<Box className={classNames(css.AbsoluteContainer, blurred && css.Blur)}>
|
<Box key={attempt} className={classNames(css.AbsoluteContainer, blurred && css.Blur)}>
|
||||||
{renderImage({
|
{renderImage({
|
||||||
alt: body,
|
alt: body,
|
||||||
title: body,
|
title: body,
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import { useVoiceChannelFull } from '../../hooks/useVoiceChannelFull';
|
|||||||
import { CallMemberRenderer } from './CallMemberCard';
|
import { CallMemberRenderer } from './CallMemberCard';
|
||||||
import * as css from './styles.css';
|
import * as css from './styles.css';
|
||||||
import { CallControls } from './CallControls';
|
import { CallControls } from './CallControls';
|
||||||
|
import { ImmersiveCallOverlay } from './ImmersiveCallOverlay';
|
||||||
import { useLivekitSupport } from '../../hooks/useLivekitSupport';
|
import { useLivekitSupport } from '../../hooks/useLivekitSupport';
|
||||||
import { CallsUnavailableMessage } from './CallsUnavailable';
|
import { CallsUnavailableMessage } from './CallsUnavailable';
|
||||||
import { webRTCSupported } from '../../utils/rtc';
|
import { webRTCSupported } from '../../utils/rtc';
|
||||||
@@ -198,10 +199,24 @@ function CallLoadErrorMessage() {
|
|||||||
type CallJoinedProps = {
|
type CallJoinedProps = {
|
||||||
containerRef: RefObject<HTMLDivElement>;
|
containerRef: RefObject<HTMLDivElement>;
|
||||||
joined: boolean;
|
joined: boolean;
|
||||||
|
/** [Gitea #126] Full screen: controls float over the call instead. */
|
||||||
|
onExitImmersive?: () => void;
|
||||||
};
|
};
|
||||||
function CallJoined({ joined, containerRef }: CallJoinedProps) {
|
function CallJoined({ joined, containerRef, onExitImmersive }: CallJoinedProps) {
|
||||||
const callEmbed = useCallEmbed();
|
const callEmbed = useCallEmbed();
|
||||||
|
|
||||||
|
if (onExitImmersive) {
|
||||||
|
return (
|
||||||
|
<Box grow="Yes" direction="Column" style={{ position: 'relative' }}>
|
||||||
|
<Box grow="Yes" ref={containerRef} />
|
||||||
|
{callEmbed && joined && (
|
||||||
|
<ImmersiveCallOverlay callEmbed={callEmbed} onExit={onExitImmersive} />
|
||||||
|
)}
|
||||||
|
{callEmbed && joined && <LotusDecorationPusher callEmbed={callEmbed} />}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box grow="Yes" direction="Column">
|
<Box grow="Yes" direction="Column">
|
||||||
<Box grow="Yes" ref={containerRef} />
|
<Box grow="Yes" ref={containerRef} />
|
||||||
@@ -212,7 +227,7 @@ function CallJoined({ joined, containerRef }: CallJoinedProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CallView() {
|
export function CallView({ onExitImmersive }: { onExitImmersive?: () => void } = {}) {
|
||||||
const room = useRoom();
|
const room = useRoom();
|
||||||
const callContainerRef = useRef<HTMLDivElement>(null) as React.RefObject<HTMLDivElement>;
|
const callContainerRef = useRef<HTMLDivElement>(null) as React.RefObject<HTMLDivElement>;
|
||||||
useCallEmbedPlacementSync(callContainerRef);
|
useCallEmbedPlacementSync(callContainerRef);
|
||||||
@@ -227,6 +242,26 @@ export function CallView() {
|
|||||||
// made it into the call (a hung iframe / blank spinner otherwise).
|
// made it into the call (a hung iframe / blank spinner otherwise).
|
||||||
const showLoadError = isCurrentRoom && !currentJoined && Boolean(loadError);
|
const showLoadError = isCurrentRoom && !currentJoined && Boolean(loadError);
|
||||||
|
|
||||||
|
if (onExitImmersive && currentJoined) {
|
||||||
|
// [Gitea #126] Cover the screen with a transparent layer above the call
|
||||||
|
// frame: the frame follows the placeholder (useCallEmbedPlacementSync), so
|
||||||
|
// it goes full screen too; the layer only takes touches on its own
|
||||||
|
// tap-catcher / controls, so the call underneath stays usable.
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
inset: 0,
|
||||||
|
zIndex: 10,
|
||||||
|
pointerEvents: 'none',
|
||||||
|
paddingTop: 'env(safe-area-inset-top)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CallJoined joined containerRef={callContainerRef} onExitImmersive={onExitImmersive} />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
className={ContainerColor({ variant: 'Surface' })}
|
className={ContainerColor({ variant: 'Surface' })}
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { useSetAtom } from 'jotai';
|
||||||
|
import { Box, Button, Icon, Icons, Text, config, toRem } from 'folds';
|
||||||
|
import { CallEmbed } from '../../plugins/call';
|
||||||
|
import { CallControls } from './CallControls';
|
||||||
|
import { callChatAtom } from '../../state/callEmbed';
|
||||||
|
import { CONTROLS_AUTOHIDE_MS, wantsBrowserFullscreen } from './landscapeCall';
|
||||||
|
|
||||||
|
const isStandalone = (): boolean =>
|
||||||
|
window.matchMedia?.('(display-mode: standalone)').matches ||
|
||||||
|
(navigator as { standalone?: boolean }).standalone === true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [Gitea #126] Full-screen call controls. Taps inside the call frame never
|
||||||
|
* reach us, so while the controls are hidden a transparent layer covers the
|
||||||
|
* call: the first tap shows them (and is otherwise swallowed, as in native
|
||||||
|
* video apps); with them up the layer is gone, so the call stays usable. They
|
||||||
|
* hide again after a few seconds without a touch. The first tap in an Android
|
||||||
|
* browser tab also enters the browser's own full screen (hides the address
|
||||||
|
* bar); it is left again when this unmounts (rotate back, hang up, exit).
|
||||||
|
*/
|
||||||
|
export function ImmersiveCallOverlay({
|
||||||
|
callEmbed,
|
||||||
|
onExit,
|
||||||
|
}: {
|
||||||
|
callEmbed: CallEmbed;
|
||||||
|
onExit: () => void;
|
||||||
|
}) {
|
||||||
|
const [shown, setShown] = useState(false);
|
||||||
|
const timer = useRef<number | undefined>(undefined);
|
||||||
|
const enteredFullscreen = useRef(false);
|
||||||
|
const setChat = useSetAtom(callChatAtom);
|
||||||
|
|
||||||
|
const armHide = useCallback(() => {
|
||||||
|
window.clearTimeout(timer.current);
|
||||||
|
timer.current = window.setTimeout(() => setShown(false), CONTROLS_AUTOHIDE_MS);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
window.clearTimeout(timer.current);
|
||||||
|
if (enteredFullscreen.current && document.fullscreenElement === document.documentElement) {
|
||||||
|
document.exitFullscreen().catch(() => undefined);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const reveal = () => {
|
||||||
|
if (
|
||||||
|
wantsBrowserFullscreen({
|
||||||
|
userAgent: navigator.userAgent,
|
||||||
|
standalone: isStandalone(),
|
||||||
|
fullscreenEnabled: !!document.fullscreenEnabled,
|
||||||
|
alreadyFullscreen: !!document.fullscreenElement,
|
||||||
|
})
|
||||||
|
) {
|
||||||
|
document.documentElement
|
||||||
|
.requestFullscreen({ navigationUI: 'hide' })
|
||||||
|
.then(() => {
|
||||||
|
enteredFullscreen.current = true;
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
}
|
||||||
|
setShown(true);
|
||||||
|
armHide();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!shown) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
aria-label="Show call controls"
|
||||||
|
onClick={reveal}
|
||||||
|
onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && reveal()}
|
||||||
|
style={{ position: 'absolute', inset: 0, pointerEvents: 'auto' }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
direction="Column"
|
||||||
|
// Any touch on the controls keeps them up a little longer.
|
||||||
|
onPointerDown={armHide}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
pointerEvents: 'auto',
|
||||||
|
paddingLeft: 'env(safe-area-inset-left)',
|
||||||
|
paddingRight: 'env(safe-area-inset-right)',
|
||||||
|
paddingBottom: 'env(safe-area-inset-bottom)',
|
||||||
|
background: 'linear-gradient(to top, rgba(0,0,0,0.7), rgba(0,0,0,0))',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
justifyContent="End"
|
||||||
|
gap="200"
|
||||||
|
style={{ padding: `${config.space.S200} ${config.space.S300} 0` }}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
radii="Pill"
|
||||||
|
before={<Icon size="100" src={Icons.Message} />}
|
||||||
|
onClick={() => setChat(true)}
|
||||||
|
>
|
||||||
|
<Text size="B300">Chat</Text>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
radii="Pill"
|
||||||
|
before={<Icon size="100" src={Icons.Cross} />}
|
||||||
|
onClick={onExit}
|
||||||
|
style={{ minWidth: toRem(40) }}
|
||||||
|
>
|
||||||
|
<Text size="B300">Exit full screen</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
<CallControls callEmbed={callEmbed} />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { shouldGoImmersive, wantsBrowserFullscreen } from './landscapeCall';
|
||||||
|
|
||||||
|
const base = { landscapePhone: true, joinedHere: true, chatOpen: false, dismissed: false };
|
||||||
|
|
||||||
|
test('[#126] full screen only for a joined call on a sideways phone', () => {
|
||||||
|
assert.equal(shouldGoImmersive(base), true);
|
||||||
|
assert.equal(shouldGoImmersive({ ...base, landscapePhone: false }), false, 'upright / tablet');
|
||||||
|
assert.equal(shouldGoImmersive({ ...base, joinedHere: false }), false, 'prescreen / other room');
|
||||||
|
assert.equal(shouldGoImmersive({ ...base, chatOpen: true }), false, 'chat open');
|
||||||
|
assert.equal(shouldGoImmersive({ ...base, dismissed: true }), false, 'user exited');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[#126] browser full screen only in an Android browser tab', () => {
|
||||||
|
const env = {
|
||||||
|
userAgent: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) Chrome/140 Mobile',
|
||||||
|
standalone: false,
|
||||||
|
fullscreenEnabled: true,
|
||||||
|
alreadyFullscreen: false,
|
||||||
|
};
|
||||||
|
assert.equal(wantsBrowserFullscreen(env), true);
|
||||||
|
assert.equal(wantsBrowserFullscreen({ ...env, standalone: true }), false, 'installed app');
|
||||||
|
assert.equal(
|
||||||
|
wantsBrowserFullscreen({
|
||||||
|
...env,
|
||||||
|
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0) Safari',
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
'iPhone',
|
||||||
|
);
|
||||||
|
assert.equal(wantsBrowserFullscreen({ ...env, alreadyFullscreen: true }), false);
|
||||||
|
assert.equal(wantsBrowserFullscreen({ ...env, fullscreenEnabled: false }), false);
|
||||||
|
});
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
/**
|
||||||
|
* [Gitea #126] Phone turned sideways in a call: the call takes the whole
|
||||||
|
* screen. A phone in landscape is ~840px wide (the "Tablet" size class), so
|
||||||
|
* the trigger is the shape of the screen, not the size class: landscape, at
|
||||||
|
* most 500px tall, touch input. Tablets and desktops never match.
|
||||||
|
*/
|
||||||
|
export const LANDSCAPE_PHONE_QUERY =
|
||||||
|
'(orientation: landscape) and (max-height: 500px) and (pointer: coarse)';
|
||||||
|
|
||||||
|
/** Controls hide again after this long without a touch on them. */
|
||||||
|
export const CONTROLS_AUTOHIDE_MS = 4000;
|
||||||
|
|
||||||
|
export type ImmersiveInputs = {
|
||||||
|
landscapePhone: boolean;
|
||||||
|
/** This room's call is the one we are in, and we have joined it. */
|
||||||
|
joinedHere: boolean;
|
||||||
|
/** The in-call chat is open (it replaces the call on small screens). */
|
||||||
|
chatOpen: boolean;
|
||||||
|
/** "Exit full screen" was pressed since the phone was last upright. */
|
||||||
|
dismissed: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Pure: whether the call should be full screen. */
|
||||||
|
export const shouldGoImmersive = (i: ImmersiveInputs): boolean =>
|
||||||
|
i.landscapePhone && i.joinedHere && !i.chatOpen && !i.dismissed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pure: use the browser's own full-screen mode too? Only where an address bar
|
||||||
|
* takes room: an Android browser tab (not the installed app / iOS, which have
|
||||||
|
* none or don't support it), when the page isn't already full screen.
|
||||||
|
*/
|
||||||
|
export const wantsBrowserFullscreen = (env: {
|
||||||
|
userAgent: string;
|
||||||
|
standalone: boolean;
|
||||||
|
fullscreenEnabled: boolean;
|
||||||
|
alreadyFullscreen: boolean;
|
||||||
|
}): boolean =>
|
||||||
|
/Android/i.test(env.userAgent) &&
|
||||||
|
!env.standalone &&
|
||||||
|
env.fullscreenEnabled &&
|
||||||
|
!env.alreadyFullscreen;
|
||||||
@@ -48,7 +48,7 @@ export function RoomRetention({ permissions }: RoomRetentionProps) {
|
|||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Message Retention"
|
title="Message Retention"
|
||||||
description="Messages older than this window disappear from the timeline. Each member can opt in to permanently delete their own expired messages in Settings → General; full server-side deletion also requires homeserver retention to be configured."
|
description="Messages older than this window disappear from the timeline. Each member can opt in to permanently delete their own expired messages in Settings → Messages; full server-side deletion also requires homeserver retention to be configured."
|
||||||
>
|
>
|
||||||
<Box gap="200" alignItems="Center" style={{ flexWrap: 'wrap' }}>
|
<Box gap="200" alignItems="Center" style={{ flexWrap: 'wrap' }}>
|
||||||
{RETENTION_PRESETS.map((preset) => {
|
{RETENTION_PRESETS.map((preset) => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useCallback, useEffect, useRef } from 'react';
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { Box, Line } from 'folds';
|
import { Box, Line } from 'folds';
|
||||||
import { useParams } from 'react-router-dom';
|
import { useParams } from 'react-router-dom';
|
||||||
import { isKeyHotkey } from 'is-hotkey';
|
import { isKeyHotkey } from 'is-hotkey';
|
||||||
@@ -11,7 +11,6 @@ import { WidgetsPanel } from './widgets/WidgetsPanel';
|
|||||||
import { widgetsPanelAtom } from '../../state/widgetsPanel';
|
import { widgetsPanelAtom } from '../../state/widgetsPanel';
|
||||||
import { mobileMembersPanelAtom } from '../../state/mobileMembersPanel';
|
import { mobileMembersPanelAtom } from '../../state/mobileMembersPanel';
|
||||||
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
|
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
|
||||||
import { useMediaQuery } from '../../hooks/useMediaQuery';
|
|
||||||
import { useSetting } from '../../state/hooks/settings';
|
import { useSetting } from '../../state/hooks/settings';
|
||||||
import { settingsAtom } from '../../state/settings';
|
import { settingsAtom } from '../../state/settings';
|
||||||
import { PowerLevelsContextProvider, usePowerLevels } from '../../hooks/usePowerLevels';
|
import { PowerLevelsContextProvider, usePowerLevels } from '../../hooks/usePowerLevels';
|
||||||
@@ -21,10 +20,12 @@ import { markAsRead } from '../../utils/notifications';
|
|||||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
import { useRoomMembers } from '../../hooks/useRoomMembers';
|
import { useRoomMembers } from '../../hooks/useRoomMembers';
|
||||||
import { CallView } from '../call/CallView';
|
import { CallView } from '../call/CallView';
|
||||||
|
import { LANDSCAPE_PHONE_QUERY, shouldGoImmersive } from '../call/landscapeCall';
|
||||||
|
import { useMediaQuery } from '../../hooks/useMediaQuery';
|
||||||
import { RoomViewHeader } from './RoomViewHeader';
|
import { RoomViewHeader } from './RoomViewHeader';
|
||||||
import { callChatAtom } from '../../state/callEmbed';
|
import { callChatAtom, immersiveCallAtom } from '../../state/callEmbed';
|
||||||
import { CallChatView } from './CallChatView';
|
import { CallChatView } from './CallChatView';
|
||||||
import { useCallEmbed } from '../../hooks/useCallEmbed';
|
import { useCallEmbed, useCallJoined } from '../../hooks/useCallEmbed';
|
||||||
import { useCallMembers, useCallSession } from '../../hooks/useCall';
|
import { useCallMembers, useCallSession } from '../../hooks/useCall';
|
||||||
import { roomIdToActiveThreadIdAtomFamily } from '../../state/room/thread';
|
import { roomIdToActiveThreadIdAtomFamily } from '../../state/room/thread';
|
||||||
import { threadsListAtom } from '../../state/threadsList';
|
import { threadsListAtom } from '../../state/threadsList';
|
||||||
@@ -57,6 +58,25 @@ export function Room() {
|
|||||||
const powerLevels = usePowerLevels(room);
|
const powerLevels = usePowerLevels(room);
|
||||||
const members = useRoomMembers(mx, room.roomId);
|
const members = useRoomMembers(mx, room.roomId);
|
||||||
const chat = useAtomValue(callChatAtom);
|
const chat = useAtomValue(callChatAtom);
|
||||||
|
// [Gitea #126] Phone turned sideways in this room's call: full screen.
|
||||||
|
const landscapePhone = useMediaQuery(LANDSCAPE_PHONE_QUERY);
|
||||||
|
const joinedAnywhere = useCallJoined(callEmbed);
|
||||||
|
const [immersiveDismissed, setImmersiveDismissed] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
// "Exit full screen" lasts until the phone is upright again.
|
||||||
|
if (!landscapePhone) setImmersiveDismissed(false);
|
||||||
|
}, [landscapePhone]);
|
||||||
|
const setImmersiveCall = useSetAtom(immersiveCallAtom);
|
||||||
|
const immersive = shouldGoImmersive({
|
||||||
|
landscapePhone,
|
||||||
|
joinedHere: joinedAnywhere && callEmbed?.roomId === room.roomId,
|
||||||
|
chatOpen: chat,
|
||||||
|
dismissed: immersiveDismissed,
|
||||||
|
});
|
||||||
|
useEffect(() => {
|
||||||
|
setImmersiveCall(immersive);
|
||||||
|
return () => setImmersiveCall(false);
|
||||||
|
}, [immersive, setImmersiveCall]);
|
||||||
// Hoisted here (instead of inside RoomTimeline) so ThreadPanel/ThreadTimeline —
|
// Hoisted here (instead of inside RoomTimeline) so ThreadPanel/ThreadTimeline —
|
||||||
// rendered as siblings of RoomView, not descendants — share the same computed
|
// rendered as siblings of RoomView, not descendants — share the same computed
|
||||||
// positions instead of falling back to the context default (Gitea #38).
|
// positions instead of falling back to the context default (Gitea #38).
|
||||||
@@ -170,7 +190,8 @@ export function Room() {
|
|||||||
<PowerLevelsContextProvider value={powerLevels}>
|
<PowerLevelsContextProvider value={powerLevels}>
|
||||||
<ReadPositionsContext.Provider value={readPositions}>
|
<ReadPositionsContext.Provider value={readPositions}>
|
||||||
<Box grow="Yes">
|
<Box grow="Yes">
|
||||||
{callView && (screenSize === ScreenSize.Desktop || !chat) && (
|
{immersive && <CallView onExitImmersive={() => setImmersiveDismissed(true)} />}
|
||||||
|
{!immersive && callView && (screenSize === ScreenSize.Desktop || !chat) && (
|
||||||
<Box grow="Yes" direction="Column">
|
<Box grow="Yes" direction="Column">
|
||||||
<RoomViewHeader callView />
|
<RoomViewHeader callView />
|
||||||
<Box grow="Yes">
|
<Box grow="Yes">
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ export function ThreadPanel({ room, threadId, requestClose }: ThreadPanelProps)
|
|||||||
const editor = useEditor();
|
const editor = useEditor();
|
||||||
const thread = useThreadInstance(room, threadId);
|
const thread = useThreadInstance(room, threadId);
|
||||||
const [privateReadReceipts] = useSetting(settingsAtom, 'privateReadReceipts');
|
const [privateReadReceipts] = useSetting(settingsAtom, 'privateReadReceipts');
|
||||||
// "Hide Typing & Read Receipts" must also make thread receipts private (matches markAsRead).
|
// "Hide typing and read receipts" must also make thread receipts private (matches markAsRead).
|
||||||
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
|
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
|
||||||
const fileDropContainerRef = useRef<HTMLDivElement>(null) as React.RefObject<HTMLDivElement>;
|
const fileDropContainerRef = useRef<HTMLDivElement>(null) as React.RefObject<HTMLDivElement>;
|
||||||
|
|
||||||
|
|||||||
@@ -23,8 +23,11 @@ import {
|
|||||||
nudgeFor,
|
nudgeFor,
|
||||||
NudgeRecord,
|
NudgeRecord,
|
||||||
parseNudgeRecord,
|
parseNudgeRecord,
|
||||||
shouldShowNudge,
|
pickNudge,
|
||||||
|
staleSessions,
|
||||||
|
staleSessionsText,
|
||||||
} from '../../utils/securityNudge';
|
} from '../../utils/securityNudge';
|
||||||
|
import { preselectSignOutAtom } from '../../state/staleSessions';
|
||||||
import { StatusStrip } from '../server-status/ServerStatusBanner';
|
import { StatusStrip } from '../server-status/ServerStatusBanner';
|
||||||
|
|
||||||
/** This device's backup connection: undefined until known, then true/false. */
|
/** This device's backup connection: undefined until known, then true/false. */
|
||||||
@@ -40,6 +43,35 @@ const useBackupActive = (crypto: CryptoApi): boolean | undefined => {
|
|||||||
return active;
|
return active;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [Gitea #113] Ids of this account's sessions unused for 90+ days. Fetched
|
||||||
|
* once sync has settled, then hourly; [] until known or on error.
|
||||||
|
*/
|
||||||
|
const useStaleSessionIds = (enabled: boolean): string[] => {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const alive = useAlive();
|
||||||
|
const [ids, setIds] = useState<string[]>([]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enabled) return undefined;
|
||||||
|
const load = () =>
|
||||||
|
mx
|
||||||
|
.getDevices()
|
||||||
|
.then(({ devices }) => {
|
||||||
|
if (alive())
|
||||||
|
setIds(
|
||||||
|
staleSessions(devices, mx.getDeviceId() ?? undefined, Date.now()).map(
|
||||||
|
(d) => d.device_id,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
load();
|
||||||
|
const t = window.setInterval(load, 60 * 60 * 1000);
|
||||||
|
return () => window.clearInterval(t);
|
||||||
|
}, [mx, enabled, alive]);
|
||||||
|
return ids;
|
||||||
|
};
|
||||||
|
|
||||||
const readRecord = (key: string): NudgeRecord => {
|
const readRecord = (key: string): NudgeRecord => {
|
||||||
let raw: string | null = null;
|
let raw: string | null = null;
|
||||||
try {
|
try {
|
||||||
@@ -84,12 +116,15 @@ function SecurityBannerFor({ crypto }: { crypto: CryptoApi }) {
|
|||||||
let deviceVerified: boolean | undefined;
|
let deviceVerified: boolean | undefined;
|
||||||
if (status === VerificationStatus.Verified) deviceVerified = true;
|
if (status === VerificationStatus.Verified) deviceVerified = true;
|
||||||
else if (status === VerificationStatus.Unverified) deviceVerified = false;
|
else if (status === VerificationStatus.Unverified) deviceVerified = false;
|
||||||
const kind = nudgeFor({
|
const securityKind = nudgeFor({
|
||||||
crossSigning,
|
crossSigning,
|
||||||
deviceVerified,
|
deviceVerified,
|
||||||
backupOnServer: backupInfo === undefined ? undefined : backupInfo !== null,
|
backupOnServer: backupInfo === undefined ? undefined : backupInfo !== null,
|
||||||
backupActive,
|
backupActive,
|
||||||
});
|
});
|
||||||
|
const staleIds = useStaleSessionIds(settled);
|
||||||
|
const setPreselect = useSetAtom(preselectSignOutAtom);
|
||||||
|
const kind = pickNudge(securityKind, staleIds.length, record, Date.now());
|
||||||
|
|
||||||
// One strip at a time: outages, maintenance and a lost connection win.
|
// One strip at a time: outages, maintenance and a lost connection win.
|
||||||
// [Gitea #307] Pass what the user dismissed: a dismissed announcement isn't
|
// [Gitea #307] Pass what the user dismissed: a dismissed announcement isn't
|
||||||
@@ -97,10 +132,12 @@ function SecurityBannerFor({ crypto }: { crypto: CryptoApi }) {
|
|||||||
const otherStrip =
|
const otherStrip =
|
||||||
syncLost ||
|
syncLost ||
|
||||||
!!pickBanner(serverStatus, { syncLost, where: 'client', dismissed: new Set(statusDismissed) });
|
!!pickBanner(serverStatus, { syncLost, where: 'client', dismissed: new Set(statusDismissed) });
|
||||||
if (!settled || !deviceId || !kind || otherStrip || !shouldShowNudge(kind, record, Date.now()))
|
if (!settled || !deviceId || !kind || otherStrip) return null;
|
||||||
return null;
|
|
||||||
|
|
||||||
const copy = NUDGE_COPY[kind];
|
const copy =
|
||||||
|
kind === 'stale-sessions'
|
||||||
|
? { ...NUDGE_COPY[kind], text: staleSessionsText(staleIds.length) }
|
||||||
|
: NUDGE_COPY[kind];
|
||||||
const dismiss = () => {
|
const dismiss = () => {
|
||||||
const next = dismissNudge(kind, record, Date.now());
|
const next = dismissNudge(kind, record, Date.now());
|
||||||
try {
|
try {
|
||||||
@@ -113,8 +150,15 @@ function SecurityBannerFor({ crypto }: { crypto: CryptoApi }) {
|
|||||||
return (
|
return (
|
||||||
<StatusStrip
|
<StatusStrip
|
||||||
banner={{ key: kind, tone: 'Primary', text: copy.text, dismissable: true }}
|
banner={{ key: kind, tone: 'Primary', text: copy.text, dismissable: true }}
|
||||||
icon={Icons.ShieldUser}
|
action={{
|
||||||
action={{ label: copy.action, onClick: () => requestSettings('devices') }}
|
label: copy.action,
|
||||||
|
onClick: () => {
|
||||||
|
// Review: the Devices page opens with these ticked for sign-out.
|
||||||
|
if (kind === 'stale-sessions') setPreselect(staleIds);
|
||||||
|
requestSettings('devices');
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
icon={kind === 'stale-sessions' ? Icons.Category : Icons.ShieldUser}
|
||||||
dismissLabel="Not now"
|
dismissLabel="Not now"
|
||||||
onDismiss={dismiss}
|
onDismiss={dismiss}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useMemo, useState } from 'react';
|
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Avatar,
|
Avatar,
|
||||||
Box,
|
Box,
|
||||||
@@ -13,9 +13,19 @@ import {
|
|||||||
OverlayBackdrop,
|
OverlayBackdrop,
|
||||||
OverlayCenter,
|
OverlayCenter,
|
||||||
Text,
|
Text,
|
||||||
|
color,
|
||||||
} from 'folds';
|
} from 'folds';
|
||||||
import FocusTrap from 'focus-trap-react';
|
import FocusTrap from 'focus-trap-react';
|
||||||
import { General } from './general';
|
import {
|
||||||
|
AdvancedDisplayOptions,
|
||||||
|
AppearancePage,
|
||||||
|
CallsPage,
|
||||||
|
DataStoragePage,
|
||||||
|
DesktopPage,
|
||||||
|
MessagesPage,
|
||||||
|
Privacy,
|
||||||
|
} from './general';
|
||||||
|
import { isTauri as isTauriEnv } from '../../hooks/useTauri';
|
||||||
import { PageNav, PageNavContent, PageNavHeader, PageRoot } from '../../components/page';
|
import { PageNav, PageNavContent, PageNavHeader, PageRoot } from '../../components/page';
|
||||||
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
|
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
|
||||||
import { Account } from './account';
|
import { Account } from './account';
|
||||||
@@ -34,6 +44,8 @@ import { UseStateProvider } from '../../components/UseStateProvider';
|
|||||||
import { stopPropagation } from '../../utils/keyboard';
|
import { stopPropagation } from '../../utils/keyboard';
|
||||||
import { LogoutDialog } from '../../components/LogoutDialog';
|
import { LogoutDialog } from '../../components/LogoutDialog';
|
||||||
import { SettingsPages } from './pages';
|
import { SettingsPages } from './pages';
|
||||||
|
import { SettingsSearch } from './search/SettingsSearch';
|
||||||
|
import type { SettingsEntry } from './search/settingsIndex';
|
||||||
|
|
||||||
export { SettingsPages };
|
export { SettingsPages };
|
||||||
|
|
||||||
@@ -45,43 +57,23 @@ type SettingsMenuItem = {
|
|||||||
|
|
||||||
const useSettingsMenuItems = (): SettingsMenuItem[] =>
|
const useSettingsMenuItems = (): SettingsMenuItem[] =>
|
||||||
useMemo(
|
useMemo(
|
||||||
() => [
|
() =>
|
||||||
{
|
[
|
||||||
page: SettingsPages.GeneralPage,
|
{ page: SettingsPages.AccountPage, name: 'Account', icon: Icons.User },
|
||||||
name: 'General',
|
{ page: SettingsPages.AppearancePage, name: 'Appearance', icon: Icons.Sun },
|
||||||
icon: Icons.Setting,
|
{ page: SettingsPages.MessagesPage, name: 'Messages', icon: Icons.Message },
|
||||||
},
|
{ page: SettingsPages.NotificationPage, name: 'Notifications', icon: Icons.Bell },
|
||||||
{
|
{ page: SettingsPages.CallsPage, name: 'Calls & audio', icon: Icons.Phone },
|
||||||
page: SettingsPages.AccountPage,
|
{ page: SettingsPages.DevicesPage, name: 'Privacy & security', icon: Icons.ShieldUser },
|
||||||
name: 'Account',
|
{ page: SettingsPages.DataStoragePage, name: 'Data & storage', icon: Icons.Download },
|
||||||
icon: Icons.User,
|
// [Gitea #459] Desktop-only options: nothing to show in a browser.
|
||||||
},
|
...(isTauriEnv()
|
||||||
{
|
? [{ page: SettingsPages.DesktopPage, name: 'Desktop', icon: Icons.Monitor }]
|
||||||
page: SettingsPages.NotificationPage,
|
: []),
|
||||||
name: 'Notifications',
|
{ page: SettingsPages.EmojisStickersPage, name: 'Emojis & stickers', icon: Icons.Smile },
|
||||||
icon: Icons.Bell,
|
{ page: SettingsPages.DeveloperToolsPage, name: 'Advanced', icon: Icons.Terminal },
|
||||||
},
|
{ page: SettingsPages.AboutPage, name: 'About', icon: Icons.Info },
|
||||||
{
|
] as SettingsMenuItem[],
|
||||||
page: SettingsPages.DevicesPage,
|
|
||||||
name: 'Devices',
|
|
||||||
icon: Icons.Monitor,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
page: SettingsPages.EmojisStickersPage,
|
|
||||||
name: 'Emojis & Stickers',
|
|
||||||
icon: Icons.Smile,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
page: SettingsPages.DeveloperToolsPage,
|
|
||||||
name: 'Developer Tools',
|
|
||||||
icon: Icons.Terminal,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
page: SettingsPages.AboutPage,
|
|
||||||
name: 'About',
|
|
||||||
icon: Icons.Info,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -102,9 +94,52 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
|
|||||||
const screenSize = useScreenSizeContext();
|
const screenSize = useScreenSizeContext();
|
||||||
const [activePage, setActivePage] = useState<SettingsPages | undefined>(() => {
|
const [activePage, setActivePage] = useState<SettingsPages | undefined>(() => {
|
||||||
if (initialPage) return initialPage;
|
if (initialPage) return initialPage;
|
||||||
return screenSize === ScreenSize.Mobile ? undefined : SettingsPages.GeneralPage;
|
return screenSize === ScreenSize.Mobile ? undefined : SettingsPages.AccountPage;
|
||||||
});
|
});
|
||||||
const menuItems = useSettingsMenuItems();
|
const menuItems = useSettingsMenuItems();
|
||||||
|
// [Gitea #463] Settings search: results replace the page list while typing;
|
||||||
|
// picking one opens its page and briefly highlights the setting.
|
||||||
|
const pageNames = useMemo(
|
||||||
|
() => new Map(menuItems.map((item) => [item.page, item.name])),
|
||||||
|
[menuItems],
|
||||||
|
);
|
||||||
|
const [searching, setSearching] = useState(false);
|
||||||
|
const [highlight, setHighlight] = useState<string>();
|
||||||
|
const pickResult = useCallback((entry: SettingsEntry) => {
|
||||||
|
setActivePage(entry.page);
|
||||||
|
setHighlight(entry.title);
|
||||||
|
}, []);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!highlight) return undefined;
|
||||||
|
let tries = 0;
|
||||||
|
let flashTimer: number | undefined;
|
||||||
|
const find = () => {
|
||||||
|
const match = [...document.querySelectorAll<HTMLElement>('p, span, label, h1, h2, h3')].find(
|
||||||
|
(el) =>
|
||||||
|
!el.closest('nav') && el.textContent?.trim() === highlight && el.offsetParent !== null,
|
||||||
|
);
|
||||||
|
if (!match) {
|
||||||
|
tries += 1;
|
||||||
|
if (tries < 20) poll = window.setTimeout(find, 100);
|
||||||
|
else setHighlight(undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const target = (match.closest('[class*="SequenceCard"]') as HTMLElement | null) ?? match;
|
||||||
|
target.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
||||||
|
const prev = target.style.boxShadow;
|
||||||
|
target.style.boxShadow = `0 0 0 2px ${color.Primary.Main}`;
|
||||||
|
target.style.transition = 'box-shadow 0.3s';
|
||||||
|
flashTimer = window.setTimeout(() => {
|
||||||
|
target.style.boxShadow = prev;
|
||||||
|
setHighlight(undefined);
|
||||||
|
}, 1800);
|
||||||
|
};
|
||||||
|
let poll = window.setTimeout(find, 50);
|
||||||
|
return () => {
|
||||||
|
window.clearTimeout(poll);
|
||||||
|
window.clearTimeout(flashTimer);
|
||||||
|
};
|
||||||
|
}, [highlight, activePage]);
|
||||||
|
|
||||||
const handlePageRequestClose = () => {
|
const handlePageRequestClose = () => {
|
||||||
if (screenSize === ScreenSize.Mobile) {
|
if (screenSize === ScreenSize.Mobile) {
|
||||||
@@ -145,8 +180,13 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
|
|||||||
</Box>
|
</Box>
|
||||||
</PageNavHeader>
|
</PageNavHeader>
|
||||||
<Box grow="Yes" direction="Column">
|
<Box grow="Yes" direction="Column">
|
||||||
|
<SettingsSearch
|
||||||
|
pageNames={pageNames}
|
||||||
|
onActiveChange={setSearching}
|
||||||
|
onPick={pickResult}
|
||||||
|
/>
|
||||||
<PageNavContent>
|
<PageNavContent>
|
||||||
<nav aria-label="Settings sections" style={{ flexGrow: 1 }}>
|
<nav aria-label="Settings sections" style={{ flexGrow: 1 }} hidden={searching}>
|
||||||
{menuItems.map((item) => (
|
{menuItems.map((item) => (
|
||||||
<MenuItem
|
<MenuItem
|
||||||
key={item.name}
|
key={item.name}
|
||||||
@@ -207,8 +247,20 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{activePage === SettingsPages.GeneralPage && (
|
{activePage === SettingsPages.AppearancePage && (
|
||||||
<General requestClose={handlePageRequestClose} />
|
<AppearancePage requestClose={handlePageRequestClose} />
|
||||||
|
)}
|
||||||
|
{activePage === SettingsPages.MessagesPage && (
|
||||||
|
<MessagesPage requestClose={handlePageRequestClose} />
|
||||||
|
)}
|
||||||
|
{activePage === SettingsPages.CallsPage && (
|
||||||
|
<CallsPage requestClose={handlePageRequestClose} />
|
||||||
|
)}
|
||||||
|
{activePage === SettingsPages.DataStoragePage && (
|
||||||
|
<DataStoragePage requestClose={handlePageRequestClose} />
|
||||||
|
)}
|
||||||
|
{activePage === SettingsPages.DesktopPage && (
|
||||||
|
<DesktopPage requestClose={handlePageRequestClose} />
|
||||||
)}
|
)}
|
||||||
{activePage === SettingsPages.AccountPage && (
|
{activePage === SettingsPages.AccountPage && (
|
||||||
<Account requestClose={handlePageRequestClose} />
|
<Account requestClose={handlePageRequestClose} />
|
||||||
@@ -217,13 +269,21 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
|
|||||||
<Notifications requestClose={handlePageRequestClose} />
|
<Notifications requestClose={handlePageRequestClose} />
|
||||||
)}
|
)}
|
||||||
{activePage === SettingsPages.DevicesPage && (
|
{activePage === SettingsPages.DevicesPage && (
|
||||||
<Devices requestClose={handlePageRequestClose} />
|
<Devices
|
||||||
|
title="Privacy & security"
|
||||||
|
before={<Privacy />}
|
||||||
|
requestClose={handlePageRequestClose}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{activePage === SettingsPages.EmojisStickersPage && (
|
{activePage === SettingsPages.EmojisStickersPage && (
|
||||||
<EmojisStickers requestClose={handlePageRequestClose} />
|
<EmojisStickers requestClose={handlePageRequestClose} />
|
||||||
)}
|
)}
|
||||||
{activePage === SettingsPages.DeveloperToolsPage && (
|
{activePage === SettingsPages.DeveloperToolsPage && (
|
||||||
<DeveloperTools requestClose={handlePageRequestClose} />
|
<DeveloperTools
|
||||||
|
title="Advanced"
|
||||||
|
before={<AdvancedDisplayOptions />}
|
||||||
|
requestClose={handlePageRequestClose}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
{activePage === SettingsPages.AboutPage && <About requestClose={handlePageRequestClose} />}
|
{activePage === SettingsPages.AboutPage && <About requestClose={handlePageRequestClose} />}
|
||||||
</PageRoot>
|
</PageRoot>
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ export function About({ requestClose }: AboutProps) {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Clear Cache & Reload"
|
title="Clear cache and reload"
|
||||||
description="Clear all your locally stored data and reload from server. This also deletes this device's encryption keys — older encrypted messages stay unreadable here unless key backup is set up."
|
description="Clear all your locally stored data and reload from server. This also deletes this device's encryption keys — older encrypted messages stay unreadable here unless key backup is set up."
|
||||||
after={
|
after={
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -22,14 +22,14 @@ export function ContactInformation() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Contact Information</Text>
|
<Text size="L400">Contact information</Text>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
className={SequenceCardStyle}
|
className={SequenceCardStyle}
|
||||||
variant="SurfaceVariant"
|
variant="SurfaceVariant"
|
||||||
direction="Column"
|
direction="Column"
|
||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile title="Email Address" description="Email address attached to your account.">
|
<SettingTile title="Email address" description="Email address attached to your account.">
|
||||||
<Box>
|
<Box>
|
||||||
{emailIds?.map((email) => (
|
{emailIds?.map((email) => (
|
||||||
<Chip key={email.address} as="span" variant="Secondary" radii="Pill">
|
<Chip key={email.address} as="span" variant="Secondary" radii="Pill">
|
||||||
|
|||||||
@@ -136,7 +136,7 @@ export function IgnoredUserList() {
|
|||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Box alignItems="Center" justifyContent="SpaceBetween" gap="200">
|
<Box alignItems="Center" justifyContent="SpaceBetween" gap="200">
|
||||||
<Text size="L400">Blocked Users</Text>
|
<Text size="L400">Blocked users</Text>
|
||||||
</Box>
|
</Box>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
className={SequenceCardStyle}
|
className={SequenceCardStyle}
|
||||||
@@ -145,8 +145,8 @@ export function IgnoredUserList() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Select User"
|
title="Block someone"
|
||||||
description="Prevent receiving messages or invites from user by adding their userId."
|
description="Stop someone's messages and invites reaching you. Enter their Matrix ID, e.g. @name:server."
|
||||||
>
|
>
|
||||||
<Box direction="Column" gap="300">
|
<Box direction="Column" gap="300">
|
||||||
<IgnoreUserInput userList={ignoredUsers} />
|
<IgnoreUserInput userList={ignoredUsers} />
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export function OidcManageAccount() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Account Management</Text>
|
<Text size="L400">Account management</Text>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
className={SequenceCardStyle}
|
className={SequenceCardStyle}
|
||||||
variant="SurfaceVariant"
|
variant="SurfaceVariant"
|
||||||
|
|||||||
@@ -38,11 +38,7 @@ import { SettingTile } from '../../../components/setting-tile';
|
|||||||
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||||
import { getAccountData, setAccountData } from '../../../utils/accountData';
|
import { getAccountData, setAccountData } from '../../../utils/accountData';
|
||||||
import { presenceStateFromSetting } from '../../../hooks/usePresenceUpdater';
|
import { presenceStateFromSetting } from '../../../hooks/usePresenceUpdater';
|
||||||
import {
|
import { describePresenceError, queuePresenceWrite } from '../../../utils/presenceWrite';
|
||||||
describePresenceError,
|
|
||||||
setPresenceWithRetry,
|
|
||||||
writePresence,
|
|
||||||
} from '../../../utils/presenceWrite';
|
|
||||||
import { useSetting } from '../../../state/hooks/settings';
|
import { useSetting } from '../../../state/hooks/settings';
|
||||||
import { settingsAtom } from '../../../state/settings';
|
import { settingsAtom } from '../../../state/settings';
|
||||||
import { UserProfile, useUserProfile } from '../../../hooks/useUserProfile';
|
import { UserProfile, useUserProfile } from '../../../hooks/useUserProfile';
|
||||||
@@ -313,7 +309,7 @@ function ProfileDisplayName({ profile, userId }: ProfileProps) {
|
|||||||
<SettingTile
|
<SettingTile
|
||||||
title={
|
title={
|
||||||
<Text as="span" size="L400">
|
<Text as="span" size="L400">
|
||||||
Display Name
|
Display name
|
||||||
</Text>
|
</Text>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
@@ -419,6 +415,10 @@ function ProfileStatus() {
|
|||||||
// until our own echo lands or a short window elapses (bounded so a genuinely
|
// until our own echo lands or a short window elapses (bounded so a genuinely
|
||||||
// dropped echo can't block real cross-device updates forever).
|
// dropped echo can't block real cross-device updates forever).
|
||||||
const pendingAppliedRef = useRef<{ value: string; ts: number } | null>(null);
|
const pendingAppliedRef = useRef<{ value: string; ts: number } | null>(null);
|
||||||
|
// The status as this device last applied or synced it. "Save" compares with
|
||||||
|
// this, not with the server echo, so it switches off the moment a status is
|
||||||
|
// applied instead of staying lit until the (rate-limited) write lands.
|
||||||
|
const [savedMsg, setSavedMsg] = useState<string>(initialStatus);
|
||||||
const [clearAfter, setClearAfter] = useState('0');
|
const [clearAfter, setClearAfter] = useState('0');
|
||||||
const [emojiAnchor, setEmojiAnchor] = useState<RectCords>();
|
const [emojiAnchor, setEmojiAnchor] = useState<RectCords>();
|
||||||
const { presets, addPreset, removePreset } = useStatusPresets();
|
const { presets, addPreset, removePreset } = useStatusPresets();
|
||||||
@@ -442,7 +442,7 @@ function ProfileStatus() {
|
|||||||
if (pending) {
|
if (pending) {
|
||||||
if (remoteStatus === pending.value) {
|
if (remoteStatus === pending.value) {
|
||||||
pendingAppliedRef.current = null; // our own echo landed — accept it
|
pendingAppliedRef.current = null; // our own echo landed — accept it
|
||||||
} else if (Date.now() - pending.ts < 15_000) {
|
} else if (Date.now() - pending.ts < 30_000) {
|
||||||
return; // stale echo of the previous status; ignore within the window
|
return; // stale echo of the previous status; ignore within the window
|
||||||
} else {
|
} else {
|
||||||
pendingAppliedRef.current = null; // window elapsed — accept external changes
|
pendingAppliedRef.current = null; // window elapsed — accept external changes
|
||||||
@@ -451,6 +451,7 @@ function ProfileStatus() {
|
|||||||
// [Gitea #283] "dnd" is the Do Not Disturb sentinel, not something the user
|
// [Gitea #283] "dnd" is the Do Not Disturb sentinel, not something the user
|
||||||
// typed: don't show it in the status field or keep it as their status.
|
// typed: don't show it in the status field or keep it as their status.
|
||||||
if (remoteStatus === DND_STATUS_SENTINEL) return;
|
if (remoteStatus === DND_STATUS_SENTINEL) return;
|
||||||
|
setSavedMsg(remoteStatus);
|
||||||
if (remoteStatus) {
|
if (remoteStatus) {
|
||||||
setStatusMsg(remoteStatus);
|
setStatusMsg(remoteStatus);
|
||||||
localStorage.setItem(STATUS_MSG_KEY(userId), remoteStatus);
|
localStorage.setItem(STATUS_MSG_KEY(userId), remoteStatus);
|
||||||
@@ -467,9 +468,10 @@ function ProfileStatus() {
|
|||||||
useCallback(
|
useCallback(
|
||||||
(msg: string) =>
|
(msg: string) =>
|
||||||
// Synapse allows ONE presence write per 10 s per user (shared by all
|
// Synapse allows ONE presence write per 10 s per user (shared by all
|
||||||
// devices) and our heartbeat spends that budget too — wait out a 429
|
// devices) and our heartbeat spends that budget too. The shared queue
|
||||||
// instead of failing the user's save.
|
// waits out a 429 and folds quick successive changes into one write;
|
||||||
setPresenceWithRetry(mx, {
|
// the UI doesn't wait on it (the status is applied locally at once).
|
||||||
|
queuePresenceWrite(mx, {
|
||||||
// Derive presence from the user's chosen setting so writing a status
|
// Derive presence from the user's chosen setting so writing a status
|
||||||
// never overrides Invisible/DND/Idle (e.g. outing an Invisible user).
|
// never overrides Invisible/DND/Idle (e.g. outing an Invisible user).
|
||||||
presence: presenceStateFromSetting(presenceStatus, hidePresence),
|
presence: presenceStateFromSetting(presenceStatus, hidePresence),
|
||||||
@@ -498,6 +500,7 @@ function ProfileStatus() {
|
|||||||
(rawMsg: string, clearAfterValue: string) => {
|
(rawMsg: string, clearAfterValue: string) => {
|
||||||
statusDirtyRef.current = false;
|
statusDirtyRef.current = false;
|
||||||
const msg = rawMsg.trim();
|
const msg = rawMsg.trim();
|
||||||
|
setSavedMsg(msg);
|
||||||
// Guard against a stale presence echo reverting this value (see the sync effect).
|
// Guard against a stale presence echo reverting this value (see the sync effect).
|
||||||
pendingAppliedRef.current = { value: msg, ts: Date.now() };
|
pendingAppliedRef.current = { value: msg, ts: Date.now() };
|
||||||
noteLocalStatusWrite();
|
noteLocalStatusWrite();
|
||||||
@@ -527,19 +530,17 @@ function ProfileStatus() {
|
|||||||
|
|
||||||
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
|
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
|
||||||
evt.preventDefault();
|
evt.preventDefault();
|
||||||
if (saving) return;
|
|
||||||
applyStatus(statusMsg, clearAfter);
|
applyStatus(statusMsg, clearAfter);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Preset click = one-click apply: reflect it in the inputs and save immediately.
|
// Preset click = one-click apply: reflect it in the inputs and save immediately.
|
||||||
const applyPreset = useCallback(
|
const applyPreset = useCallback(
|
||||||
(preset: StatusPreset) => {
|
(preset: StatusPreset) => {
|
||||||
if (saving) return;
|
|
||||||
setStatusMsg(preset.label);
|
setStatusMsg(preset.label);
|
||||||
setClearAfter(preset.clearAfter);
|
setClearAfter(preset.clearAfter);
|
||||||
applyStatus(preset.label, preset.clearAfter);
|
applyStatus(preset.label, preset.clearAfter);
|
||||||
},
|
},
|
||||||
[saving, applyStatus],
|
[applyStatus],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleSaveCurrent = useCallback(() => {
|
const handleSaveCurrent = useCallback(() => {
|
||||||
@@ -560,23 +561,24 @@ function ProfileStatus() {
|
|||||||
pendingAppliedRef.current = { value: '', ts: Date.now() };
|
pendingAppliedRef.current = { value: '', ts: Date.now() };
|
||||||
noteLocalStatusWrite();
|
noteLocalStatusWrite();
|
||||||
setStatusMsg('');
|
setStatusMsg('');
|
||||||
|
setSavedMsg('');
|
||||||
localStorage.removeItem(STATUS_MSG_KEY(userId));
|
localStorage.removeItem(STATUS_MSG_KEY(userId));
|
||||||
localStorage.removeItem(STATUS_EXPIRY_KEY(userId));
|
localStorage.removeItem(STATUS_EXPIRY_KEY(userId));
|
||||||
writeStatusExpiry(mx, '').catch(() => undefined);
|
writeStatusExpiry(mx, '').catch(() => undefined);
|
||||||
// Preserve the user's chosen presence when clearing the status message.
|
// Preserve the user's chosen presence when clearing the status message.
|
||||||
writePresence(mx, {
|
queuePresenceWrite(mx, {
|
||||||
presence: presenceStateFromSetting(presenceStatus, hidePresence),
|
presence: presenceStateFromSetting(presenceStatus, hidePresence),
|
||||||
status_msg: '',
|
status_msg: '',
|
||||||
}).catch(() => undefined);
|
}).catch(() => undefined);
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasChanges = statusMsg !== (presence?.status ?? '');
|
const hasChanges = statusMsg.trim() !== savedMsg;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title={
|
title={
|
||||||
<Text as="span" size="L400">
|
<Text as="span" size="L400">
|
||||||
Status Message
|
Status message
|
||||||
</Text>
|
</Text>
|
||||||
}
|
}
|
||||||
description={
|
description={
|
||||||
@@ -599,7 +601,6 @@ function ProfileStatus() {
|
|||||||
variant="Secondary"
|
variant="Secondary"
|
||||||
fill="Soft"
|
fill="Soft"
|
||||||
radii="Pill"
|
radii="Pill"
|
||||||
disabled={saving}
|
|
||||||
onClick={() => applyPreset(preset)}
|
onClick={() => applyPreset(preset)}
|
||||||
>
|
>
|
||||||
<Text as="span" size="B300">
|
<Text as="span" size="B300">
|
||||||
@@ -625,7 +626,6 @@ function ProfileStatus() {
|
|||||||
variant="Secondary"
|
variant="Secondary"
|
||||||
fill="Soft"
|
fill="Soft"
|
||||||
radii="Pill"
|
radii="Pill"
|
||||||
disabled={saving}
|
|
||||||
onClick={() => applyPreset(preset)}
|
onClick={() => applyPreset(preset)}
|
||||||
>
|
>
|
||||||
<Text as="span" size="B300">
|
<Text as="span" size="B300">
|
||||||
@@ -651,7 +651,7 @@ function ProfileStatus() {
|
|||||||
fill="Soft"
|
fill="Soft"
|
||||||
radii="Pill"
|
radii="Pill"
|
||||||
outlined
|
outlined
|
||||||
disabled={saving || !statusMsg.trim()}
|
disabled={!statusMsg.trim()}
|
||||||
onClick={handleSaveCurrent}
|
onClick={handleSaveCurrent}
|
||||||
before={<Icon size="100" src={Icons.Plus} />}
|
before={<Icon size="100" src={Icons.Plus} />}
|
||||||
>
|
>
|
||||||
@@ -662,7 +662,7 @@ function ProfileStatus() {
|
|||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Box as="form" onSubmit={handleSubmit} gap="200" alignItems="Center" aria-disabled={saving}>
|
<Box as="form" onSubmit={handleSubmit} gap="200" alignItems="Center">
|
||||||
<Box grow="Yes" direction="Column" gap="100">
|
<Box grow="Yes" direction="Column" gap="100">
|
||||||
<Input
|
<Input
|
||||||
name="statusMsgInput"
|
name="statusMsgInput"
|
||||||
@@ -672,7 +672,6 @@ function ProfileStatus() {
|
|||||||
placeholder="What's on your mind?"
|
placeholder="What's on your mind?"
|
||||||
variant="Secondary"
|
variant="Secondary"
|
||||||
radii="300"
|
radii="300"
|
||||||
readOnly={saving}
|
|
||||||
maxLength={64}
|
maxLength={64}
|
||||||
/>
|
/>
|
||||||
<Text
|
<Text
|
||||||
@@ -733,13 +732,17 @@ function ProfileStatus() {
|
|||||||
fill={hasChanges ? 'Solid' : 'Soft'}
|
fill={hasChanges ? 'Solid' : 'Soft'}
|
||||||
outlined
|
outlined
|
||||||
radii="300"
|
radii="300"
|
||||||
disabled={!hasChanges || saving}
|
disabled={!hasChanges}
|
||||||
type="submit"
|
type="submit"
|
||||||
>
|
>
|
||||||
{saving && <Spinner variant="Success" fill="Solid" size="300" />}
|
|
||||||
<Text size="B400">Save</Text>
|
<Text size="B400">Save</Text>
|
||||||
</Button>
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
|
{saving && (
|
||||||
|
<Text size="T200" priority="300" role="status">
|
||||||
|
Status set. Sharing it with others, this can take a few seconds.
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
{saveState.status === AsyncStatus.Error && (
|
{saveState.status === AsyncStatus.Error && (
|
||||||
<Text size="T200" style={{ color: color.Critical.Main }}>
|
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||||
{describePresenceError(saveState.error)}
|
{describePresenceError(saveState.error)}
|
||||||
@@ -764,7 +767,6 @@ function ProfileStatus() {
|
|||||||
radii="300"
|
radii="300"
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleClear}
|
onClick={handleClear}
|
||||||
disabled={saving}
|
|
||||||
>
|
>
|
||||||
<Text size="B300">Clear Status</Text>
|
<Text size="B300">Clear Status</Text>
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -102,6 +102,8 @@ export function ProfileDecoration() {
|
|||||||
|
|
||||||
const [current, setCurrent] = useState<string | null>(null);
|
const [current, setCurrent] = useState<string | null>(null);
|
||||||
const [selected, setSelected] = useState<string | null>(null);
|
const [selected, setSelected] = useState<string | null>(null);
|
||||||
|
// [Gitea #460] The catalog stays closed until "Change"; it was always open.
|
||||||
|
const [browsing, setBrowsing] = useState(false);
|
||||||
// Distinguish "confirmed no decoration" from "failed to load": a fetch
|
// Distinguish "confirmed no decoration" from "failed to load": a fetch
|
||||||
// failure must not be shown as (and saved over) "None".
|
// failure must not be shown as (and saved over) "None".
|
||||||
const [loadError, setLoadError] = useState(false);
|
const [loadError, setLoadError] = useState(false);
|
||||||
@@ -199,7 +201,7 @@ export function ProfileDecoration() {
|
|||||||
<SettingTile
|
<SettingTile
|
||||||
title={
|
title={
|
||||||
<Text as="span" size="L400">
|
<Text as="span" size="L400">
|
||||||
Avatar Decoration
|
Avatar decoration
|
||||||
</Text>
|
</Text>
|
||||||
}
|
}
|
||||||
description={
|
description={
|
||||||
@@ -282,6 +284,20 @@ export function ProfileDecoration() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
{!loadError && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
outlined
|
||||||
|
aria-expanded={browsing}
|
||||||
|
onClick={() => setBrowsing((b) => !b)}
|
||||||
|
>
|
||||||
|
<Text size="B300">{browsing ? 'Done' : 'Change'}</Text>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
{hasChanges && !loadError && (
|
{hasChanges && !loadError && (
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -324,6 +340,8 @@ export function ProfileDecoration() {
|
|||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{browsing && (
|
||||||
|
<>
|
||||||
{/* Search + category tabs. Only one category (or the search results)
|
{/* Search + category tabs. Only one category (or the search results)
|
||||||
is mounted at a time so the picker never loads the whole catalog. */}
|
is mounted at a time so the picker never loads the whole catalog. */}
|
||||||
<Input
|
<Input
|
||||||
@@ -391,6 +409,8 @@ export function ProfileDecoration() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
</SettingTile>
|
</SettingTile>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useCallback, useState } from 'react';
|
import React, { useCallback, useState, ReactNode } from 'react';
|
||||||
import { Box, Text, IconButton, Icon, Icons, Scroll, Switch, Button } from 'folds';
|
import { Box, Text, IconButton, Icon, Icons, Scroll, Switch, Button } from 'folds';
|
||||||
import { Page, PageContent, PageHeader } from '../../../components/page';
|
import { Page, PageContent, PageHeader } from '../../../components/page';
|
||||||
import { SequenceCard } from '../../../components/sequence-card';
|
import { SequenceCard } from '../../../components/sequence-card';
|
||||||
@@ -18,8 +18,12 @@ import { CryptoDiagnostics } from '../developer/CryptoDiagnostics';
|
|||||||
|
|
||||||
type DeveloperToolsProps = {
|
type DeveloperToolsProps = {
|
||||||
requestClose: () => void;
|
requestClose: () => void;
|
||||||
|
/** [Gitea #459] Shown as the page title (the menu entry's name). */
|
||||||
|
title?: string;
|
||||||
|
/** [Gitea #459] Sections shown above this page's own. */
|
||||||
|
before?: ReactNode;
|
||||||
};
|
};
|
||||||
export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
|
export function DeveloperTools({ requestClose, title, before }: DeveloperToolsProps) {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
const [developerTools, setDeveloperTools] = useSetting(settingsAtom, 'developerTools');
|
const [developerTools, setDeveloperTools] = useSetting(settingsAtom, 'developerTools');
|
||||||
const [expand, setExpend] = useState(false);
|
const [expand, setExpend] = useState(false);
|
||||||
@@ -49,7 +53,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
|
|||||||
<Box grow="Yes" gap="200">
|
<Box grow="Yes" gap="200">
|
||||||
<Box grow="Yes" alignItems="Center" gap="200">
|
<Box grow="Yes" alignItems="Center" gap="200">
|
||||||
<Text size="H3" truncate>
|
<Text size="H3" truncate>
|
||||||
Developer Tools
|
{title ?? 'Developer Tools'}
|
||||||
</Text>
|
</Text>
|
||||||
</Box>
|
</Box>
|
||||||
<Box shrink="No">
|
<Box shrink="No">
|
||||||
@@ -63,6 +67,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
|
|||||||
<Scroll hideTrack visibility="Hover">
|
<Scroll hideTrack visibility="Hover">
|
||||||
<PageContent>
|
<PageContent>
|
||||||
<Box direction="Column" gap="700">
|
<Box direction="Column" gap="700">
|
||||||
|
{before}
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Options</Text>
|
<Text size="L400">Options</Text>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
@@ -72,7 +77,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Enable Developer Tools"
|
title="Enable developer tools"
|
||||||
after={
|
after={
|
||||||
<Switch
|
<Switch
|
||||||
variant="Primary"
|
variant="Primary"
|
||||||
@@ -90,7 +95,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Access Token"
|
title="Access token"
|
||||||
description="Copy access token to clipboard."
|
description="Copy access token to clipboard."
|
||||||
after={
|
after={
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ export function CryptoDiagnostics() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Crypto Diagnostics</Text>
|
<Text size="L400">Crypto diagnostics</Text>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
className={SequenceCardStyle}
|
className={SequenceCardStyle}
|
||||||
variant="SurfaceVariant"
|
variant="SurfaceVariant"
|
||||||
@@ -43,8 +43,8 @@ export function CryptoDiagnostics() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Crypto Diagnostics — captures E2EE error signatures this session"
|
title="Crypto diagnostics"
|
||||||
description="Ring-buffers up to 200 matched console warnings/errors for the KE-1..KE-4 bug cluster. Local only — no network calls. The downloaded report includes the matched log lines as evidence."
|
description="Captures encryption error signatures from this session. Ring-buffers up to 200 matched console warnings/errors for the KE-1..KE-4 bug cluster. Local only — no network calls. The downloaded report includes the matched log lines as evidence."
|
||||||
after={
|
after={
|
||||||
<Box alignItems="Center" gap="200" shrink="No">
|
<Box alignItems="Center" gap="200" shrink="No">
|
||||||
<Badge variant={count > 0 ? 'Critical' : 'Secondary'} fill="Solid" radii="Pill">
|
<Badge variant={count > 0 ? 'Critical' : 'Secondary'} fill="Solid" radii="Pill">
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ function DeviceRename({ device, onCancel, onRename, refreshDeviceList }: DeviceR
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box as="form" onSubmit={handleSubmit} direction="Column" gap="100">
|
<Box as="form" onSubmit={handleSubmit} direction="Column" gap="100">
|
||||||
<Text size="L400">Device Name</Text>
|
<Text size="L400">Device name</Text>
|
||||||
<Box gap="200">
|
<Box gap="200">
|
||||||
<Box grow="Yes" direction="Column">
|
<Box grow="Yes" direction="Column">
|
||||||
<Input
|
<Input
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React from 'react';
|
import React, { ReactNode } from 'react';
|
||||||
import { Box, Text, IconButton, Icon, Icons, Scroll } from 'folds';
|
import { Box, Text, IconButton, Icon, Icons, Scroll } from 'folds';
|
||||||
import { Page, PageContent, PageHeader } from '../../../components/page';
|
import { Page, PageContent, PageHeader } from '../../../components/page';
|
||||||
import { SequenceCard } from '../../../components/sequence-card';
|
import { SequenceCard } from '../../../components/sequence-card';
|
||||||
@@ -38,8 +38,12 @@ function DevicesPlaceholder() {
|
|||||||
|
|
||||||
type DevicesProps = {
|
type DevicesProps = {
|
||||||
requestClose: () => void;
|
requestClose: () => void;
|
||||||
|
/** [Gitea #459] Shown as the page title (the menu entry's name). */
|
||||||
|
title?: string;
|
||||||
|
/** [Gitea #459] Sections shown above this page's own. */
|
||||||
|
before?: ReactNode;
|
||||||
};
|
};
|
||||||
export function Devices({ requestClose }: DevicesProps) {
|
export function Devices({ requestClose, title, before }: DevicesProps) {
|
||||||
const mx = useMatrixClient();
|
const mx = useMatrixClient();
|
||||||
const crypto = mx.getCrypto();
|
const crypto = mx.getCrypto();
|
||||||
const crossSigningActive = useCrossSigningActive();
|
const crossSigningActive = useCrossSigningActive();
|
||||||
@@ -70,7 +74,7 @@ export function Devices({ requestClose }: DevicesProps) {
|
|||||||
<Box grow="Yes" gap="200">
|
<Box grow="Yes" gap="200">
|
||||||
<Box grow="Yes" alignItems="Center" gap="200">
|
<Box grow="Yes" alignItems="Center" gap="200">
|
||||||
<Text size="H3" truncate>
|
<Text size="H3" truncate>
|
||||||
Devices
|
{title ?? 'Devices'}
|
||||||
</Text>
|
</Text>
|
||||||
</Box>
|
</Box>
|
||||||
<Box shrink="No">
|
<Box shrink="No">
|
||||||
@@ -84,6 +88,7 @@ export function Devices({ requestClose }: DevicesProps) {
|
|||||||
<Scroll hideTrack visibility="Hover">
|
<Scroll hideTrack visibility="Hover">
|
||||||
<PageContent>
|
<PageContent>
|
||||||
<Box direction="Column" gap="700">
|
<Box direction="Column" gap="700">
|
||||||
|
{before}
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Security</Text>
|
<Text size="L400">Security</Text>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
@@ -93,8 +98,8 @@ export function Devices({ requestClose }: DevicesProps) {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Device Verification"
|
title="Device verification"
|
||||||
description="To verify device identity and grant access to encrypted messages."
|
description="Verify this device so it can read your encrypted messages and others can trust it."
|
||||||
after={
|
after={
|
||||||
<>
|
<>
|
||||||
<EnableVerification visible={!crossSigningActive} />
|
<EnableVerification visible={!crossSigningActive} />
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ function ExportKeys() {
|
|||||||
{(match, doMatch, passRef, confPassRef) => (
|
{(match, doMatch, passRef, confPassRef) => (
|
||||||
<>
|
<>
|
||||||
<Box grow="Yes" direction="Column" gap="100">
|
<Box grow="Yes" direction="Column" gap="100">
|
||||||
<Text size="L400">New Password</Text>
|
<Text size="L400">New password</Text>
|
||||||
<PasswordInput
|
<PasswordInput
|
||||||
ref={passRef}
|
ref={passRef}
|
||||||
name="passwordInput"
|
name="passwordInput"
|
||||||
@@ -82,7 +82,7 @@ function ExportKeys() {
|
|||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
<Box grow="Yes" direction="Column" gap="100">
|
<Box grow="Yes" direction="Column" gap="100">
|
||||||
<Text size="L400">Confirm Password</Text>
|
<Text size="L400">Confirm password</Text>
|
||||||
<PasswordInput
|
<PasswordInput
|
||||||
ref={confPassRef}
|
ref={confPassRef}
|
||||||
style={{ color: match ? undefined : color.Critical.Main }}
|
style={{ color: match ? undefined : color.Critical.Main }}
|
||||||
@@ -130,8 +130,8 @@ function ExportKeysTile() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Export Messages Data"
|
title="Export encryption keys"
|
||||||
description="Save password protected copy of encryption data on your device to decrypt messages later."
|
description="Save a password-protected file of your encryption keys. Useful when moving to a device without key backup, or as an offline copy."
|
||||||
after={
|
after={
|
||||||
<Box>
|
<Box>
|
||||||
<Button
|
<Button
|
||||||
@@ -260,8 +260,8 @@ function ImportKeysTile() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Import Messages Data"
|
title="Import encryption keys"
|
||||||
description="Load password protected copy of encryption data from device to decrypt your messages."
|
description="Load a password-protected encryption key file to read older encrypted messages on this device."
|
||||||
after={
|
after={
|
||||||
<Box>
|
<Box>
|
||||||
{file ? (
|
{file ? (
|
||||||
@@ -307,7 +307,7 @@ function ImportKeysTile() {
|
|||||||
export function LocalBackup() {
|
export function LocalBackup() {
|
||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Local Backup</Text>
|
<Text size="L400">Encryption key backup file</Text>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
className={SequenceCardStyle}
|
className={SequenceCardStyle}
|
||||||
variant="SurfaceVariant"
|
variant="SurfaceVariant"
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useCallback, useState } from 'react';
|
import React, { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { useAtom } from 'jotai';
|
||||||
import { Box, Button, config, Menu, Spinner, Text } from 'folds';
|
import { Box, Button, config, Menu, Spinner, Text } from 'folds';
|
||||||
import { AuthDict, IMyDevice, MatrixError } from 'matrix-js-sdk';
|
import { AuthDict, IMyDevice, MatrixError } from 'matrix-js-sdk';
|
||||||
import { SequenceCard } from '../../../components/sequence-card';
|
import { SequenceCard } from '../../../components/sequence-card';
|
||||||
@@ -15,6 +16,8 @@ import { useAuthMetadata } from '../../../hooks/useAuthMetadata';
|
|||||||
import { withSearchParam } from '../../../pages/pathUtils';
|
import { withSearchParam } from '../../../pages/pathUtils';
|
||||||
import { useAccountManagementActions } from '../../../hooks/useAccountManagement';
|
import { useAccountManagementActions } from '../../../hooks/useAccountManagement';
|
||||||
import { SettingTile } from '../../../components/setting-tile';
|
import { SettingTile } from '../../../components/setting-tile';
|
||||||
|
import { preselectSignOutAtom } from '../../../state/staleSessions';
|
||||||
|
import { staleSessions } from '../../../utils/securityNudge';
|
||||||
|
|
||||||
type OtherDevicesProps = {
|
type OtherDevicesProps = {
|
||||||
devices: IMyDevice[];
|
devices: IMyDevice[];
|
||||||
@@ -29,6 +32,23 @@ export function OtherDevices({ devices, refreshDeviceList, showVerification }: O
|
|||||||
|
|
||||||
const [deleted, setDeleted] = useState<Set<string>>(new Set());
|
const [deleted, setDeleted] = useState<Set<string>>(new Set());
|
||||||
|
|
||||||
|
// [Gitea #113] The stale-sessions nudge's Review: tick those sessions for
|
||||||
|
// sign-out (one confirm below). OIDC accounts sign out on the provider's
|
||||||
|
// dashboard instead, so nothing is ticked there.
|
||||||
|
const [preselect, setPreselect] = useAtom(preselectSignOutAtom);
|
||||||
|
useEffect(() => {
|
||||||
|
if (preselect.length === 0) return;
|
||||||
|
if (!authMetadata) {
|
||||||
|
const present = new Set(devices.map((d) => d.device_id));
|
||||||
|
setDeleted(new Set(preselect.filter((id) => present.has(id))));
|
||||||
|
}
|
||||||
|
setPreselect([]);
|
||||||
|
}, [preselect, setPreselect, devices, authMetadata]);
|
||||||
|
|
||||||
|
const staleIds = new Set(
|
||||||
|
staleSessions(devices, mx.getDeviceId() ?? undefined, Date.now()).map((d) => d.device_id),
|
||||||
|
);
|
||||||
|
|
||||||
const handleDashboardOIDC = useCallback(() => {
|
const handleDashboardOIDC = useCallback(() => {
|
||||||
const authUrl = authMetadata?.account_management_uri ?? authMetadata?.issuer;
|
const authUrl = authMetadata?.account_management_uri ?? authMetadata?.issuer;
|
||||||
if (!authUrl) return;
|
if (!authUrl) return;
|
||||||
@@ -115,7 +135,7 @@ export function OtherDevices({ devices, refreshDeviceList, showVerification }: O
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Device Dashboard"
|
title="Device dashboard"
|
||||||
description="Manage your devices on OIDC dashboard."
|
description="Manage your devices on OIDC dashboard."
|
||||||
after={
|
after={
|
||||||
<Button
|
<Button
|
||||||
@@ -132,8 +152,20 @@ export function OtherDevices({ devices, refreshDeviceList, showVerification }: O
|
|||||||
/>
|
/>
|
||||||
</SequenceCard>
|
</SequenceCard>
|
||||||
)}
|
)}
|
||||||
{devices
|
{staleIds.size > 0 && (
|
||||||
|
<Text size="T200" priority="300">
|
||||||
|
{staleIds.size === 1
|
||||||
|
? "1 session hasn't been used in 3 months or more (marked Inactive)."
|
||||||
|
: `${staleIds.size} sessions haven't been used in 3 months or more (marked Inactive).`}{' '}
|
||||||
|
Sign out the ones you no longer use.
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{[...devices]
|
||||||
|
// [Gitea #113] Inactive (90+ days) sessions first, then most recent.
|
||||||
.sort((d1, d2) => {
|
.sort((d1, d2) => {
|
||||||
|
const s1 = staleIds.has(d1.device_id) ? 0 : 1;
|
||||||
|
const s2 = staleIds.has(d2.device_id) ? 0 : 1;
|
||||||
|
if (s1 !== s2) return s1 - s2;
|
||||||
if (!d1.last_seen_ts || !d2.last_seen_ts) return 0;
|
if (!d1.last_seen_ts || !d2.last_seen_ts) return 0;
|
||||||
return d1.last_seen_ts < d2.last_seen_ts ? 1 : -1;
|
return d1.last_seen_ts < d2.last_seen_ts ? 1 : -1;
|
||||||
})
|
})
|
||||||
@@ -145,6 +177,11 @@ export function OtherDevices({ devices, refreshDeviceList, showVerification }: O
|
|||||||
direction="Column"
|
direction="Column"
|
||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
|
{staleIds.has(device.device_id) && (
|
||||||
|
<Text size="L400" style={{ color: 'inherit' }}>
|
||||||
|
Inactive for 3+ months
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
<DeviceTile
|
<DeviceTile
|
||||||
device={device}
|
device={device}
|
||||||
deleted={deleted.has(device.device_id)}
|
deleted={deleted.has(device.device_id)}
|
||||||
|
|||||||
@@ -423,7 +423,7 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Favorite Packs</Text>
|
<Text size="L400">Favourite packs</Text>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
className={SequenceCardStyle}
|
className={SequenceCardStyle}
|
||||||
variant="SurfaceVariant"
|
variant="SurfaceVariant"
|
||||||
@@ -431,7 +431,7 @@ export function GlobalPacks({ onViewPack }: GlobalPacksProps) {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Select Pack"
|
title="Add a pack"
|
||||||
description="Pick emojis and stickers pack from rooms to use in all rooms."
|
description="Pick emojis and stickers pack from rooms to use in all rooms."
|
||||||
after={
|
after={
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export function UserPack({ onViewPack }: UserPackProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Default Pack</Text>
|
<Text size="L400">Default pack</Text>
|
||||||
<SequenceCard
|
<SequenceCard
|
||||||
className={SequenceCardStyle}
|
className={SequenceCardStyle}
|
||||||
variant="SurfaceVariant"
|
variant="SurfaceVariant"
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,287 @@
|
|||||||
|
import React, { useCallback, useRef, useState } from 'react';
|
||||||
|
import { useAtom } from 'jotai';
|
||||||
|
import { Method } from 'matrix-js-sdk';
|
||||||
|
import { Box, Button, RadioButton, Text, color } from 'folds';
|
||||||
|
import { SequenceCard } from '../../../components/sequence-card';
|
||||||
|
import { SequenceCardStyle } from '../styles.css';
|
||||||
|
import { SettingTile } from '../../../components/setting-tile';
|
||||||
|
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||||
|
import { Settings, settingsAtom } from '../../../state/settings';
|
||||||
|
import {
|
||||||
|
buildExport,
|
||||||
|
EXPORT_ACCOUNT_DATA,
|
||||||
|
ExportFile,
|
||||||
|
ImportPlanItem,
|
||||||
|
mergeData,
|
||||||
|
parseExport,
|
||||||
|
planImport,
|
||||||
|
} from '../../../utils/dataExport';
|
||||||
|
import { invalidateDecorationCache } from '../../../hooks/useAvatarDecoration';
|
||||||
|
|
||||||
|
const DECORATION_FIELD = 'io.lotus.avatar_decoration';
|
||||||
|
|
||||||
|
type Current = {
|
||||||
|
accountData: Record<string, unknown>;
|
||||||
|
decoration: string | null;
|
||||||
|
localSettings: Record<string, unknown> | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [Gitea #114] "Your data": export the account's Lotus data (settings,
|
||||||
|
* bookmarks, notes, sections, ...) to a file and import it here or on another
|
||||||
|
* account. Import merges: new things are added; for things that differ the
|
||||||
|
* user picks "keep mine" (default) or "use the file's". Message history and
|
||||||
|
* encryption keys have their own exports.
|
||||||
|
*/
|
||||||
|
export function YourDataSection() {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const userId = mx.getSafeUserId();
|
||||||
|
const [settings, setSettings] = useAtom(settingsAtom);
|
||||||
|
const fileInput = useRef<HTMLInputElement>(null);
|
||||||
|
const [pending, setPending] = useState<{ file: ExportFile; plan: ImportPlanItem[] }>();
|
||||||
|
const [preferFile, setPreferFile] = useState(false);
|
||||||
|
const [message, setMessage] = useState<{ tone: 'ok' | 'error'; text: string }>();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
const readCurrent = useCallback(async (): Promise<Current> => {
|
||||||
|
const accountData: Record<string, unknown> = {};
|
||||||
|
EXPORT_ACCOUNT_DATA.forEach(({ type }) => {
|
||||||
|
const c = mx.getAccountData(type as never)?.getContent();
|
||||||
|
if (c && Object.keys(c).length > 0) accountData[type] = c;
|
||||||
|
});
|
||||||
|
let decoration: string | null = null;
|
||||||
|
try {
|
||||||
|
const profile = await mx.http.authedRequest<Record<string, unknown>>(
|
||||||
|
Method.Get,
|
||||||
|
`/profile/${encodeURIComponent(userId)}`,
|
||||||
|
);
|
||||||
|
const v = profile[DECORATION_FIELD];
|
||||||
|
decoration = typeof v === 'string' && v ? v : null;
|
||||||
|
} catch {
|
||||||
|
/* no decoration */
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
accountData,
|
||||||
|
decoration,
|
||||||
|
localSettings: settings as unknown as Record<string, unknown>,
|
||||||
|
};
|
||||||
|
}, [mx, userId, settings]);
|
||||||
|
|
||||||
|
const exportData = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
setMessage(undefined);
|
||||||
|
try {
|
||||||
|
const cur = await readCurrent();
|
||||||
|
const file = buildExport({ userId, ...cur });
|
||||||
|
const blob = new Blob([JSON.stringify(file, null, 2)], { type: 'application/json' });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = `lotus-chat-data-${userId.replace(/[^a-z0-9]+/gi, '-')}-${file.exportedAt.slice(0, 10)}.json`;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
setMessage({ tone: 'ok', text: 'Exported. Keep the file somewhere safe.' });
|
||||||
|
} catch {
|
||||||
|
setMessage({ tone: 'error', text: "Couldn't export your data. Please try again." });
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const chooseFile = async (f: File | undefined) => {
|
||||||
|
if (!f) return;
|
||||||
|
setMessage(undefined);
|
||||||
|
const parsed = parseExport(await f.text());
|
||||||
|
if (!parsed.ok) {
|
||||||
|
setMessage({ tone: 'error', text: parsed.error });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const plan = planImport(parsed.file, await readCurrent());
|
||||||
|
setPreferFile(false);
|
||||||
|
setPending({ file: parsed.file, plan });
|
||||||
|
};
|
||||||
|
|
||||||
|
const applyImport = async () => {
|
||||||
|
if (!pending) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const cur = await readCurrent();
|
||||||
|
const { file } = pending;
|
||||||
|
await Object.entries(file.accountData).reduce<Promise<void>>(
|
||||||
|
async (prev, [type, incoming]) => {
|
||||||
|
await prev;
|
||||||
|
const r = mergeData(cur.accountData[type], incoming, preferFile);
|
||||||
|
if (r.added > 0 || (preferFile && r.conflicts > 0)) {
|
||||||
|
await mx.setAccountData(type as never, r.value as never);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Promise.resolve(),
|
||||||
|
);
|
||||||
|
const deco = file.profile.decoration;
|
||||||
|
if (deco && deco !== cur.decoration && (!cur.decoration || preferFile)) {
|
||||||
|
await mx.http.authedRequest(
|
||||||
|
Method.Put,
|
||||||
|
`/profile/${encodeURIComponent(userId)}/${DECORATION_FIELD}`,
|
||||||
|
undefined,
|
||||||
|
{ [DECORATION_FIELD]: deco },
|
||||||
|
);
|
||||||
|
invalidateDecorationCache(userId);
|
||||||
|
}
|
||||||
|
if (file.local.settings) {
|
||||||
|
const r = mergeData(cur.localSettings ?? {}, file.local.settings, preferFile);
|
||||||
|
setSettings({ ...settings, ...(r.value as Partial<Settings>) });
|
||||||
|
}
|
||||||
|
setPending(undefined);
|
||||||
|
setMessage({ tone: 'ok', text: 'Imported.' });
|
||||||
|
} catch {
|
||||||
|
setMessage({ tone: 'error', text: "Couldn't finish the import. Nothing else was changed." });
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const totals = pending?.plan.reduce(
|
||||||
|
(t, p) => ({ added: t.added + p.added, conflicts: t.conflicts + p.conflicts }),
|
||||||
|
{ added: 0, conflicts: 0 },
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="100">
|
||||||
|
<Text size="L400">Your data</Text>
|
||||||
|
<SequenceCard
|
||||||
|
className={SequenceCardStyle}
|
||||||
|
variant="SurfaceVariant"
|
||||||
|
direction="Column"
|
||||||
|
gap="400"
|
||||||
|
>
|
||||||
|
<SettingTile
|
||||||
|
title="Export your data"
|
||||||
|
description="Settings, bookmarks, private notes, room sections and names, reminders, status presets, soundboard and emoji, as one file. Not your messages or encryption keys (they have their own exports)."
|
||||||
|
after={
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
radii="300"
|
||||||
|
outlined
|
||||||
|
disabled={busy}
|
||||||
|
onClick={exportData}
|
||||||
|
>
|
||||||
|
<Text size="B300">Export</Text>
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<SettingTile
|
||||||
|
title="Import data"
|
||||||
|
description="Load a Lotus Chat data file into this account. New items are added; you choose what happens to things that differ."
|
||||||
|
after={
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
radii="300"
|
||||||
|
outlined
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => fileInput.current?.click()}
|
||||||
|
>
|
||||||
|
<Text size="B300">Import…</Text>
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
ref={fileInput}
|
||||||
|
type="file"
|
||||||
|
accept="application/json,.json"
|
||||||
|
hidden
|
||||||
|
aria-label="Lotus Chat data file"
|
||||||
|
onChange={(e) => {
|
||||||
|
chooseFile(e.target.files?.[0]).catch(() => undefined);
|
||||||
|
e.target.value = '';
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{pending && totals && (
|
||||||
|
<Box direction="Column" gap="200" role="region" aria-label="Import summary">
|
||||||
|
{pending.file.userId && pending.file.userId !== userId && (
|
||||||
|
<Text size="T200">
|
||||||
|
This file is from <b>{pending.file.userId}</b>.
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{pending.plan.map((p) => (
|
||||||
|
<Text key={p.key} size="T200">
|
||||||
|
{p.label}:{' '}
|
||||||
|
{p.added === 0 && p.conflicts === 0
|
||||||
|
? 'already up to date'
|
||||||
|
: [p.added > 0 && `${p.added} new`, p.conflicts > 0 && `${p.conflicts} differ`]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(', ')}
|
||||||
|
</Text>
|
||||||
|
))}
|
||||||
|
{totals.conflicts > 0 && (
|
||||||
|
<Box direction="Column" gap="100" role="radiogroup" aria-label="Things that differ">
|
||||||
|
<Text size="T200">
|
||||||
|
<b>{totals.conflicts}</b>{' '}
|
||||||
|
{totals.conflicts === 1 ? 'thing differs' : 'things differ'} from what's
|
||||||
|
here:
|
||||||
|
</Text>
|
||||||
|
<label>
|
||||||
|
<RadioButton
|
||||||
|
name="your-data-conflicts"
|
||||||
|
variant="Primary"
|
||||||
|
size="300"
|
||||||
|
checked={!preferFile}
|
||||||
|
onClick={() => setPreferFile(false)}
|
||||||
|
/>{' '}
|
||||||
|
<Text as="span" size="T200">
|
||||||
|
Keep mine
|
||||||
|
</Text>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<RadioButton
|
||||||
|
name="your-data-conflicts"
|
||||||
|
variant="Primary"
|
||||||
|
size="300"
|
||||||
|
checked={preferFile}
|
||||||
|
onClick={() => setPreferFile(true)}
|
||||||
|
/>{' '}
|
||||||
|
<Text as="span" size="T200">
|
||||||
|
Use the file's
|
||||||
|
</Text>
|
||||||
|
</label>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
<Box gap="200">
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
variant="Primary"
|
||||||
|
radii="300"
|
||||||
|
disabled={busy || (totals.added === 0 && !(preferFile && totals.conflicts > 0))}
|
||||||
|
onClick={applyImport}
|
||||||
|
>
|
||||||
|
<Text size="B300">Import</Text>
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="300"
|
||||||
|
variant="Secondary"
|
||||||
|
fill="Soft"
|
||||||
|
radii="300"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => setPending(undefined)}
|
||||||
|
>
|
||||||
|
<Text size="B300">Cancel</Text>
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
{message && (
|
||||||
|
<Text
|
||||||
|
size="T200"
|
||||||
|
role="status"
|
||||||
|
style={{ color: message.tone === 'error' ? color.Critical.Main : undefined }}
|
||||||
|
>
|
||||||
|
{message.text}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</SequenceCard>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -82,7 +82,7 @@ export function AllMessagesNotifications() {
|
|||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Box alignItems="Center" justifyContent="SpaceBetween" gap="200">
|
<Box alignItems="Center" justifyContent="SpaceBetween" gap="200">
|
||||||
<Text size="L400">All Messages</Text>
|
<Text size="L400">All messages</Text>
|
||||||
<Box gap="100">
|
<Box gap="100">
|
||||||
<Text size="T200">Badge: </Text>
|
<Text size="T200">Badge: </Text>
|
||||||
<Badge radii="300" variant="Secondary" fill="Solid">
|
<Badge radii="300" variant="Secondary" fill="Solid">
|
||||||
@@ -97,7 +97,7 @@ export function AllMessagesNotifications() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="1-to-1 Chats"
|
title="1-to-1 chats"
|
||||||
after={<AllMessagesModeSwitcher pushRules={pushRules} ruleId={RuleId.DM} oneToOne />}
|
after={<AllMessagesModeSwitcher pushRules={pushRules} ruleId={RuleId.DM} oneToOne />}
|
||||||
/>
|
/>
|
||||||
</SequenceCard>
|
</SequenceCard>
|
||||||
@@ -108,7 +108,7 @@ export function AllMessagesNotifications() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="1-to-1 Chats (Encrypted)"
|
title="1-to-1 chats (encrypted)"
|
||||||
after={
|
after={
|
||||||
<AllMessagesModeSwitcher
|
<AllMessagesModeSwitcher
|
||||||
pushRules={pushRules}
|
pushRules={pushRules}
|
||||||
@@ -137,7 +137,7 @@ export function AllMessagesNotifications() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Rooms (Encrypted)"
|
title="Rooms (encrypted)"
|
||||||
after={
|
after={
|
||||||
<AllMessagesModeSwitcher
|
<AllMessagesModeSwitcher
|
||||||
pushRules={pushRules}
|
pushRules={pushRules}
|
||||||
|
|||||||
@@ -171,7 +171,7 @@ export function KeywordMessagesNotifications() {
|
|||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Box alignItems="Center" justifyContent="SpaceBetween" gap="200">
|
<Box alignItems="Center" justifyContent="SpaceBetween" gap="200">
|
||||||
<Text size="L400">Keyword Messages</Text>
|
<Text size="L400">Keyword messages</Text>
|
||||||
<Box gap="100">
|
<Box gap="100">
|
||||||
<Text size="T200">Badge: </Text>
|
<Text size="T200">Badge: </Text>
|
||||||
<Badge radii="300" variant="Success" fill="Solid">
|
<Badge radii="300" variant="Success" fill="Solid">
|
||||||
@@ -186,7 +186,7 @@ export function KeywordMessagesNotifications() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Select Keyword"
|
title="Add a keyword"
|
||||||
description="Set a notification preference for message containing given keyword."
|
description="Set a notification preference for message containing given keyword."
|
||||||
>
|
>
|
||||||
<KeywordInput />
|
<KeywordInput />
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import { KeywordMessagesNotifications } from './KeywordMessages';
|
|||||||
import { PushRuleEditor } from './PushRuleEditor';
|
import { PushRuleEditor } from './PushRuleEditor';
|
||||||
import { SequenceCard } from '../../../components/sequence-card';
|
import { SequenceCard } from '../../../components/sequence-card';
|
||||||
import { SequenceCardStyle } from '../styles.css';
|
import { SequenceCardStyle } from '../styles.css';
|
||||||
import { SettingTile } from '../../../components/setting-tile';
|
|
||||||
import { settingsAtom, Settings } from '../../../state/settings';
|
import { settingsAtom, Settings } from '../../../state/settings';
|
||||||
import { notificationSnoozeUntilAtom } from '../../../state/notificationSnooze';
|
import { notificationSnoozeUntilAtom } from '../../../state/notificationSnooze';
|
||||||
|
|
||||||
@@ -81,7 +80,7 @@ function NotificationPresets() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Quick Presets</Text>
|
<Text size="L400">Quick presets</Text>
|
||||||
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
|
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
|
||||||
<Box gap="300" style={{ padding: config.space.S300, flexWrap: 'wrap' }}>
|
<Box gap="300" style={{ padding: config.space.S300, flexWrap: 'wrap' }}>
|
||||||
{PRESETS.map((preset) => (
|
{PRESETS.map((preset) => (
|
||||||
@@ -150,17 +149,6 @@ export function Notifications({ requestClose }: NotificationsProps) {
|
|||||||
<SpecialMessagesNotifications />
|
<SpecialMessagesNotifications />
|
||||||
<KeywordMessagesNotifications />
|
<KeywordMessagesNotifications />
|
||||||
<PushRuleEditor />
|
<PushRuleEditor />
|
||||||
<Box direction="Column" gap="100">
|
|
||||||
<Text size="L400">Block Messages</Text>
|
|
||||||
<SequenceCard
|
|
||||||
className={SequenceCardStyle}
|
|
||||||
variant="SurfaceVariant"
|
|
||||||
direction="Column"
|
|
||||||
gap="400"
|
|
||||||
>
|
|
||||||
<SettingTile description='This option has been moved to "Account > Block Users" section.' />
|
|
||||||
</SequenceCard>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
</Box>
|
||||||
</PageContent>
|
</PageContent>
|
||||||
</Scroll>
|
</Scroll>
|
||||||
|
|||||||
@@ -333,10 +333,15 @@ export function PushRuleEditor() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Text size="L400">Advanced Push Rules</Text>
|
<Text size="L400">Advanced push rules</Text>
|
||||||
<RuleSection title="Override Rules" kind={PushRuleKind.Override} rules={overrideRules} />
|
{/* [Gitea #459] Matrix terms kept, with one line on what they are. */}
|
||||||
|
<Text size="T200" priority="300">
|
||||||
|
The raw Matrix notification rules behind the options above, checked in this order: override,
|
||||||
|
room, sender, then underride. You rarely need to change these.
|
||||||
|
</Text>
|
||||||
|
<RuleSection title="Override rules" kind={PushRuleKind.Override} rules={overrideRules} />
|
||||||
<RuleSection
|
<RuleSection
|
||||||
title="Room Rules"
|
title="Room rules"
|
||||||
kind={PushRuleKind.RoomSpecific}
|
kind={PushRuleKind.RoomSpecific}
|
||||||
rules={roomRules}
|
rules={roomRules}
|
||||||
addForm={
|
addForm={
|
||||||
@@ -348,7 +353,7 @@ export function PushRuleEditor() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<RuleSection
|
<RuleSection
|
||||||
title="Sender Rules"
|
title="Sender rules"
|
||||||
kind={PushRuleKind.SenderSpecific}
|
kind={PushRuleKind.SenderSpecific}
|
||||||
rules={senderRules}
|
rules={senderRules}
|
||||||
addForm={
|
addForm={
|
||||||
@@ -359,7 +364,7 @@ export function PushRuleEditor() {
|
|||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<RuleSection title="Underride Rules" kind={PushRuleKind.Underride} rules={underrideRules} />
|
<RuleSection title="Underride rules" kind={PushRuleKind.Underride} rules={underrideRules} />
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -124,7 +124,7 @@ export function SpecialMessagesNotifications() {
|
|||||||
return (
|
return (
|
||||||
<Box direction="Column" gap="100">
|
<Box direction="Column" gap="100">
|
||||||
<Box alignItems="Center" justifyContent="SpaceBetween" gap="200">
|
<Box alignItems="Center" justifyContent="SpaceBetween" gap="200">
|
||||||
<Text size="L400">Special Messages</Text>
|
<Text size="L400">Special messages</Text>
|
||||||
<Box gap="100">
|
<Box gap="100">
|
||||||
<Text size="T200">Badge: </Text>
|
<Text size="T200">Badge: </Text>
|
||||||
<Badge radii="300" variant="Success" fill="Solid">
|
<Badge radii="300" variant="Success" fill="Solid">
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ function EmailNotification() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Email Notification"
|
title="Email notifications"
|
||||||
description={
|
description={
|
||||||
<>
|
<>
|
||||||
{result && !result.email && (
|
{result && !result.email && (
|
||||||
@@ -161,7 +161,7 @@ function PauseNotifications() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Pause Notifications"
|
title="Pause notifications"
|
||||||
description={<span style={active ? { color: color.Warning.Main } : undefined}>{status}</span>}
|
description={<span style={active ? { color: color.Warning.Main } : undefined}>{status}</span>}
|
||||||
after={
|
after={
|
||||||
active ? (
|
active ? (
|
||||||
@@ -221,7 +221,7 @@ export function SystemNotification() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Desktop Notifications"
|
title="Desktop notifications"
|
||||||
description={
|
description={
|
||||||
notifPermission === 'denied' ? (
|
notifPermission === 'denied' ? (
|
||||||
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
|
||||||
@@ -230,7 +230,7 @@ export function SystemNotification() {
|
|||||||
: 'Notifications are not supported by the system.'}
|
: 'Notifications are not supported by the system.'}
|
||||||
</Text>
|
</Text>
|
||||||
) : (
|
) : (
|
||||||
<span>Show desktop notifications when message arrive.</span>
|
<span>Show desktop notifications when messages arrive.</span>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
after={
|
after={
|
||||||
@@ -263,8 +263,8 @@ export function SystemNotification() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Notification Sound"
|
title="Notification sound"
|
||||||
description="Play sound when new message arrive."
|
description="Play a sound when a new message arrives."
|
||||||
after={<Switch value={isNotificationSounds} onChange={setIsNotificationSounds} />}
|
after={<Switch value={isNotificationSounds} onChange={setIsNotificationSounds} />}
|
||||||
/>
|
/>
|
||||||
{isNotificationSounds && (
|
{isNotificationSounds && (
|
||||||
@@ -353,7 +353,7 @@ export function SystemNotification() {
|
|||||||
gap="400"
|
gap="400"
|
||||||
>
|
>
|
||||||
<SettingTile
|
<SettingTile
|
||||||
title="Quiet Hours"
|
title="Quiet hours"
|
||||||
description="Notifications are silenced between these times. Handles overnight (e.g. 11:00 PM – 8:00 AM)."
|
description="Notifications are silenced between these times. Handles overnight (e.g. 11:00 PM – 8:00 AM)."
|
||||||
after={<Switch value={quietHoursEnabled} onChange={setQuietHoursEnabled} />}
|
after={<Switch value={quietHoursEnabled} onChange={setQuietHoursEnabled} />}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
/** Settings dialog pages. Kept apart from Settings.tsx so callers can name a
|
/** Settings dialog pages. Kept apart from Settings.tsx so callers can name a
|
||||||
* page without pulling the dialog into the entry chunk. */
|
* page without pulling the dialog into the entry chunk. */
|
||||||
export enum SettingsPages {
|
export enum SettingsPages {
|
||||||
GeneralPage,
|
|
||||||
AccountPage,
|
AccountPage,
|
||||||
|
// [Gitea #459] These replace the old catch-all General page.
|
||||||
|
AppearancePage,
|
||||||
|
MessagesPage,
|
||||||
NotificationPage,
|
NotificationPage,
|
||||||
|
CallsPage,
|
||||||
|
/** "Privacy & security": privacy options plus devices and encryption. */
|
||||||
DevicesPage,
|
DevicesPage,
|
||||||
|
DataStoragePage,
|
||||||
|
/** Desktop app only. */
|
||||||
|
DesktopPage,
|
||||||
EmojisStickersPage,
|
EmojisStickersPage,
|
||||||
|
/** "Advanced": developer tools and display plumbing. */
|
||||||
DeveloperToolsPage,
|
DeveloperToolsPage,
|
||||||
AboutPage,
|
AboutPage,
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import React, { useEffect, useRef, useState } from 'react';
|
||||||
|
import { Box, Icon, IconButton, Icons, Input, MenuItem, Text, config } from 'folds';
|
||||||
|
import { SettingsPages } from '../pages';
|
||||||
|
import { searchSettings, SettingsEntry } from './settingsIndex';
|
||||||
|
import { loadSettingsIndex } from './loadSettingsIndex';
|
||||||
|
import { isTauri } from '../../../hooks/useTauri';
|
||||||
|
|
||||||
|
type SettingsSearchProps = {
|
||||||
|
pageNames: Map<SettingsPages, string>;
|
||||||
|
/** Whether a query is active (the page list is hidden meanwhile). */
|
||||||
|
onActiveChange: (active: boolean) => void;
|
||||||
|
onPick: (entry: SettingsEntry) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [Gitea #463] Search box at the top of the settings sidebar. Ctrl/Cmd+F
|
||||||
|
* focuses it while settings are open; Esc clears it.
|
||||||
|
*/
|
||||||
|
export function SettingsSearch({ pageNames, onActiveChange, onPick }: SettingsSearchProps) {
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
const [entries, setEntries] = useState<SettingsEntry[]>();
|
||||||
|
const active = query.trim().length > 0;
|
||||||
|
|
||||||
|
useEffect(() => onActiveChange(active), [active, onActiveChange]);
|
||||||
|
|
||||||
|
const ensureIndex = () => {
|
||||||
|
if (!entries) loadSettingsIndex().then(setEntries, () => setEntries([]));
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f') {
|
||||||
|
// Capture phase + stop: settings is on top, so this beats the app's
|
||||||
|
// own Ctrl/Cmd+F (message search) underneath.
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
inputRef.current?.focus();
|
||||||
|
inputRef.current?.select();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey, true);
|
||||||
|
return () => window.removeEventListener('keydown', onKey, true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Only desktop-app options in the desktop app; only pages that exist here.
|
||||||
|
const results = entries
|
||||||
|
? searchSettings(entries, query, { desktop: isTauri() }).filter((e) => pageNames.has(e.page))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box direction="Column" gap="200" style={{ padding: `0 ${config.space.S200}` }}>
|
||||||
|
<Input
|
||||||
|
ref={inputRef}
|
||||||
|
size="400"
|
||||||
|
variant="Background"
|
||||||
|
radii="400"
|
||||||
|
placeholder="Search settings"
|
||||||
|
aria-label="Search settings"
|
||||||
|
value={query}
|
||||||
|
onFocus={ensureIndex}
|
||||||
|
onChange={(e) => {
|
||||||
|
ensureIndex();
|
||||||
|
setQuery(e.currentTarget.value);
|
||||||
|
}}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Escape' && query) {
|
||||||
|
e.stopPropagation();
|
||||||
|
setQuery('');
|
||||||
|
}
|
||||||
|
if (e.key === 'Enter' && results[0]) {
|
||||||
|
onPick(results[0]);
|
||||||
|
setQuery('');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
before={<Icon size="100" src={Icons.Search} />}
|
||||||
|
after={
|
||||||
|
query ? (
|
||||||
|
<IconButton
|
||||||
|
size="300"
|
||||||
|
radii="300"
|
||||||
|
variant="Background"
|
||||||
|
aria-label="Clear search"
|
||||||
|
onClick={() => setQuery('')}
|
||||||
|
>
|
||||||
|
<Icon size="50" src={Icons.Cross} />
|
||||||
|
</IconButton>
|
||||||
|
) : undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{active && (
|
||||||
|
<Box direction="Column" role="list" aria-label="Matching settings">
|
||||||
|
{entries === undefined && (
|
||||||
|
<Text size="T200" priority="300" style={{ padding: config.space.S200 }}>
|
||||||
|
Searching…
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{entries !== undefined && results.length === 0 && (
|
||||||
|
<Text size="T200" priority="300" style={{ padding: config.space.S200 }}>
|
||||||
|
No settings match “{query.trim()}”.
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
{results.map((r) => (
|
||||||
|
<MenuItem
|
||||||
|
key={`${r.page}-${r.title}`}
|
||||||
|
role="listitem"
|
||||||
|
variant="Background"
|
||||||
|
radii="400"
|
||||||
|
onClick={() => {
|
||||||
|
onPick(r);
|
||||||
|
setQuery('');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box direction="Column" style={{ padding: `${config.space.S100} 0`, minWidth: 0 }}>
|
||||||
|
<Text size="T300" truncate>
|
||||||
|
{r.title}
|
||||||
|
</Text>
|
||||||
|
<Text size="T200" priority="300" truncate>
|
||||||
|
{pageNames.get(r.page)}
|
||||||
|
{r.section && r.section !== r.title ? ` · ${r.section}` : ''}
|
||||||
|
</Text>
|
||||||
|
</Box>
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { parseSettingsSource, SettingsEntry } from './settingsIndex';
|
||||||
|
|
||||||
|
// [Gitea #463] The settings source, as text, in its own lazily loaded chunk:
|
||||||
|
// fetched the first time someone searches, never at startup.
|
||||||
|
const sources = import.meta.glob(['../**/*.tsx', '!../**/*.test.tsx'], {
|
||||||
|
query: '?raw',
|
||||||
|
import: 'default',
|
||||||
|
}) as Record<string, () => Promise<string>>;
|
||||||
|
|
||||||
|
let index: Promise<SettingsEntry[]> | undefined;
|
||||||
|
|
||||||
|
export const loadSettingsIndex = (): Promise<SettingsEntry[]> => {
|
||||||
|
index ??= Promise.all(
|
||||||
|
Object.entries(sources).map(async ([path, load]) =>
|
||||||
|
// '../general/General.tsx' -> '/general/General.tsx' (what the parser matches)
|
||||||
|
parseSettingsSource(path.replace(/^\.\./, ''), await load()),
|
||||||
|
),
|
||||||
|
).then((all) => all.flat());
|
||||||
|
return index;
|
||||||
|
};
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import { parseSettingsSource, searchSettings } from './settingsIndex';
|
||||||
|
import { SettingsPages } from '../pages';
|
||||||
|
|
||||||
|
const general = fs.readFileSync('src/app/features/settings/general/General.tsx', 'utf8');
|
||||||
|
const devices = fs.readFileSync('src/app/features/settings/devices/Devices.tsx', 'utf8');
|
||||||
|
const sys = fs.readFileSync(
|
||||||
|
'src/app/features/settings/notifications/SystemNotification.tsx',
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
const entries = [
|
||||||
|
...parseSettingsSource('src/app/features/settings/general/General.tsx', general),
|
||||||
|
...parseSettingsSource('src/app/features/settings/devices/Devices.tsx', devices),
|
||||||
|
...parseSettingsSource('src/app/features/settings/notifications/SystemNotification.tsx', sys),
|
||||||
|
];
|
||||||
|
const find = (t: string) => entries.find((e) => e.title === t);
|
||||||
|
|
||||||
|
test('[#463] indexes the real settings source with the right pages', () => {
|
||||||
|
assert.equal(find('Push to deafen')?.page, SettingsPages.CallsPage);
|
||||||
|
assert.equal(find('Strip tracking parameters from links')?.page, SettingsPages.DevicesPage);
|
||||||
|
assert.equal(find('Page zoom')?.page, SettingsPages.AppearancePage);
|
||||||
|
assert.equal(find('Enter for a new line')?.page, SettingsPages.MessagesPage);
|
||||||
|
assert.equal(find('Show hidden events')?.page, SettingsPages.DeveloperToolsPage);
|
||||||
|
assert.equal(find('Device verification')?.page, SettingsPages.DevicesPage);
|
||||||
|
assert.equal(find('Quiet hours')?.page, SettingsPages.NotificationPage);
|
||||||
|
assert.equal(find('Launch on login')?.desktopOnly, true);
|
||||||
|
assert.match(find('Strip tracking parameters from links')?.description ?? '', /utm_/);
|
||||||
|
assert.ok(entries.length > 70, `indexed ${entries.length}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[#463] search: words anywhere, title first, desktop-only hidden in a browser', () => {
|
||||||
|
assert.equal(searchSettings(entries, 'deafen')[0]?.title, 'Push to deafen');
|
||||||
|
assert.equal(
|
||||||
|
searchSettings(entries, 'tracking')[0]?.title,
|
||||||
|
'Strip tracking parameters from links',
|
||||||
|
);
|
||||||
|
assert.equal(searchSettings(entries, 'zoom')[0]?.title, 'Page zoom');
|
||||||
|
assert.ok(searchSettings(entries, 'utm').some((e) => e.title.startsWith('Strip tracking')));
|
||||||
|
assert.equal(searchSettings(entries, 'launch on login').length, 0);
|
||||||
|
assert.equal(
|
||||||
|
searchSettings(entries, 'launch on login', { desktop: true })[0]?.title,
|
||||||
|
'Launch on login',
|
||||||
|
);
|
||||||
|
assert.deepEqual(searchSettings(entries, ' '), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[#463] parser handles the attribute forms and skips dynamic titles', () => {
|
||||||
|
const src = `
|
||||||
|
<Text size="L400">Things</Text>
|
||||||
|
<SettingTile title="Plain" description="A & B" after={<Switch value={x} />} />
|
||||||
|
<SettingTile title={'Quoted'} description={\`tick\`} />
|
||||||
|
<SettingTile title={\`Dynamic \${name}\`} />
|
||||||
|
<SettingTile title={someVar} />`;
|
||||||
|
const got = parseSettingsSource('src/app/features/settings/about/About.tsx', src);
|
||||||
|
assert.deepEqual(
|
||||||
|
got.map((e) => [e.title, e.description, e.section]),
|
||||||
|
[
|
||||||
|
['Plain', 'A & B', 'Things'],
|
||||||
|
['Quoted', 'tick', 'Things'],
|
||||||
|
['Things', '', undefined],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import { SettingsPages } from '../pages';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [Gitea #463] Search across all settings. The index is built from the
|
||||||
|
* settings source itself (each <SettingTile title=… description=…> and each
|
||||||
|
* section header), so options added later are found without a hand-kept list.
|
||||||
|
* Pure: path + source text in, entries out.
|
||||||
|
*/
|
||||||
|
export type SettingsEntry = {
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
page: SettingsPages;
|
||||||
|
/** Section header the setting sits under, when known. */
|
||||||
|
section?: string;
|
||||||
|
/** Desktop-only (hidden in a browser). */
|
||||||
|
desktopOnly?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
// General.tsx: which page each section (or helper used by a section) is on.
|
||||||
|
const GENERAL_SECTIONS: Record<string, SettingsPages> = {
|
||||||
|
Appearance: SettingsPages.AppearancePage,
|
||||||
|
SystemThemePreferences: SettingsPages.AppearancePage,
|
||||||
|
SelectTheme: SettingsPages.AppearancePage,
|
||||||
|
PageZoomInput: SettingsPages.AppearancePage,
|
||||||
|
CollapsiblePicker: SettingsPages.AppearancePage,
|
||||||
|
SeasonalBgGrid: SettingsPages.AppearancePage,
|
||||||
|
ChatBgGrid: SettingsPages.AppearancePage,
|
||||||
|
Messages: SettingsPages.MessagesPage,
|
||||||
|
SelectMessageLayout: SettingsPages.MessagesPage,
|
||||||
|
SelectMessageSpacing: SettingsPages.MessagesPage,
|
||||||
|
Editor: SettingsPages.MessagesPage,
|
||||||
|
ComposerToolbarReorder: SettingsPages.MessagesPage,
|
||||||
|
ComposerToolbarButtonRow: SettingsPages.MessagesPage,
|
||||||
|
DateAndTime: SettingsPages.MessagesPage,
|
||||||
|
SelectDateFormat: SettingsPages.MessagesPage,
|
||||||
|
DateHint: SettingsPages.MessagesPage,
|
||||||
|
CustomDateFormat: SettingsPages.MessagesPage,
|
||||||
|
PresetDateFormat: SettingsPages.MessagesPage,
|
||||||
|
Calls: SettingsPages.CallsPage,
|
||||||
|
Privacy: SettingsPages.DevicesPage,
|
||||||
|
SettingsSyncSection: SettingsPages.DataStoragePage,
|
||||||
|
AdvancedDisplayOptions: SettingsPages.DeveloperToolsPage,
|
||||||
|
DesktopChromeSetting: SettingsPages.DesktopPage,
|
||||||
|
AutostartSetting: SettingsPages.DesktopPage,
|
||||||
|
KeychainMirrorSetting: SettingsPages.DesktopPage,
|
||||||
|
DesktopSettings: SettingsPages.DesktopPage,
|
||||||
|
PackageUpdate: SettingsPages.DesktopPage,
|
||||||
|
AppUpdates: SettingsPages.DesktopPage,
|
||||||
|
};
|
||||||
|
|
||||||
|
const FOLDER_PAGES: [RegExp, SettingsPages][] = [
|
||||||
|
[/\/account\//, SettingsPages.AccountPage],
|
||||||
|
[/\/notifications\//, SettingsPages.NotificationPage],
|
||||||
|
[/\/devices\//, SettingsPages.DevicesPage],
|
||||||
|
[/\/developer(-tools)?\//, SettingsPages.DeveloperToolsPage],
|
||||||
|
[/\/emojis-stickers\//, SettingsPages.EmojisStickersPage],
|
||||||
|
[/\/about\//, SettingsPages.AboutPage],
|
||||||
|
[/\/general\/(StorageUsage|YourData)\.tsx$/, SettingsPages.DataStoragePage],
|
||||||
|
];
|
||||||
|
|
||||||
|
const decode = (s: string): string =>
|
||||||
|
s
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/'|'/g, "'")
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/\\'/g, "'")
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
/** A JSX attribute's static text: "…", {'…'}, {"…"} or {`…`} without ${}. */
|
||||||
|
const attr = (tag: string, name: string): string | undefined => {
|
||||||
|
const m = new RegExp(
|
||||||
|
`\\b${name}=(?:"([^"]*)"|\\{\\s*'((?:[^'\\\\]|\\\\.)*)'\\s*\\}|\\{\\s*"([^"]*)"\\s*\\}|\\{\\s*\`([^\`$]*)\`\\s*\\})`,
|
||||||
|
).exec(tag);
|
||||||
|
const v = m && (m[1] ?? m[2] ?? m[3] ?? m[4]);
|
||||||
|
return v ? decode(v) : undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The opening tag starting at `start` (up to the matching '>' outside braces/strings). */
|
||||||
|
const openingTag = (src: string, start: number): string => {
|
||||||
|
let depth = 0;
|
||||||
|
let quote: string | null = null;
|
||||||
|
for (let i = start; i < src.length; i += 1) {
|
||||||
|
const c = src[i];
|
||||||
|
if (quote) {
|
||||||
|
if (c === quote && src[i - 1] !== '\\') quote = null;
|
||||||
|
} else if (c === '"' || c === "'" || c === '`') quote = c;
|
||||||
|
else if (c === '{') depth += 1;
|
||||||
|
else if (c === '}') depth -= 1;
|
||||||
|
else if (c === '>' && depth === 0) return src.slice(start, i + 1);
|
||||||
|
}
|
||||||
|
return src.slice(start);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseSettingsSource = (path: string, src: string): SettingsEntry[] => {
|
||||||
|
const isGeneral = /\/general\/General\.tsx$/.test(path);
|
||||||
|
const folderPage = FOLDER_PAGES.find(([re]) => re.test(path))?.[1];
|
||||||
|
if (!isGeneral && folderPage === undefined) return [];
|
||||||
|
|
||||||
|
// For General.tsx: positions of each top-level function, to know the section.
|
||||||
|
const fns = isGeneral
|
||||||
|
? [...src.matchAll(/\n(?:export )?function (\w+)\(/g)].map((m) => ({
|
||||||
|
at: m.index ?? 0,
|
||||||
|
name: m[1],
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
const pageAt = (pos: number): SettingsPages | undefined => {
|
||||||
|
if (!isGeneral) return folderPage;
|
||||||
|
let name: string | undefined;
|
||||||
|
fns.forEach((f) => {
|
||||||
|
if (f.at < pos) name = f.name;
|
||||||
|
});
|
||||||
|
return name ? GENERAL_SECTIONS[name] : undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
const out: SettingsEntry[] = [];
|
||||||
|
const headers = [...src.matchAll(/<Text size="L400">([^<{]+)<\/Text>/g)].map((m) => ({
|
||||||
|
at: m.index ?? 0,
|
||||||
|
text: decode(m[1]),
|
||||||
|
}));
|
||||||
|
const sectionAt = (pos: number): string | undefined => {
|
||||||
|
let s: string | undefined;
|
||||||
|
headers.forEach((h) => {
|
||||||
|
if (h.at < pos) s = h.text;
|
||||||
|
});
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const m of src.matchAll(/<SettingTile\b/g)) {
|
||||||
|
const at = m.index ?? 0;
|
||||||
|
const tag = openingTag(src, at);
|
||||||
|
const title = attr(tag, 'title');
|
||||||
|
const page = pageAt(at);
|
||||||
|
if (title && page !== undefined) {
|
||||||
|
out.push({
|
||||||
|
title,
|
||||||
|
description: attr(tag, 'description') ?? '',
|
||||||
|
page,
|
||||||
|
section: sectionAt(at),
|
||||||
|
desktopOnly: page === SettingsPages.DesktopPage || undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
headers.forEach((h) => {
|
||||||
|
const page = pageAt(h.at);
|
||||||
|
if (page !== undefined && !out.some((e) => e.title === h.text && e.page === page)) {
|
||||||
|
out.push({
|
||||||
|
title: h.text,
|
||||||
|
description: '',
|
||||||
|
page,
|
||||||
|
desktopOnly: page === SettingsPages.DesktopPage || undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
const norm = (s: string): string => s.toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pure: rank entries for a query. Every word must appear in the title,
|
||||||
|
* description or section; title matches rank first.
|
||||||
|
*/
|
||||||
|
export const searchSettings = (
|
||||||
|
entries: SettingsEntry[],
|
||||||
|
query: string,
|
||||||
|
{ desktop = false, limit = 30 }: { desktop?: boolean; limit?: number } = {},
|
||||||
|
): SettingsEntry[] => {
|
||||||
|
const words = norm(query).split(/\s+/).filter(Boolean);
|
||||||
|
if (words.length === 0) return [];
|
||||||
|
const scored: { e: SettingsEntry; score: number }[] = [];
|
||||||
|
entries.forEach((e) => {
|
||||||
|
if (e.desktopOnly && !desktop) return;
|
||||||
|
const title = norm(e.title);
|
||||||
|
const rest = norm(`${e.description} ${e.section ?? ''}`);
|
||||||
|
let score = 0;
|
||||||
|
const all = words.every((w) => {
|
||||||
|
if (title.startsWith(w)) score += 3;
|
||||||
|
else if (title.includes(w)) score += 2;
|
||||||
|
else if (rest.includes(w)) score += 1;
|
||||||
|
else return false;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
if (all) scored.push({ e, score });
|
||||||
|
});
|
||||||
|
return scored
|
||||||
|
.sort((a, b) => b.score - a.score || a.e.title.localeCompare(b.e.title))
|
||||||
|
.slice(0, limit)
|
||||||
|
.map((s) => s.e);
|
||||||
|
};
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useEffect, useRef } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import { SetPresence } from 'matrix-js-sdk';
|
import { SetPresence } from 'matrix-js-sdk';
|
||||||
import { PresenceDeduper, PresenceWrite, writePresence } from '../utils/presenceWrite';
|
import { PresenceDeduper, PresenceWrite, queuePresenceWrite } from '../utils/presenceWrite';
|
||||||
import { useMatrixClient } from './useMatrixClient';
|
import { useMatrixClient } from './useMatrixClient';
|
||||||
import { getLastLocalStatusWrite, pickHeartbeatStatus } from '../utils/ownStatusSync';
|
import { getLastLocalStatusWrite, pickHeartbeatStatus } from '../utils/ownStatusSync';
|
||||||
import { useSetting } from '../state/hooks/settings';
|
import { useSetting } from '../state/hooks/settings';
|
||||||
@@ -70,9 +70,25 @@ export function usePresenceUpdater() {
|
|||||||
// by all devices) and /sync already keeps us online — only send when the
|
// by all devices) and /sync already keeps us online — only send when the
|
||||||
// state or status actually changes, so a manual status save isn't 429'd
|
// state or status actually changes, so a manual status save isn't 429'd
|
||||||
// by a heartbeat that changed nothing.
|
// by a heartbeat that changed nothing.
|
||||||
|
// What the server reported in the last resolveStatus() (consumed by send).
|
||||||
|
let serverNow: { presence: string; status_msg?: string } | undefined;
|
||||||
const send = (write: PresenceWrite, label: string) => {
|
const send = (write: PresenceWrite, label: string) => {
|
||||||
|
const server = serverNow;
|
||||||
|
serverNow = undefined;
|
||||||
if (!deduper.shouldSend(write)) return Promise.resolve();
|
if (!deduper.shouldSend(write)) return Promise.resolve();
|
||||||
return writePresence(mx, write)
|
// The server already shows exactly this (e.g. /sync keeps us online and
|
||||||
|
// the status is unchanged): writing it again would only spend the
|
||||||
|
// 10-second budget a status save may need next.
|
||||||
|
if (
|
||||||
|
server &&
|
||||||
|
server.presence === write.presence &&
|
||||||
|
(server.status_msg ?? '') === (write.status_msg ?? '')
|
||||||
|
) {
|
||||||
|
deduper.sent(write);
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
// Shared queue with the status save: waits out a 429, newest write wins.
|
||||||
|
return queuePresenceWrite(mx, write)
|
||||||
.then(() => deduper.sent(write))
|
.then(() => deduper.sent(write))
|
||||||
.catch((err) => warnPresenceFailure(label, err));
|
.catch((err) => warnPresenceFailure(label, err));
|
||||||
};
|
};
|
||||||
@@ -84,6 +100,7 @@ export function usePresenceUpdater() {
|
|||||||
const local = readStatus();
|
const local = readStatus();
|
||||||
if (!userId) return local;
|
if (!userId) return local;
|
||||||
const server = await mx.getPresence(userId).catch(() => undefined);
|
const server = await mx.getPresence(userId).catch(() => undefined);
|
||||||
|
serverNow = server;
|
||||||
const status = pickHeartbeatStatus({
|
const status = pickHeartbeatStatus({
|
||||||
local,
|
local,
|
||||||
server,
|
server,
|
||||||
|
|||||||
@@ -140,7 +140,7 @@ export function useSettingsSync(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Manual actions for Settings → General → Sync. `pushNow` stamps a fresh
|
* Manual actions for Settings → Data & storage → Sync. `pushNow` stamps a fresh
|
||||||
* snapshot of THIS device so it wins on every other device; `clearRemote`
|
* snapshot of THIS device so it wins on every other device; `clearRemote`
|
||||||
* blanks the account-data event (other devices ignore the invalid content and
|
* blanks the account-data event (other devices ignore the invalid content and
|
||||||
* keep their local settings until someone pushes again).
|
* keep their local settings until someone pushes again).
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
import { useAtomValue } from 'jotai';
|
||||||
|
import { immersiveCallAtom } from '../state/callEmbed';
|
||||||
import { useCallEmbed } from '../hooks/useCallEmbed';
|
import { useCallEmbed } from '../hooks/useCallEmbed';
|
||||||
import { CallStatus } from '../features/call-status';
|
import { CallStatus } from '../features/call-status';
|
||||||
import { useSelectedRoom } from '../hooks/router/useSelectedRoom';
|
import { useSelectedRoom } from '../hooks/router/useSelectedRoom';
|
||||||
@@ -9,8 +11,10 @@ export function CallStatusRenderer() {
|
|||||||
const selectedRoom = useSelectedRoom();
|
const selectedRoom = useSelectedRoom();
|
||||||
|
|
||||||
const screenSize = useScreenSizeContext();
|
const screenSize = useScreenSizeContext();
|
||||||
|
// [Gitea #126] The full-screen call has its own controls.
|
||||||
|
const immersive = useAtomValue(immersiveCallAtom);
|
||||||
|
|
||||||
if (!callEmbed) return null;
|
if (!callEmbed || immersive) return null;
|
||||||
|
|
||||||
if (screenSize === ScreenSize.Mobile && callEmbed.roomId === selectedRoom) return null;
|
if (screenSize === ScreenSize.Mobile && callEmbed.roomId === selectedRoom) return null;
|
||||||
|
|
||||||
|
|||||||
@@ -1015,13 +1015,13 @@ function TauriUpdateFeature() {
|
|||||||
dismissToast(UPDATE_PROGRESS_TOAST);
|
dismissToast(UPDATE_PROGRESS_TOAST);
|
||||||
if (!failure) return;
|
if (!failure) return;
|
||||||
// Short on purpose; the full explanation and a Download installer button
|
// Short on purpose; the full explanation and a Download installer button
|
||||||
// are in Settings → General → App Updates.
|
// are in Settings → Desktop → App updates.
|
||||||
const busy = failure.phase !== 'install' && isNetworkUpdateError(failure.message);
|
const busy = failure.phase !== 'install' && isNetworkUpdateError(failure.message);
|
||||||
setToast({
|
setToast({
|
||||||
id: UPDATE_FAILED_TOAST,
|
id: UPDATE_FAILED_TOAST,
|
||||||
iconSrc: Icons.Warning,
|
iconSrc: Icons.Warning,
|
||||||
displayName: 'Update didn’t install',
|
displayName: 'Update didn’t install',
|
||||||
body: `${busy ? 'The update server seems busy. ' : ''}Click to try again, or get the installer in Settings → General → App Updates.`,
|
body: `${busy ? 'The update server seems busy. ' : ''}Click to try again, or get the installer in Settings → Desktop → App updates.`,
|
||||||
roomName: 'System',
|
roomName: 'System',
|
||||||
roomId: '',
|
roomId: '',
|
||||||
sticky: true,
|
sticky: true,
|
||||||
@@ -1062,7 +1062,7 @@ function TauriUpdateFeature() {
|
|||||||
roomName: 'System',
|
roomName: 'System',
|
||||||
roomId: '',
|
roomId: '',
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
if (viaPackage) requestSettings('general');
|
if (viaPackage) requestSettings('desktop');
|
||||||
else installFromToast();
|
else installFromToast();
|
||||||
},
|
},
|
||||||
sticky: true,
|
sticky: true,
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ import { AutoDiscovery } from './AutoDiscovery';
|
|||||||
|
|
||||||
// Capture-only E2EE diagnostics ring buffer (KE-1→4 signatures) — installed at
|
// Capture-only E2EE diagnostics ring buffer (KE-1→4 signatures) — installed at
|
||||||
// module load so it sees crypto warnings from the very first sync. Idempotent;
|
// module load so it sees crypto warnings from the very first sync. Idempotent;
|
||||||
// report download lives in Settings → Developer Tools → Crypto Diagnostics.
|
// report download lives in Settings → Advanced → Crypto diagnostics.
|
||||||
installCryptoDiagLog();
|
installCryptoDiagLog();
|
||||||
|
|
||||||
function ClientRootLoading() {
|
function ClientRootLoading() {
|
||||||
|
|||||||
@@ -72,8 +72,8 @@ export function KeyUploadBanner() {
|
|||||||
rejects every new upload and other people can't start fresh encrypted sessions
|
rejects every new upload and other people can't start fresh encrypted sessions
|
||||||
with you. This usually happens after the browser cleared this site's storage
|
with you. This usually happens after the browser cleared this site's storage
|
||||||
while you stayed signed in. Before signing out, make sure this device is verified or
|
while you stayed signed in. Before signing out, make sure this device is verified or
|
||||||
key backup is on (Settings → Devices), so your message history comes back when you
|
key backup is on (Settings → Privacy & security), so your message history comes back
|
||||||
sign in again.
|
when you sign in again.
|
||||||
</Text>
|
</Text>
|
||||||
{lastError && (
|
{lastError && (
|
||||||
<Text size="T200" align="Center" priority="300" style={{ wordBreak: 'break-word' }}>
|
<Text size="T200" align="Center" priority="300" style={{ wordBreak: 'break-word' }}>
|
||||||
|
|||||||
@@ -180,7 +180,10 @@ export function SettingsTab() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!settingsRequest) return;
|
if (!settingsRequest) return;
|
||||||
const page = {
|
const page = {
|
||||||
general: SettingsPages.GeneralPage,
|
// [Gitea #459] General is gone; its old deep links land on Appearance.
|
||||||
|
general: SettingsPages.AppearancePage,
|
||||||
|
appearance: SettingsPages.AppearancePage,
|
||||||
|
desktop: SettingsPages.DesktopPage,
|
||||||
account: SettingsPages.AccountPage,
|
account: SettingsPages.AccountPage,
|
||||||
notifications: SettingsPages.NotificationPage,
|
notifications: SettingsPages.NotificationPage,
|
||||||
devices: SettingsPages.DevicesPage,
|
devices: SettingsPages.DevicesPage,
|
||||||
|
|||||||
@@ -18,3 +18,6 @@ export const callEmbedAtom = atom<CallEmbed | undefined, [CallEmbed | undefined]
|
|||||||
);
|
);
|
||||||
|
|
||||||
export const callChatAtom = atom<boolean>(false);
|
export const callChatAtom = atom<boolean>(false);
|
||||||
|
|
||||||
|
/** [Gitea #126] The call is full screen (phone turned sideways). */
|
||||||
|
export const immersiveCallAtom = atom<boolean>(false);
|
||||||
@@ -1,6 +1,12 @@
|
|||||||
import { atom } from 'jotai';
|
import { atom } from 'jotai';
|
||||||
|
|
||||||
export type SettingsRequestPage = 'general' | 'account' | 'notifications' | 'devices';
|
export type SettingsRequestPage =
|
||||||
|
| 'general'
|
||||||
|
| 'account'
|
||||||
|
| 'notifications'
|
||||||
|
| 'devices'
|
||||||
|
| 'desktop'
|
||||||
|
| 'appearance';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ask the sidebar to open User Settings at a page from anywhere in the app
|
* Ask the sidebar to open User Settings at a page from anywhere in the app
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { atom } from 'jotai';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [Gitea #113] Session ids the stale-sessions nudge's Review asked Settings →
|
||||||
|
* Devices to tick for sign-out. Consumed (and cleared) by OtherDevices.
|
||||||
|
*/
|
||||||
|
export const preselectSignOutAtom = atom<string[]>([]);
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { buildExport, mergeData, parseExport, planImport } from './dataExport';
|
||||||
|
|
||||||
|
const file = buildExport({
|
||||||
|
userId: '@a:hs',
|
||||||
|
accountData: {
|
||||||
|
'io.lotus.bookmarks': { bookmarks: [{ id: 'b1', note: 'x' }] },
|
||||||
|
'io.lotus.user_notes': { notes: { '@b:hs': 'met at LAN party' } },
|
||||||
|
'm.direct': { secret: true },
|
||||||
|
'io.lotus.settings': { theme: 'dark', fontSize: 16 },
|
||||||
|
},
|
||||||
|
decoration: 'halo',
|
||||||
|
localSettings: { callNoiseSuppression: 'ml' },
|
||||||
|
now: new Date('2026-10-25T00:00:00Z'),
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[#114] export keeps only our own types', () => {
|
||||||
|
assert.equal(file.format, 'lotus-chat-data');
|
||||||
|
assert.equal(file.version, 1);
|
||||||
|
assert.deepEqual(Object.keys(file.accountData).sort(), [
|
||||||
|
'io.lotus.bookmarks',
|
||||||
|
'io.lotus.settings',
|
||||||
|
'io.lotus.user_notes',
|
||||||
|
]);
|
||||||
|
assert.equal(file.profile.decoration, 'halo');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[#114] parse: round trip, wrong files, newer versions, foreign types', () => {
|
||||||
|
const r = parseExport(JSON.stringify(file));
|
||||||
|
assert.ok(r.ok);
|
||||||
|
assert.equal(parseExport('nope').ok, false);
|
||||||
|
assert.equal(parseExport('{"format":"other"}').ok, false);
|
||||||
|
const newer = parseExport(JSON.stringify({ ...file, version: 2 }));
|
||||||
|
assert.ok(!newer.ok && /newer Lotus Chat/.test(newer.error));
|
||||||
|
const sneaky = parseExport(
|
||||||
|
JSON.stringify({ ...file, accountData: { 'm.push_rules': {}, 'io.lotus.bookmarks': {} } }),
|
||||||
|
);
|
||||||
|
assert.ok(sneaky.ok);
|
||||||
|
assert.deepEqual(Object.keys(sneaky.file.accountData), ['io.lotus.bookmarks']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[#114] merge: lists by id, maps by key, conflicts kept unless preferred', () => {
|
||||||
|
const mine = { bookmarks: [{ id: 'b1', note: 'mine' }, { id: 'b2' }] };
|
||||||
|
const theirs = { bookmarks: [{ id: 'b1', note: 'theirs' }, { id: 'b3' }] };
|
||||||
|
const keep = mergeData(mine, theirs);
|
||||||
|
assert.equal(keep.added, 1);
|
||||||
|
assert.equal(keep.conflicts, 1);
|
||||||
|
assert.deepEqual(keep.value, {
|
||||||
|
bookmarks: [{ id: 'b1', note: 'mine' }, { id: 'b2' }, { id: 'b3' }],
|
||||||
|
});
|
||||||
|
const take = mergeData(mine, theirs, true);
|
||||||
|
assert.deepEqual((take.value as typeof mine).bookmarks[0], { id: 'b1', note: 'theirs' });
|
||||||
|
|
||||||
|
const notes = mergeData({ a: 1, b: 2 }, { b: 3, c: 4 });
|
||||||
|
assert.deepEqual(notes, { value: { a: 1, b: 2, c: 4 }, added: 1, conflicts: 1 });
|
||||||
|
assert.deepEqual(mergeData(undefined, { x: 1 }), { value: { x: 1 }, added: 1, conflicts: 0 });
|
||||||
|
assert.deepEqual(mergeData(['a'], ['a', 'b']).value, ['a', 'b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[#114] plan summarises per category', () => {
|
||||||
|
const plan = planImport(file, {
|
||||||
|
accountData: { 'io.lotus.settings': { theme: 'light' } },
|
||||||
|
decoration: null,
|
||||||
|
localSettings: { callNoiseSuppression: 'ml' },
|
||||||
|
});
|
||||||
|
const by = Object.fromEntries(plan.map((p) => [p.key, p]));
|
||||||
|
assert.deepEqual(
|
||||||
|
[by['io.lotus.settings'].added, by['io.lotus.settings'].conflicts],
|
||||||
|
[1, 1],
|
||||||
|
'fontSize new, theme differs',
|
||||||
|
);
|
||||||
|
assert.equal(by['io.lotus.bookmarks'].added, 1);
|
||||||
|
assert.equal(by['profile.decoration'].added, 1);
|
||||||
|
assert.deepEqual([by['local.settings'].added, by['local.settings'].conflicts], [0, 0]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
/**
|
||||||
|
* [Gitea #114] Export / import "your data": the Lotus-side personal data of
|
||||||
|
* an account (not message history, not encryption keys: those have their own
|
||||||
|
* exports, and keys are secret). One JSON file:
|
||||||
|
*
|
||||||
|
* { format: 'lotus-chat-data', version: 1, exportedAt, userId,
|
||||||
|
* accountData: { [type]: content }, profile: { decoration }, local: { settings } }
|
||||||
|
*
|
||||||
|
* Import MERGES: anything missing here is added; a value that differs is a
|
||||||
|
* conflict, kept as it is unless the user chooses the file's. Pure helpers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const EXPORT_FORMAT = 'lotus-chat-data';
|
||||||
|
export const EXPORT_VERSION = 1;
|
||||||
|
|
||||||
|
/** The account-data types that are the user's own Lotus data, with labels. */
|
||||||
|
export const EXPORT_ACCOUNT_DATA: { type: string; label: string }[] = [
|
||||||
|
{ type: 'io.lotus.settings', label: 'Synced settings' },
|
||||||
|
{ type: 'io.lotus.bookmarks', label: 'Bookmarks' },
|
||||||
|
{ type: 'io.lotus.user_notes', label: 'Private notes about people' },
|
||||||
|
{ type: 'io.lotus.room_names', label: 'Your names for rooms' },
|
||||||
|
{ type: 'in.cinny.spaces', label: 'Room sections and sidebar' },
|
||||||
|
{ type: 'io.lotus.reminders', label: 'Reminders' },
|
||||||
|
{ type: 'io.lotus.status_presets', label: 'Status presets' },
|
||||||
|
{ type: 'io.lotus.thread_notifications', label: 'Thread notification settings' },
|
||||||
|
{ type: 'io.lotus.mute_timers', label: 'Timed mutes' },
|
||||||
|
{ type: 'io.lotus.soundboard', label: 'Soundboard (clips stay on the server)' },
|
||||||
|
{ type: 'io.lotus.soundboard_rooms', label: 'Soundboards enabled everywhere' },
|
||||||
|
{ type: 'im.ponies.user_emotes', label: 'Your emoji and stickers' },
|
||||||
|
{ type: 'im.ponies.emote_rooms', label: 'Emoji packs enabled everywhere' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export type ExportFile = {
|
||||||
|
format: typeof EXPORT_FORMAT;
|
||||||
|
version: number;
|
||||||
|
exportedAt: string;
|
||||||
|
userId: string;
|
||||||
|
accountData: Record<string, unknown>;
|
||||||
|
profile: { decoration: string | null };
|
||||||
|
local: { settings: Record<string, unknown> | null };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const buildExport = (input: {
|
||||||
|
userId: string;
|
||||||
|
accountData: Record<string, unknown>;
|
||||||
|
decoration: string | null;
|
||||||
|
localSettings: Record<string, unknown> | null;
|
||||||
|
now?: Date;
|
||||||
|
}): ExportFile => {
|
||||||
|
const accountData: Record<string, unknown> = {};
|
||||||
|
EXPORT_ACCOUNT_DATA.forEach(({ type }) => {
|
||||||
|
const c = input.accountData[type];
|
||||||
|
if (c !== undefined && c !== null) accountData[type] = c;
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
format: EXPORT_FORMAT,
|
||||||
|
version: EXPORT_VERSION,
|
||||||
|
exportedAt: (input.now ?? new Date()).toISOString(),
|
||||||
|
userId: input.userId,
|
||||||
|
accountData,
|
||||||
|
profile: { decoration: input.decoration },
|
||||||
|
local: { settings: input.localSettings },
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const isObject = (v: unknown): v is Record<string, unknown> =>
|
||||||
|
!!v && typeof v === 'object' && !Array.isArray(v);
|
||||||
|
|
||||||
|
export type ParseResult = { ok: true; file: ExportFile } | { ok: false; error: string };
|
||||||
|
|
||||||
|
/** Validate an imported file; older versions would be migrated here. */
|
||||||
|
export const parseExport = (text: string): ParseResult => {
|
||||||
|
let v: unknown;
|
||||||
|
try {
|
||||||
|
v = JSON.parse(text);
|
||||||
|
} catch {
|
||||||
|
return { ok: false, error: "This isn't a Lotus Chat data file (it isn't valid JSON)." };
|
||||||
|
}
|
||||||
|
if (!isObject(v) || v.format !== EXPORT_FORMAT)
|
||||||
|
return { ok: false, error: "This isn't a Lotus Chat data file." };
|
||||||
|
if (typeof v.version !== 'number' || v.version < 1)
|
||||||
|
return { ok: false, error: 'This data file is damaged (no version).' };
|
||||||
|
if (v.version > EXPORT_VERSION)
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
error: 'This file was made by a newer Lotus Chat. Update the app, then import it again.',
|
||||||
|
};
|
||||||
|
const accountData = isObject(v.accountData) ? v.accountData : {};
|
||||||
|
const known = new Set(EXPORT_ACCOUNT_DATA.map((t) => t.type));
|
||||||
|
const filtered: Record<string, unknown> = {};
|
||||||
|
Object.entries(accountData).forEach(([type, content]) => {
|
||||||
|
// Only our own types: a file can't be used to write arbitrary account data.
|
||||||
|
if (known.has(type) && content !== null && content !== undefined) filtered[type] = content;
|
||||||
|
});
|
||||||
|
const profile = isObject(v.profile) ? v.profile : {};
|
||||||
|
const local = isObject(v.local) ? v.local : {};
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
file: {
|
||||||
|
format: EXPORT_FORMAT,
|
||||||
|
version: v.version,
|
||||||
|
exportedAt: typeof v.exportedAt === 'string' ? v.exportedAt : '',
|
||||||
|
userId: typeof v.userId === 'string' ? v.userId : '',
|
||||||
|
accountData: filtered,
|
||||||
|
profile: {
|
||||||
|
decoration: typeof profile.decoration === 'string' ? profile.decoration : null,
|
||||||
|
},
|
||||||
|
local: { settings: isObject(local.settings) ? local.settings : null },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
|
||||||
|
|
||||||
|
const itemKey = (v: unknown): string => {
|
||||||
|
if (isObject(v)) {
|
||||||
|
const id = v.id ?? v.eventId ?? v.event_id ?? v.key ?? v.roomId ?? v.room_id ?? v.mxc;
|
||||||
|
if (typeof id === 'string' || typeof id === 'number') return `id:${String(id)}`;
|
||||||
|
}
|
||||||
|
return `json:${JSON.stringify(v)}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type MergeResult = { value: unknown; added: number; conflicts: number };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pure: merge `incoming` into `current`. Lists: add items that are missing
|
||||||
|
* (matched by id, else by content). Objects: add missing keys, recurse into
|
||||||
|
* shared ones. A differing leaf is a conflict: `preferIncoming` decides.
|
||||||
|
*/
|
||||||
|
export const mergeData = (
|
||||||
|
current: unknown,
|
||||||
|
incoming: unknown,
|
||||||
|
preferIncoming = false,
|
||||||
|
): MergeResult => {
|
||||||
|
if (current === undefined || current === null) {
|
||||||
|
return { value: incoming, added: incoming === undefined ? 0 : 1, conflicts: 0 };
|
||||||
|
}
|
||||||
|
if (Array.isArray(current) && Array.isArray(incoming)) {
|
||||||
|
const have = new Map(current.map((v, i) => [itemKey(v), i]));
|
||||||
|
const out = [...current];
|
||||||
|
let added = 0;
|
||||||
|
let conflicts = 0;
|
||||||
|
incoming.forEach((item) => {
|
||||||
|
const k = itemKey(item);
|
||||||
|
const at = have.get(k);
|
||||||
|
if (at === undefined) {
|
||||||
|
out.push(item);
|
||||||
|
have.set(k, out.length - 1);
|
||||||
|
added += 1;
|
||||||
|
} else if (!same(out[at], item)) {
|
||||||
|
conflicts += 1;
|
||||||
|
if (preferIncoming) out[at] = item;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { value: out, added, conflicts };
|
||||||
|
}
|
||||||
|
if (isObject(current) && isObject(incoming)) {
|
||||||
|
const out: Record<string, unknown> = { ...current };
|
||||||
|
let added = 0;
|
||||||
|
let conflicts = 0;
|
||||||
|
Object.entries(incoming).forEach(([k, v]) => {
|
||||||
|
if (!(k in current)) {
|
||||||
|
out[k] = v;
|
||||||
|
added += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const r = mergeData(current[k], v, preferIncoming);
|
||||||
|
out[k] = r.value;
|
||||||
|
added += r.added;
|
||||||
|
conflicts += r.conflicts;
|
||||||
|
});
|
||||||
|
return { value: out, added, conflicts };
|
||||||
|
}
|
||||||
|
if (same(current, incoming)) return { value: current, added: 0, conflicts: 0 };
|
||||||
|
return { value: preferIncoming ? incoming : current, added: 0, conflicts: 1 };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ImportPlanItem = {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
added: number;
|
||||||
|
conflicts: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** What importing `file` into the current data would change, per category. */
|
||||||
|
export const planImport = (
|
||||||
|
file: ExportFile,
|
||||||
|
current: {
|
||||||
|
accountData: Record<string, unknown>;
|
||||||
|
decoration: string | null;
|
||||||
|
localSettings: Record<string, unknown> | null;
|
||||||
|
},
|
||||||
|
): ImportPlanItem[] => {
|
||||||
|
const items: ImportPlanItem[] = [];
|
||||||
|
EXPORT_ACCOUNT_DATA.forEach(({ type, label }) => {
|
||||||
|
if (!(type in file.accountData)) return;
|
||||||
|
const r = mergeData(current.accountData[type], file.accountData[type]);
|
||||||
|
items.push({ key: type, label, added: r.added, conflicts: r.conflicts });
|
||||||
|
});
|
||||||
|
if (file.profile.decoration !== null) {
|
||||||
|
const differs = current.decoration !== file.profile.decoration;
|
||||||
|
items.push({
|
||||||
|
key: 'profile.decoration',
|
||||||
|
label: 'Avatar decoration',
|
||||||
|
added: !current.decoration && differs ? 1 : 0,
|
||||||
|
conflicts: current.decoration && differs ? 1 : 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (file.local.settings) {
|
||||||
|
const r = mergeData(current.localSettings ?? {}, file.local.settings);
|
||||||
|
items.push({
|
||||||
|
key: 'local.settings',
|
||||||
|
label: "This device's settings",
|
||||||
|
added: r.added,
|
||||||
|
conflicts: r.conflicts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
};
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { MatrixError } from 'matrix-js-sdk';
|
import { IPresenceOpts, MatrixError } from 'matrix-js-sdk';
|
||||||
import { PresenceDeduper, describePresenceError, setPresenceWithRetry } from './presenceWrite';
|
import {
|
||||||
|
PresenceDeduper,
|
||||||
|
describePresenceError,
|
||||||
|
isPresenceWritePending,
|
||||||
|
queuePresenceWrite,
|
||||||
|
setPresenceWithRetry,
|
||||||
|
} from './presenceWrite';
|
||||||
|
|
||||||
const limited = (retryMs = 3000) =>
|
const limited = (retryMs = 3000) =>
|
||||||
new MatrixError(
|
new MatrixError(
|
||||||
@@ -79,3 +85,43 @@ test('error wording', () => {
|
|||||||
);
|
);
|
||||||
assert.match(describePresenceError(new TypeError('Failed to fetch')), /couldn't reach/);
|
assert.match(describePresenceError(new TypeError('Failed to fetch')), /couldn't reach/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('[status save] queuePresenceWrite: newest wins, waits out 429 once, all callers settle', async () => {
|
||||||
|
const sent: string[] = [];
|
||||||
|
let calls = 0;
|
||||||
|
const sleeps: number[] = [];
|
||||||
|
const mx = {
|
||||||
|
setPresence: async (w: IPresenceOpts) => {
|
||||||
|
calls += 1;
|
||||||
|
if (calls === 1) {
|
||||||
|
sent.push(`429:${w.status_msg}`);
|
||||||
|
throw new MatrixError({ errcode: 'M_LIMIT_EXCEEDED', retry_after_ms: 7000 }, 429);
|
||||||
|
}
|
||||||
|
sent.push(`ok:${w.status_msg}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const sleepFn = async (ms: number) => {
|
||||||
|
sleeps.push(ms);
|
||||||
|
};
|
||||||
|
// 'a' goes out at once; 'b' and 'c' arrive while it waits out the limit.
|
||||||
|
const first = queuePresenceWrite(mx, { presence: 'online', status_msg: 'a' }, { sleepFn });
|
||||||
|
const second = queuePresenceWrite(mx, { presence: 'online', status_msg: 'b' }, { sleepFn });
|
||||||
|
const third = queuePresenceWrite(mx, { presence: 'online', status_msg: 'c' }, { sleepFn });
|
||||||
|
assert.equal(isPresenceWritePending(mx), true);
|
||||||
|
await Promise.all([first, second, third]);
|
||||||
|
// 'a' was 429'd; after the wait only the newest ('c') goes out — 'a' isn't
|
||||||
|
// retried and 'b' is never sent.
|
||||||
|
assert.deepEqual(sent, ['429:a', 'ok:c']);
|
||||||
|
assert.deepEqual(sleeps, [7000]);
|
||||||
|
assert.equal(isPresenceWritePending(mx), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[status save] queuePresenceWrite: a failure rejects the callers of that write', async () => {
|
||||||
|
const mx = {
|
||||||
|
setPresence: async () => {
|
||||||
|
throw new MatrixError({ errcode: 'M_FORBIDDEN' }, 403);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await assert.rejects(queuePresenceWrite(mx, { presence: 'online', status_msg: 'x' }));
|
||||||
|
assert.equal(isPresenceWritePending(mx), false);
|
||||||
|
});
|
||||||
@@ -94,3 +94,78 @@ export const describePresenceError = (e: unknown): string => {
|
|||||||
}
|
}
|
||||||
return "Failed to save status — couldn't reach the server. Try again.";
|
return "Failed to save status — couldn't reach the server. Try again.";
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type PresenceQueue = {
|
||||||
|
pending?: PresenceWrite;
|
||||||
|
waiters: { resolve: () => void; reject: (e: unknown) => void }[];
|
||||||
|
running: boolean;
|
||||||
|
};
|
||||||
|
const queues = new WeakMap<object, PresenceQueue>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One presence writer per client, newest write wins. The status save and the
|
||||||
|
* heartbeat share Synapse's one-write-per-10-s budget, so instead of each
|
||||||
|
* waiting out 429s on its own (and racing), writes queue here: anything still
|
||||||
|
* waiting is replaced by the newer write, which goes out as soon as the server
|
||||||
|
* allows. Each caller's promise settles with the outcome of the write that
|
||||||
|
* finally carried (or superseded) theirs.
|
||||||
|
*/
|
||||||
|
export function queuePresenceWrite(
|
||||||
|
mx: Pick<MatrixClient, 'setPresence'>,
|
||||||
|
write: PresenceWrite,
|
||||||
|
opts: { maxWaitMs?: number; sleepFn?: (ms: number) => Promise<void> } = {},
|
||||||
|
): Promise<void> {
|
||||||
|
let q = queues.get(mx);
|
||||||
|
if (!q) {
|
||||||
|
q = { waiters: [], running: false };
|
||||||
|
queues.set(mx, q);
|
||||||
|
}
|
||||||
|
const queue = q;
|
||||||
|
queue.pending = write;
|
||||||
|
const settled = new Promise<void>((resolve, reject) => {
|
||||||
|
queue.waiters.push({ resolve, reject });
|
||||||
|
});
|
||||||
|
if (!queue.running) {
|
||||||
|
queue.running = true;
|
||||||
|
const maxWaitMs = opts.maxWaitMs ?? 25_000;
|
||||||
|
const sleepFn = opts.sleepFn ?? sleep;
|
||||||
|
(async () => {
|
||||||
|
let waited = 0;
|
||||||
|
while (queue.pending) {
|
||||||
|
const next = queue.pending;
|
||||||
|
queue.pending = undefined;
|
||||||
|
const waiters = queue.waiters.splice(0);
|
||||||
|
try {
|
||||||
|
// eslint-disable-next-line no-await-in-loop
|
||||||
|
await writePresence(mx, next);
|
||||||
|
waited = 0;
|
||||||
|
if (queue.pending) queue.waiters.unshift(...waiters);
|
||||||
|
else waiters.forEach((w) => w.resolve());
|
||||||
|
} catch (e) {
|
||||||
|
const wait =
|
||||||
|
e instanceof MatrixError && e.httpStatus === 429
|
||||||
|
? Math.min(e.getRetryAfterMs() ?? 10_500, 15_000)
|
||||||
|
: undefined;
|
||||||
|
if (wait !== undefined && waited + wait <= maxWaitMs) {
|
||||||
|
waited += wait;
|
||||||
|
// eslint-disable-next-line no-await-in-loop
|
||||||
|
await sleepFn(wait);
|
||||||
|
// After the wait, send whatever is newest: a change made meanwhile
|
||||||
|
// replaces this one rather than queueing behind it.
|
||||||
|
queue.pending ??= next;
|
||||||
|
queue.waiters.unshift(...waiters);
|
||||||
|
} else if (queue.pending) {
|
||||||
|
queue.waiters.unshift(...waiters);
|
||||||
|
} else {
|
||||||
|
waiters.forEach((w) => w.reject(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
queue.running = false;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
return settled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a presence write is queued or in flight for this client. */
|
||||||
|
export const isPresenceWritePending = (mx: object): boolean => queues.get(mx)?.running ?? false;
|
||||||
@@ -8,6 +8,9 @@ import {
|
|||||||
parseNudgeRecord,
|
parseNudgeRecord,
|
||||||
SecurityState,
|
SecurityState,
|
||||||
shouldShowNudge,
|
shouldShowNudge,
|
||||||
|
pickNudge,
|
||||||
|
staleSessions,
|
||||||
|
staleSessionsText,
|
||||||
} from './securityNudge';
|
} from './securityNudge';
|
||||||
|
|
||||||
const healthy: SecurityState = {
|
const healthy: SecurityState = {
|
||||||
@@ -79,3 +82,45 @@ test('stored record: round trip, and garbage starts a fresh grace period', () =>
|
|||||||
assert.deepEqual(parseNudgeRecord(bad, t0), { firstSeen: t0, dismissals: {} }, bad);
|
assert.deepEqual(parseNudgeRecord(bad, t0), { firstSeen: t0, dismissals: {} }, bad);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('[#113] stale sessions: 90+ days unused, never the current one', () => {
|
||||||
|
const now = Date.UTC(2026, 9, 25);
|
||||||
|
const day = 86_400_000;
|
||||||
|
const devices = [
|
||||||
|
{ device_id: 'ME', last_seen_ts: now - 400 * day },
|
||||||
|
{ device_id: 'OLD', last_seen_ts: now - 91 * day },
|
||||||
|
{ device_id: 'EDGE', last_seen_ts: now - 90 * day },
|
||||||
|
{ device_id: 'RECENT', last_seen_ts: now - 89 * day },
|
||||||
|
{ device_id: 'UNKNOWN' },
|
||||||
|
{ device_id: 'NULL', last_seen_ts: null },
|
||||||
|
];
|
||||||
|
assert.deepEqual(
|
||||||
|
staleSessions(devices, 'ME', now).map((d) => d.device_id),
|
||||||
|
['OLD', 'EDGE'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[#113] wording follows the count', () => {
|
||||||
|
assert.match(
|
||||||
|
staleSessionsText(1),
|
||||||
|
/^You have a session you haven't used in 3 months\. Signing it out/,
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
staleSessionsText(3),
|
||||||
|
/^You have 3 sessions you haven't used in 3 months\. Signing them out/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('[#113] pickNudge: security first, stale sessions when that one is snoozed or absent', () => {
|
||||||
|
const now = 10 * 86_400_000;
|
||||||
|
const fresh = { firstSeen: 0, dismissals: {} };
|
||||||
|
assert.equal(pickNudge('verify-device', 2, fresh, now), 'verify-device');
|
||||||
|
assert.equal(pickNudge(undefined, 2, fresh, now), 'stale-sessions');
|
||||||
|
assert.equal(pickNudge(undefined, 0, fresh, now), undefined);
|
||||||
|
const snoozed = dismissNudge('verify-device', fresh, now);
|
||||||
|
assert.equal(pickNudge('verify-device', 2, snoozed, now), 'stale-sessions');
|
||||||
|
const bothSnoozed = dismissNudge('stale-sessions', snoozed, now);
|
||||||
|
assert.equal(pickNudge('verify-device', 2, bothSnoozed, now), undefined);
|
||||||
|
// inside the 24 h grace period nothing shows
|
||||||
|
assert.equal(pickNudge(undefined, 2, { firstSeen: now, dismissals: {} }, now), undefined);
|
||||||
|
});
|
||||||
@@ -9,12 +9,15 @@
|
|||||||
* - setup-backup: no key backup at all (includes accounts that never set up
|
* - setup-backup: no key backup at all (includes accounts that never set up
|
||||||
* cross-signing: the setup flow does both).
|
* cross-signing: the setup flow does both).
|
||||||
*
|
*
|
||||||
|
* - stale-sessions (#113, lowest priority): sessions of this account not used
|
||||||
|
* for 90+ days; Review opens Settings → Privacy & security with them ticked to sign out.
|
||||||
|
*
|
||||||
* Anything not yet known (crypto still loading) → no nudge. Timing: not in
|
* Anything not yet known (crypto still loading) → no nudge. Timing: not in
|
||||||
* the first 24 h on a device (onboarding), "Not now" snoozes 7 days, three
|
* the first 24 h on a device (onboarding), "Not now" snoozes 7 days, three
|
||||||
* dismissals of a nudge stop it for good; a healthy device never sees one.
|
* dismissals of a nudge stop it for good; a healthy device never sees one.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export type NudgeKind = 'verify-device' | 'connect-backup' | 'setup-backup';
|
export type NudgeKind = 'verify-device' | 'connect-backup' | 'setup-backup' | 'stale-sessions';
|
||||||
|
|
||||||
export type SecurityState = {
|
export type SecurityState = {
|
||||||
/** m.cross_signing.master account data present. */
|
/** m.cross_signing.master account data present. */
|
||||||
@@ -38,6 +41,51 @@ export const nudgeFor = (s: SecurityState): NudgeKind | undefined => {
|
|||||||
return s.backupActive ? undefined : 'connect-backup';
|
return s.backupActive ? undefined : 'connect-backup';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** [Gitea #113] A session counts as stale after this long unused. */
|
||||||
|
export const STALE_SESSION_MS = 90 * 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
type SessionLike = { device_id: string; last_seen_ts?: number | null };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pure: other sessions of this account not seen for STALE_SESSION_MS. Never
|
||||||
|
* the current session; a session with no last-seen time is left alone (we
|
||||||
|
* can't tell it's unused).
|
||||||
|
*/
|
||||||
|
export const staleSessions = <T extends SessionLike>(
|
||||||
|
devices: T[],
|
||||||
|
currentDeviceId: string | undefined,
|
||||||
|
now: number,
|
||||||
|
): T[] =>
|
||||||
|
devices.filter(
|
||||||
|
(d) =>
|
||||||
|
d.device_id !== currentDeviceId &&
|
||||||
|
typeof d.last_seen_ts === 'number' &&
|
||||||
|
now - d.last_seen_ts >= STALE_SESSION_MS,
|
||||||
|
);
|
||||||
|
|
||||||
|
/** "1 session" / "3 sessions you haven't used in 3 months". */
|
||||||
|
export const staleSessionsText = (count: number): string =>
|
||||||
|
`You have ${count === 1 ? 'a session' : `${count} sessions`} you haven't used in 3 months. Signing ${
|
||||||
|
count === 1 ? 'it' : 'them'
|
||||||
|
} out keeps your account safe if an old device is lost.`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The nudge to show: the device-security one first, then stale sessions, each
|
||||||
|
* only if its own snooze allows (so a snoozed security nudge doesn't hide the
|
||||||
|
* stale-sessions one, and vice versa).
|
||||||
|
*/
|
||||||
|
export const pickNudge = (
|
||||||
|
security: NudgeKind | undefined,
|
||||||
|
staleCount: number,
|
||||||
|
record: NudgeRecord,
|
||||||
|
now: number,
|
||||||
|
): NudgeKind | undefined => {
|
||||||
|
const candidates: NudgeKind[] = [];
|
||||||
|
if (security) candidates.push(security);
|
||||||
|
if (staleCount > 0) candidates.push('stale-sessions');
|
||||||
|
return candidates.find((k) => shouldShowNudge(k, record, now));
|
||||||
|
};
|
||||||
|
|
||||||
export const NUDGE_GRACE_MS = 24 * 60 * 60 * 1000;
|
export const NUDGE_GRACE_MS = 24 * 60 * 60 * 1000;
|
||||||
export const NUDGE_SNOOZE_MS = 7 * 24 * 60 * 60 * 1000;
|
export const NUDGE_SNOOZE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||||
export const NUDGE_MAX_DISMISSALS = 3;
|
export const NUDGE_MAX_DISMISSALS = 3;
|
||||||
@@ -87,6 +135,11 @@ export const NUDGE_COPY: Record<NudgeKind, { text: string; action: string }> = {
|
|||||||
text: "This device isn't using your key backup yet. Connect it so your encrypted messages stay readable if you lose it.",
|
text: "This device isn't using your key backup yet. Connect it so your encrypted messages stay readable if you lose it.",
|
||||||
action: 'Connect',
|
action: 'Connect',
|
||||||
},
|
},
|
||||||
|
'stale-sessions': {
|
||||||
|
// The text depends on the count: see staleSessionsText.
|
||||||
|
text: '',
|
||||||
|
action: 'Review',
|
||||||
|
},
|
||||||
'setup-backup': {
|
'setup-backup': {
|
||||||
text: "Your encryption keys aren't backed up. Set up key backup so you don't lose your encrypted messages if you log out or lose this device.",
|
text: "Your encryption keys aren't backed up. Set up key backup so you don't lose your encrypted messages if you log out or lose this device.",
|
||||||
action: 'Set up',
|
action: 'Set up',
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
|
|||||||
// the user (KeyUploadBanner) instead of retrying silently forever.
|
// the user (KeyUploadBanner) instead of retrying silently forever.
|
||||||
fetchFn: watchKeyUploads((input, init) => globalThis.fetch(input, init)),
|
fetchFn: watchKeyUploads((input, init) => globalThis.fetch(input, init)),
|
||||||
timelineSupport: true,
|
timelineSupport: true,
|
||||||
cryptoCallbacks: cryptoCallbacks as any,
|
cryptoCallbacks,
|
||||||
// SAS (emoji) + QR-code verification (show/scan/reciprocate).
|
// SAS (emoji) + QR-code verification (show/scan/reciprocate).
|
||||||
verificationMethods: ['m.sas.v1', 'm.qr_code.show.v1', 'm.qr_code.scan.v1', 'm.reciprocate.v1'],
|
verificationMethods: ['m.sas.v1', 'm.qr_code.show.v1', 'm.qr_code.scan.v1', 'm.reciprocate.v1'],
|
||||||
oauthClientId: oidcIdentity?.oidc.clientId,
|
oauthClientId: oidcIdentity?.oidc.clientId,
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
const secretStorageKeys = new Map();
|
|
||||||
|
|
||||||
export function storePrivateKey(keyId, privateKey) {
|
|
||||||
if (privateKey instanceof Uint8Array === false) {
|
|
||||||
throw new Error('Unable to store, privateKey is invalid.');
|
|
||||||
}
|
|
||||||
secretStorageKeys.set(keyId, privateKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasPrivateKey(keyId) {
|
|
||||||
return secretStorageKeys.get(keyId) instanceof Uint8Array;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getPrivateKey(keyId) {
|
|
||||||
return secretStorageKeys.get(keyId);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function clearSecretStorageKeys() {
|
|
||||||
secretStorageKeys.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getSecretStorageKey({ keys }) {
|
|
||||||
const keyIds = Object.keys(keys);
|
|
||||||
const keyId = keyIds.find(hasPrivateKey);
|
|
||||||
if (!keyId) return undefined;
|
|
||||||
const privateKey = getPrivateKey(keyId);
|
|
||||||
return [keyId, privateKey];
|
|
||||||
}
|
|
||||||
|
|
||||||
function cacheSecretStorageKey(keyId, keyInfo, privateKey) {
|
|
||||||
secretStorageKeys.set(keyId, privateKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const cryptoCallbacks = {
|
|
||||||
getSecretStorageKey,
|
|
||||||
cacheSecretStorageKey,
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { clearSecretStorageKeys, cryptoCallbacks, storePrivateKey } from './secretStorageKeys';
|
||||||
|
|
||||||
|
const ask = (...ids: string[]) =>
|
||||||
|
cryptoCallbacks.getSecretStorageKey!(
|
||||||
|
{ keys: Object.fromEntries(ids.map((id) => [id, {} as never])) },
|
||||||
|
'm.cross_signing.master',
|
||||||
|
);
|
||||||
|
|
||||||
|
test('[#210] secret storage key cache: null when unknown, key when stored, copies input', async () => {
|
||||||
|
clearSecretStorageKeys();
|
||||||
|
assert.equal(await ask('k1'), null);
|
||||||
|
|
||||||
|
const key = new Uint8Array([1, 2, 3]);
|
||||||
|
storePrivateKey('k1', key);
|
||||||
|
key[0] = 9; // the cache keeps its own copy
|
||||||
|
assert.deepEqual(await ask('k0', 'k1'), ['k1', new Uint8Array([1, 2, 3])]);
|
||||||
|
|
||||||
|
cryptoCallbacks.cacheSecretStorageKey!('k2', {} as never, new Uint8Array([7]));
|
||||||
|
assert.deepEqual(await ask('k2'), ['k2', new Uint8Array([7])]);
|
||||||
|
|
||||||
|
clearSecretStorageKeys();
|
||||||
|
assert.equal(await ask('k1', 'k2'), null);
|
||||||
|
assert.throws(() => storePrivateKey('k3', 'nope' as never), /invalid/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type { CryptoCallbacks } from 'matrix-js-sdk/lib/crypto-api';
|
||||||
|
|
||||||
|
const secretStorageKeys = new Map<string, Uint8Array<ArrayBuffer>>();
|
||||||
|
|
||||||
|
export function storePrivateKey(keyId: string, privateKey: Uint8Array) {
|
||||||
|
if (privateKey instanceof Uint8Array === false) {
|
||||||
|
throw new Error('Unable to store, privateKey is invalid.');
|
||||||
|
}
|
||||||
|
// Our own copy, on a plain ArrayBuffer (what the SDK's callback type wants).
|
||||||
|
secretStorageKeys.set(keyId, new Uint8Array(privateKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearSecretStorageKeys() {
|
||||||
|
secretStorageKeys.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const cryptoCallbacks: CryptoCallbacks = {
|
||||||
|
async getSecretStorageKey({ keys }) {
|
||||||
|
const keyId = Object.keys(keys).find((id) => secretStorageKeys.get(id) instanceof Uint8Array);
|
||||||
|
const privateKey = keyId ? secretStorageKeys.get(keyId) : undefined;
|
||||||
|
// The SDK expects null (not undefined) when no key is cached.
|
||||||
|
return keyId && privateKey ? [keyId, privateKey] : null;
|
||||||
|
},
|
||||||
|
cacheSecretStorageKey(keyId, keyInfo, privateKey) {
|
||||||
|
secretStorageKeys.set(keyId, privateKey);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -9,3 +9,25 @@ export function pushSessionToSW(baseUrl?: string, accessToken?: string, userId?:
|
|||||||
userId,
|
userId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves once media requests can carry the session: immediately-ish when a
|
||||||
|
* service worker already controls the page, otherwise when one takes control
|
||||||
|
* (first visit / just updated) or after `timeoutMs`. Used to retry a media
|
||||||
|
* load that raced the worker's activation and went out without a token.
|
||||||
|
*/
|
||||||
|
export function whenMediaAuthReady(timeoutMs = 3000): Promise<void> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const sw = 'serviceWorker' in navigator ? navigator.serviceWorker : undefined;
|
||||||
|
if (!sw || sw.controller) {
|
||||||
|
window.setTimeout(resolve, 500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const done = () => {
|
||||||
|
sw.removeEventListener('controllerchange', done);
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
sw.addEventListener('controllerchange', done);
|
||||||
|
window.setTimeout(done, timeoutMs);
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user