feat(desktop): обёртка Tauri 2 вокруг веб-клиента
Первый инкремент Фазы 6 (docs/client-tauri.md): окно с тем же веб-клиентом (по умолчанию https://gl.mhspx.su, адрес настраивается), трей с меню и индикатором непрочитанных, нативные уведомления, глобальный push-to-talk и переключение микрофона/deafen, автозапуск, single-instance, сохранение геометрии окна, deep links glchat://…, автообновление по подписанному манифесту. Связь страницы с обёрткой — через платформенный адаптер (web/src/lib/platform.ts) и минимальный типизированный набор команд; в веб-клиенте появились системные уведомления об упоминаниях и личных сообщениях и переключатель в настройках. В web/src/stores/gateway.ts вместе с вызовом уведомления лежат правки по дефектам realtime (READY и сессии) из параллельной волны: файл коммитится целиком по договорённости с координатором.
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
notificationFor,
|
||||
notificationsEnabled,
|
||||
previewText,
|
||||
setNotificationsEnabled,
|
||||
} from '@/lib/desktopNotifications';
|
||||
import type { NotificationInput } from '@/lib/desktopNotifications';
|
||||
|
||||
/** Сообщение по умолчанию: обычное сообщение в канале сервера. */
|
||||
function input(overrides: Partial<NotificationInput> = {}): NotificationInput {
|
||||
return {
|
||||
message: {
|
||||
type: 'default',
|
||||
content: 'привет',
|
||||
mentions: [],
|
||||
channel_id: 'c1',
|
||||
author_id: 'u2',
|
||||
},
|
||||
meId: 'u1',
|
||||
isDirect: false,
|
||||
channelName: 'общий',
|
||||
guildId: 'g1',
|
||||
isChannelOpen: false,
|
||||
windowFocused: false,
|
||||
enabled: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('notificationFor', () => {
|
||||
it('уведомляет об упоминании в неактивной комнате', () => {
|
||||
const result = notificationFor(input({ message: { ...input().message, mentions: ['u1'] } }));
|
||||
expect(result).toMatchObject({ title: 'Упоминание в #общий', body: 'привет', channelId: 'c1' });
|
||||
});
|
||||
|
||||
it('уведомляет о личном сообщении', () => {
|
||||
const result = notificationFor(input({ isDirect: true, channelName: 'Аня', guildId: null }));
|
||||
expect(result).toMatchObject({ title: 'Личное сообщение — Аня', guildId: null });
|
||||
});
|
||||
|
||||
it('молчит об обычном сообщении в канале', () => {
|
||||
expect(notificationFor(input())).toBeNull();
|
||||
});
|
||||
|
||||
it('молчит о собственных сообщениях', () => {
|
||||
const result = notificationFor(
|
||||
input({
|
||||
isDirect: true,
|
||||
message: { ...input().message, author_id: 'u1' },
|
||||
}),
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('молчит, когда открытая комната в фокусе', () => {
|
||||
const result = notificationFor(
|
||||
input({ isDirect: true, isChannelOpen: true, windowFocused: true }),
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('уведомляет об открытой комнате, если окно не в фокусе', () => {
|
||||
const result = notificationFor(
|
||||
input({ isDirect: true, isChannelOpen: true, windowFocused: false }),
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
|
||||
it('молчит при выключенных уведомлениях', () => {
|
||||
expect(notificationFor(input({ isDirect: true, enabled: false }))).toBeNull();
|
||||
});
|
||||
|
||||
it('пропускает системные сообщения', () => {
|
||||
const result = notificationFor(
|
||||
input({
|
||||
isDirect: true,
|
||||
message: { ...input().message, type: 'system' },
|
||||
}),
|
||||
);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('подставляет «Вложение» для сообщения без текста', () => {
|
||||
const result = notificationFor(
|
||||
input({
|
||||
isDirect: true,
|
||||
message: { ...input().message, content: '', mentions: ['u1'] },
|
||||
}),
|
||||
);
|
||||
expect(result?.body).toBe('Вложение');
|
||||
});
|
||||
});
|
||||
|
||||
describe('previewText', () => {
|
||||
it('убирает разметку и лишние переводы строк', () => {
|
||||
expect(previewText('**жирный**\n\n[ссылка](https://example.com) `код`')).toBe(
|
||||
'жирный ссылка код',
|
||||
);
|
||||
});
|
||||
|
||||
it('обрезает длинный текст', () => {
|
||||
const result = previewText('а'.repeat(400));
|
||||
expect(result.length).toBeLessThanOrEqual(140);
|
||||
expect(result.endsWith('…')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('предпочтение уведомлений', () => {
|
||||
it('включено по умолчанию и выключается переключателем', () => {
|
||||
expect(notificationsEnabled()).toBe(true);
|
||||
setNotificationsEnabled(false);
|
||||
expect(notificationsEnabled()).toBe(false);
|
||||
setNotificationsEnabled(true);
|
||||
expect(notificationsEnabled()).toBe(true);
|
||||
});
|
||||
|
||||
it('не падает, если localStorage недоступен', () => {
|
||||
const stub = vi.spyOn(window, 'localStorage', 'get').mockImplementation(() => {
|
||||
throw new Error('нет доступа');
|
||||
});
|
||||
expect(notificationsEnabled()).toBe(true);
|
||||
stub.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { isTauri, platform, routeFromDeepLink, type DesktopMessage } from '@/lib/platform';
|
||||
|
||||
/** Ставит в window фальшивый мост Tauri v2 и возвращает список вызовов. */
|
||||
function stubTauri(): Array<{ command: string; args: unknown }> {
|
||||
const calls: Array<{ command: string; args: unknown }> = [];
|
||||
vi.stubGlobal('__TAURI_INTERNALS__', {
|
||||
invoke: (command: string, args?: unknown) => {
|
||||
calls.push({ command, args });
|
||||
return Promise.resolve(undefined);
|
||||
},
|
||||
});
|
||||
return calls;
|
||||
}
|
||||
|
||||
describe('routeFromDeepLink', () => {
|
||||
it('разбирает приглашение', () => {
|
||||
expect(routeFromDeepLink('glchat://invite/AbC123')).toBe('/invite/AbC123');
|
||||
});
|
||||
|
||||
it('разбирает сервер и комнату', () => {
|
||||
expect(routeFromDeepLink('glchat://guild/10/channel/20')).toBe('/app/10/20');
|
||||
});
|
||||
|
||||
it('игнорирует чужие схемы и неизвестные пути', () => {
|
||||
expect(routeFromDeepLink('https://gl.mhspx.su/invite/abc')).toBeNull();
|
||||
expect(routeFromDeepLink('glchat://unknown/1')).toBeNull();
|
||||
expect(routeFromDeepLink('glchat://guild/10')).toBeNull();
|
||||
expect(routeFromDeepLink('не ссылка')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('платформа в браузере', () => {
|
||||
it('определяется как web и не падает на вызовах', () => {
|
||||
expect(isTauri()).toBe(false);
|
||||
expect(platform.kind).toBe('web');
|
||||
expect(() => {
|
||||
platform.notify({ title: 'a', body: 'b' });
|
||||
platform.setBadge(3);
|
||||
platform.ready();
|
||||
platform.openSettings();
|
||||
}).not.toThrow();
|
||||
expect(platform.onMessage(() => {})()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('платформа в desktop-обёртке', () => {
|
||||
it('вызывает команды обёртки и принимает её сообщения', async () => {
|
||||
const calls = stubTauri();
|
||||
vi.resetModules();
|
||||
const desktop = await import('@/lib/platform');
|
||||
|
||||
expect(desktop.isTauri()).toBe(true);
|
||||
expect(desktop.platform.kind).toBe('tauri');
|
||||
|
||||
desktop.platform.notify({ title: 'Упоминание', body: 'привет', channelId: 'c1' });
|
||||
desktop.platform.setBadge(2);
|
||||
desktop.platform.ready();
|
||||
desktop.platform.openSettings();
|
||||
|
||||
expect(calls.map((call) => call.command)).toEqual([
|
||||
'desktop_notify',
|
||||
'desktop_set_badge',
|
||||
'desktop_ready',
|
||||
'desktop_open_settings',
|
||||
]);
|
||||
expect(calls[0]?.args).toEqual({
|
||||
payload: { title: 'Упоминание', body: 'привет', guildId: null, channelId: 'c1' },
|
||||
});
|
||||
expect(calls[1]?.args).toEqual({ count: 2 });
|
||||
|
||||
// Обёртка зовёт страницу через window.__glchatDesktop.receive.
|
||||
const received: DesktopMessage[] = [];
|
||||
const unsubscribe = desktop.platform.onMessage((message) => received.push(message));
|
||||
const bridge = window as unknown as {
|
||||
__glchatDesktop?: { receive: (m: DesktopMessage) => void };
|
||||
};
|
||||
bridge.__glchatDesktop?.receive({ type: 'ptt', active: true });
|
||||
expect(received).toEqual([{ type: 'ptt', active: true }]);
|
||||
|
||||
unsubscribe();
|
||||
bridge.__glchatDesktop?.receive({ type: 'toggleMic' });
|
||||
expect(received).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -222,14 +222,20 @@ describe('настройки: окно и навигация', () => {
|
||||
expect(within(dialog).queryByRole('button', { name: 'Инстанс' })).toBeNull();
|
||||
});
|
||||
|
||||
it('«Уведомления» пока заглушка', async () => {
|
||||
it('«Уведомления» переключают уведомления рабочего стола', async () => {
|
||||
installFetch(appRoutes());
|
||||
|
||||
renderApp('/app/empty');
|
||||
const dialog = await openSettings();
|
||||
await goToSection(dialog, 'Уведомления');
|
||||
|
||||
expect(within(dialog).getByText('Настройки уведомлений появятся позже.')).toBeVisible();
|
||||
const toggle = within(dialog).getByRole('checkbox', { name: /Уведомления рабочего стола/ });
|
||||
expect(toggle).toBeChecked();
|
||||
|
||||
await userEvent.click(toggle);
|
||||
|
||||
expect(toggle).not.toBeChecked();
|
||||
expect(window.localStorage.getItem('glchat.desktop-notifications')).toBe('off');
|
||||
});
|
||||
|
||||
it('«Аудио-видео» без mediaDevices честно сообщает о недоступности', async () => {
|
||||
|
||||
Reference in New Issue
Block a user