SHA256
Слить обновления main в рабочую ветку
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
|
||||
const store = new Map();
|
||||
globalThis.localStorage = {
|
||||
getItem: (key) => (store.has(key) ? store.get(key) : null),
|
||||
setItem: (key, value) => { store.set(key, String(value)); },
|
||||
removeItem: (key) => { store.delete(key); },
|
||||
key: (index) => [...store.keys()][index] ?? null,
|
||||
get length() { return store.size; },
|
||||
};
|
||||
globalThis.window ??= globalThis;
|
||||
const events = [];
|
||||
window.dispatchEvent = (event) => { events.push(event.type); return true; };
|
||||
|
||||
const { state } = await import('../js/state.js');
|
||||
const prefs = await import('../js/services/dm-chat-prefs.js');
|
||||
const { findDmChatBackground, listDmChatBackgrounds, paintDmChatBackground } = await import('../js/services/dm-chat-backgrounds.js');
|
||||
|
||||
const root = new URL('../', import.meta.url);
|
||||
const file = (path) => readFileSync(new URL(path, root), 'utf8');
|
||||
|
||||
function login(name) {
|
||||
state.session = { ...state.session, login: name };
|
||||
}
|
||||
|
||||
test('фон хранится отдельно для каждого чата и аккаунта и не задевает другие настройки', () => {
|
||||
store.clear();
|
||||
login('Alice@ns');
|
||||
prefs.setDmChatMuted('bob@ns', true);
|
||||
prefs.setDmChatPinned('bob@ns', true);
|
||||
assert.equal(prefs.getDmChatBackground('bob@ns'), '');
|
||||
|
||||
events.length = 0;
|
||||
prefs.setDmChatBackground('Bob@ns', 'nebula');
|
||||
assert.deepEqual(events, [prefs.DM_CHAT_PREFS_EVENT], 'открытый чат узнаёт о смене фона');
|
||||
assert.equal(prefs.getDmChatBackground('bob@NS'), 'nebula', 'регистр логина не важен');
|
||||
assert.equal(prefs.getDmChatBackground('carol@ns'), '', 'у другого чата фона нет');
|
||||
assert.equal(prefs.isDmChatMuted('bob@ns'), true);
|
||||
assert.equal(prefs.isDmChatPinned('bob@ns'), true);
|
||||
|
||||
// Любая другая настройка чата переписывает весь набор – фон не должен потеряться.
|
||||
prefs.setDmChatPinned('carol@ns', true);
|
||||
prefs.setDmChatMuted('bob@ns', false);
|
||||
assert.equal(prefs.getDmChatBackground('bob@ns'), 'nebula');
|
||||
|
||||
login('eve@ns');
|
||||
assert.equal(prefs.getDmChatBackground('bob@ns'), '', 'другой аккаунт на этом устройстве выбирает сам');
|
||||
login('alice@ns');
|
||||
prefs.setDmChatBackground('bob@ns', '');
|
||||
assert.equal(prefs.getDmChatBackground('bob@ns'), '');
|
||||
assert.equal(prefs.isDmChatPinned('bob@ns'), true);
|
||||
});
|
||||
|
||||
test('испорченное хранилище и логин вроде «constructor» не дают чужого фона', () => {
|
||||
store.clear();
|
||||
login('alice@ns');
|
||||
assert.equal(prefs.getDmChatBackground('constructor'), '');
|
||||
store.set('shine-dm-chat-prefs-v1:alice@ns', JSON.stringify({ backgrounds: { 'bob@ns': { x: 1 }, 'carol@ns': 'nebula' } }));
|
||||
assert.equal(prefs.getDmChatBackground('bob@ns'), '');
|
||||
assert.equal(prefs.getDmChatBackground('carol@ns'), 'nebula');
|
||||
});
|
||||
|
||||
test('хранилище не пишет: выбранный фон действует до перезагрузки вкладки и сохраняется, когда место появится', () => {
|
||||
store.clear();
|
||||
login('alice@ns');
|
||||
const { setItem } = globalThis.localStorage;
|
||||
globalThis.localStorage.setItem = () => { throw new Error('QuotaExceededError'); };
|
||||
try {
|
||||
prefs.setDmChatBackground('bob@ns', 'nebula');
|
||||
assert.equal(prefs.getDmChatBackground('bob@ns'), 'nebula');
|
||||
assert.equal(store.size, 0);
|
||||
} finally {
|
||||
globalThis.localStorage.setItem = setItem;
|
||||
}
|
||||
prefs.setDmChatPinned('carol@ns', true);
|
||||
assert.deepEqual(JSON.parse(store.get('shine-dm-chat-prefs-v1:alice@ns')).backgrounds, { 'bob@ns': 'nebula' });
|
||||
});
|
||||
|
||||
test('каждый фон: уникальный id, подпись в обоих словарях и лёгкие картинки для двух тем', () => {
|
||||
const list = listDmChatBackgrounds();
|
||||
assert.ok(list.length >= 1);
|
||||
assert.equal(new Set(list.map(({ id }) => id)).size, list.length);
|
||||
const ru = JSON.parse(file('js/i18n/locales/ru.json')).screens.dm_background;
|
||||
const en = JSON.parse(file('js/i18n/locales/en.json')).screens.dm_background;
|
||||
for (const background of list) {
|
||||
assert.match(background.id, /^[a-z][a-z0-9-]*$/);
|
||||
assert.ok(ru[background.id] && en[background.id], background.id);
|
||||
for (const theme of ['dark', 'light']) {
|
||||
const url = new URL(background[theme], root);
|
||||
assert.ok(existsSync(url), background[theme]);
|
||||
assert.ok(statSync(url).size < 250 * 1024, `${background[theme]} тяжелее 250 КБ`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('фон, которого больше нет в приложении, читается как «без фона»', () => {
|
||||
assert.equal(findDmChatBackground('removed-background'), null);
|
||||
assert.equal(findDmChatBackground(''), null);
|
||||
assert.equal(findDmChatBackground('nebula')?.id, 'nebula');
|
||||
});
|
||||
|
||||
test('картинки передаются в CSS абсолютными адресами и снимаются вместе с фоном', () => {
|
||||
const values = new Map();
|
||||
const node = { style: { setProperty: (k, v) => values.set(k, v), removeProperty: (k) => values.delete(k) } };
|
||||
const previous = globalThis.document;
|
||||
globalThis.document = { baseURI: 'https://example.test/' };
|
||||
try {
|
||||
paintDmChatBackground(node, findDmChatBackground('nebula'));
|
||||
// url() в переменной иначе считался бы от файла стилей, а не от корня приложения.
|
||||
assert.match(values.get('--dm-bg-dark'), /^url\("https:\/\/example\.test\/img\/chat-backgrounds\/[^"]+"\)$/);
|
||||
assert.match(values.get('--dm-bg-light'), /^url\("https:\/\/example\.test\/img\/chat-backgrounds\/[^"]+"\)$/);
|
||||
paintDmChatBackground(node, null);
|
||||
assert.equal(values.size, 0);
|
||||
} finally {
|
||||
globalThis.document = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test('оттенок сообщений привязан к фону, который есть в списке', () => {
|
||||
const css = file('styles/features/dm-background.css');
|
||||
const tinted = new Set([...css.matchAll(/\[data-dm-bg='([^']+)'\]/g)].map(([, id]) => id));
|
||||
for (const id of tinted) assert.ok(findDmChatBackground(id), `в стилях остался оттенок удалённого фона «${id}»`);
|
||||
// Светящимся сообщениям нужны все пять цветов в обеих темах: без одного из них пропадёт вся заливка пузыря.
|
||||
const glowing = listDmChatBackgrounds().filter(({ glow }) => glow);
|
||||
assert.ok(glowing.length >= 2);
|
||||
for (const { id } of glowing) {
|
||||
for (const prefix of ['\n', "\n:root[data-theme='light'] "]) {
|
||||
const start = css.indexOf(`${prefix}[data-dm-bg='${id}'] {`);
|
||||
assert.notEqual(start, -1, `${id}: нет блока цветов (${prefix.trim() || 'тёмная тема'})`);
|
||||
const block = css.slice(start, css.indexOf('}', start));
|
||||
for (const name of ['light', 'spark', 'core', 'slate', 'mist']) assert.match(block, new RegExp(`--dm-tint-${name}: #[0-9a-f]{6};`), `${id}: --dm-tint-${name}`);
|
||||
}
|
||||
}
|
||||
// Фон с отблесками задаёт все четыре картинки (или none): пропущенная переменная сняла бы с пузыря весь фон.
|
||||
for (const background of listDmChatBackgrounds().filter(({ flash }) => flash)) {
|
||||
assert.ok(background.glow, `${background.id}: отблески работают только вместе с glow`);
|
||||
const block = [...css.matchAll(/\n\[data-dm-bg='([^']+)'\] \{([^}]*)\}/g)].filter(([, id]) => id === background.id).map(([, , text]) => text).join('');
|
||||
for (const name of ['corner', 'edge', 'in-corner', 'in-edge']) assert.match(block, new RegExp(`--dm-flash-${name}: `), `${background.id}: --dm-flash-${name}`);
|
||||
}
|
||||
// Картинки из стилей лежат в приложении.
|
||||
for (const [, path] of css.matchAll(/url\("([^"]+)"\)/g)) assert.ok(existsSync(new URL(path, new URL('styles/features/', root))), path);
|
||||
// Оттенок нужен и ленте, и полю ввода, и плитке в шторке – все они помечаются id фона.
|
||||
assert.match(file('js/pages/chat-view.js'), /\[screen, form, backgroundLayer\]\.forEach\(\(node\) => \{ node\.dataset\.dmBg = /);
|
||||
for (const name of ['glow', 'flash']) assert.ok(file('js/pages/chat-view.js').includes(`classList.toggle('has-dm-${name}', Boolean(background?.${name}))`), name);
|
||||
assert.match(file('js/components/dm-background-sheet.js'), /preview\.dataset\.dmBg = id/);
|
||||
});
|
||||
|
||||
test('у каждого фона свой цвет микрофона, без фона он прежний', () => {
|
||||
const css = file('styles/features/dm-background.css');
|
||||
const luminance = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
|
||||
.reduce((sum, v, i) => sum + (v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4) * [0.2126, 0.7152, 0.0722][i], 0);
|
||||
for (const prefix of ['', ":root[data-theme='light'] "]) {
|
||||
const colors = listDmChatBackgrounds().map(({ id }) => {
|
||||
const color = css.split('\n').find((line) => line.startsWith(`${prefix}[data-dm-bg='${id}'] { --dm-mic: `))?.match(/#[0-9a-f]{6}/)?.[0];
|
||||
assert.ok(color, `${id}: нет --dm-mic (${prefix || 'тёмная тема'})`);
|
||||
// Днём значок на круге белый, ночью — почти чёрный: оба должны читаться.
|
||||
const contrast = prefix ? 1.05 / (luminance(color) + 0.05) : (luminance(color) + 0.05) / 0.06;
|
||||
assert.ok(contrast >= 4.5, `${id}: значок на круге сливается (${contrast.toFixed(1)})`);
|
||||
return color;
|
||||
});
|
||||
assert.equal(new Set(colors).size, colors.length, 'цвета у фонов не повторяются');
|
||||
}
|
||||
// Действует только в поле ввода с выбранным фоном.
|
||||
assert.equal(css.match(/--accent: /g).length, 1);
|
||||
assert.match(css, /\n\.dm-chat-input\.has-dm-bg \{\s+--accent: var\(--dm-mic\);/);
|
||||
assert.match(css, /\n\.dm-chat-input\.has-dm-bg \.dm-composer-bar \.dm-send-btn\[data-mode='voice'\] \{ color: var\(--accent\); \}/);
|
||||
});
|
||||
|
||||
test('объём сообщений: у эмодзи без пузыря нет канта, размытия на каждом пузыре нет', () => {
|
||||
const css = file('styles/features/chat.css').replace(/\r\n/g, '\n');
|
||||
assert.match(css, /\.dm-chat-screen \.bubble:not\(\.bubble--emoji-only\)::before/);
|
||||
// Размытие под каждым сообщением тормозит прокрутку ленты; стеклу хватает полупрозрачной заливки.
|
||||
for (const block of css.match(/\n[^\n{}]*\.bubble[^{}]*\{[^}]*\}/g) || []) {
|
||||
assert.doesNotMatch(block, /backdrop-filter:\s*blur/);
|
||||
}
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const source = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
|
||||
const source = (path) => readFileSync(new URL(path, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
|
||||
const chat = source('../js/pages/chat-view.js');
|
||||
const css = source('../styles/features/chat.css');
|
||||
const ru = JSON.parse(source('../js/i18n/locales/ru.json'));
|
||||
@@ -44,6 +44,48 @@ test('уведомление формируется только локальн
|
||||
assert.doesNotMatch(functionBody, /authService|addSignedMessageToChat|sendDirectMessage|AddBlock|fetch\(/);
|
||||
});
|
||||
|
||||
test('замок — значок приложения, шрифт справки лежит в приложении, а не грузится со стороны', () => {
|
||||
const body = chat.slice(chat.indexOf('function createDmEncryptionNotice()'), chat.indexOf('function renderLog('));
|
||||
assert.match(body, /iconHtml\('lock'\)/);
|
||||
assert.doesNotMatch(body, /🔒/u);
|
||||
const fonts = [...css.matchAll(/@font-face \{[^}]*url\("([^"]+)"\)/g)].map(([, path]) => path);
|
||||
assert.equal(fonts.length, 2, 'кириллица и латиница');
|
||||
for (const path of fonts) {
|
||||
assert.match(path, /^\.\.\/\.\.\/assets\/fonts\//);
|
||||
const data = readFileSync(new URL(path, new URL('../styles/features/', import.meta.url)));
|
||||
assert.equal(data.toString('latin1', 0, 4), 'wOF2', path);
|
||||
}
|
||||
});
|
||||
|
||||
test('расшифрованная переписка не уходит в автоперевод браузера', () => {
|
||||
for (const owner of ['screen', 'form', 'header']) assert.ok(chat.includes(`${owner}.translate = false;`), owner);
|
||||
for (const id of ['chat-forward-modal', 'chat-external-link-modal', 'chat-delete-chat-modal', 'contact-confirm-modal']) assert.match(chat, new RegExp(`id="${id}" translate="no"`));
|
||||
for (const page of ['messages-list', 'chat-media-view']) assert.match(source(`../js/pages/${page}.js`), /screen\.translate = false;/, page);
|
||||
});
|
||||
|
||||
test('логин из адреса /chat/<логин> не становится разметкой окна «Добавить в контакты»', () => {
|
||||
const start = chat.indexOf('function openConfirmContactModal(');
|
||||
const body = chat.slice(start, chat.indexOf('const close', start));
|
||||
assert.ok(start >= 0 && body.includes('${escapeDialogHtml(targetLogin)}'));
|
||||
assert.ok(!body.includes('${targetLogin}'));
|
||||
});
|
||||
|
||||
test('страница с первой секунды объявляет язык приложения', () => {
|
||||
const index = source('../index.html');
|
||||
const script = index.slice(index.indexOf('(function applyLanguageBeforePaint() {'), index.indexOf('}());', index.indexOf('applyLanguageBeforePaint')) + 5);
|
||||
const key = source('../js/i18n/index.js').match(/const STORAGE_KEY = '([^']+)'/)[1];
|
||||
const langFor = (saved, languages) => {
|
||||
const document = { documentElement: { lang: 'en' } };
|
||||
const localStorage = { getItem: (name) => (name === key ? saved : null) };
|
||||
new Function('document', 'localStorage', 'navigator', script)(document, localStorage, { languages });
|
||||
return document.documentElement.lang;
|
||||
};
|
||||
assert.equal(langFor(null, ['ru-RU', 'en-US']), 'ru');
|
||||
assert.equal(langFor('en', ['ru-RU']), 'en', 'выбор в приложении важнее языка браузера');
|
||||
assert.equal(langFor(null, ['de-DE', 'ru']), 'ru', 'неподдерживаемый язык пропускается, как в js/i18n');
|
||||
assert.equal(langFor(null, ['de-DE']), 'en');
|
||||
});
|
||||
|
||||
test('уведомление имеет собственные серые стили и не оформляется как bubble', () => {
|
||||
assert.match(css, /\.dm-security-notice\s*\{[\s\S]*?color: var\(--text-secondary\)/);
|
||||
assert.doesNotMatch(chat.slice(chat.indexOf('function createDmEncryptionNotice()'), chat.indexOf('function renderLog(')), /className = ['"`]bubble/);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { voiceReleaseAction } from '../js/components/dm-voice-recorder.js';
|
||||
|
||||
const file = (path) => readFileSync(new URL(path, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
|
||||
const recorder = file('../js/components/dm-voice-recorder.js');
|
||||
const css = file('../styles/features/dm-voice.css');
|
||||
|
||||
function body(name) {
|
||||
const start = recorder.indexOf(`function ${name}(`);
|
||||
assert.notEqual(start, -1, name);
|
||||
return recorder.slice(start, recorder.indexOf('\n }\n', start));
|
||||
}
|
||||
|
||||
test('отпустили микрофон: на месте — отправка, на полпути к отмене — запись идёт дальше, короткий тап — подсказка', () => {
|
||||
assert.equal(voiceReleaseAction({ heldMs: 1500, dragPx: 0 }), 'send');
|
||||
assert.equal(voiceReleaseAction({ heldMs: 1500, dragPx: 12 }), 'send', 'дрожание пальца не мешает отправить');
|
||||
assert.equal(voiceReleaseAction({ heldMs: 1500, dragPx: -40 }), 'send', 'вправо отмены нет');
|
||||
assert.equal(voiceReleaseAction({ heldMs: 1500, dragPx: 60 }), 'lock', 'передумал отменять: запись не теряем и не отправляем сами');
|
||||
assert.equal(voiceReleaseAction({ heldMs: 150, dragPx: 60 }), 'tip');
|
||||
});
|
||||
|
||||
test('прослушивание: звук останавливается при отправке, удалении и продолжении, память освобождается', () => {
|
||||
for (const name of ['finish', 'discardRecording', 'resumeRecording']) assert.match(body(name), /stopPreview\(\);/, name);
|
||||
assert.match(body('stopPreview'), /audio\.pause\(\);\n\s*URL\.revokeObjectURL\(audio\.src\);/);
|
||||
// Запись на паузе, а не закончена: её можно продолжить, а буфер браузера просим отдать до прослушивания.
|
||||
assert.match(body('pauseRecording'), /recorder\.pause\(\);[\s\S]*requestData\(\)/);
|
||||
assert.doesNotMatch(body('loadPreview'), /recorder\.stop\(/);
|
||||
});
|
||||
|
||||
test('прослушивание ждёт последний кусок записи, а сбой возвращает кнопку к «Play»', () => {
|
||||
const pause = body('pauseRecording');
|
||||
assert.ok(pause.indexOf("addEventListener('dataavailable', resolve") < pause.indexOf('requestData()'), 'ждать начинаем до запроса');
|
||||
const toggle = body('togglePreview');
|
||||
assert.ok(toggle.indexOf('await current?.flushed') < toggle.indexOf('loadPreview()'));
|
||||
assert.match(toggle, /if \(rec !== current \|\| state !== 'paused'\) return;/, 'пока ждали, запись могли отправить или удалить');
|
||||
assert.match(body('failPreview'), /stopPreview\(\);\s*paintPreview\(\);\s*onError\(/);
|
||||
});
|
||||
|
||||
test('микрофон едет за пальцем без задержки, а на место возвращается пружиной', () => {
|
||||
assert.match(body('dragButton'), /button\.style\.translate = `\$\{-dragPx\}px 0`/);
|
||||
const dragged = css.slice(css.indexOf('.dm-send-btn.is-dragged {'));
|
||||
assert.doesNotMatch(dragged.slice(0, dragged.indexOf('}')), /translate/, 'у перетаскиваемой кнопки нет перехода для translate');
|
||||
assert.match(css, /transition: transform 200ms [^;]*, translate \d+ms cubic-bezier\([\d.]+, 1\.\d+/);
|
||||
});
|
||||
@@ -52,3 +52,28 @@ test('profile statistics use server API without Solana RPC', () => {
|
||||
assert.match(component, /if \(!stats\.ready\)/);
|
||||
assert.match(auth, /this\.ws\.request\('GetSupportStats'/);
|
||||
});
|
||||
|
||||
test('support card collapses as one block: layers share a cell, only the card drives the height', () => {
|
||||
const css = file('../styles/features/profile-support.css');
|
||||
const rule = (selector) => {
|
||||
const start = css.indexOf(`\n${selector} {`);
|
||||
assert.notEqual(start, -1, `${selector} rule is missing`);
|
||||
return css.slice(start, css.indexOf('}', start));
|
||||
};
|
||||
// Две доли одной сетки (1fr 0fr ↔ 0fr 1fr) всегда дают в сумме высоту карточки: при сворачивании блок
|
||||
// не сжимался, а строка растягивалась на всю его высоту пустым прямоугольником.
|
||||
assert.doesNotMatch(css, /grid-template-rows:\s*(?:1fr\s+0fr|0fr\s+1fr)/);
|
||||
assert.match(rule('.profile-support > *'), /grid-area: 1 \/ 1/);
|
||||
assert.match(rule('.profile-support'), /overflow: hidden/);
|
||||
assert.match(rule('.profile-support'), /align-items: start/);
|
||||
assert.match(rule('.profile-support__panel'), /grid-template-rows: 0fr/);
|
||||
assert.match(rule('.profile-support__panel'), /visibility: hidden/);
|
||||
// Ряд панели — только добавка карточки к строке: иначе сжатие упирается в строку на полном ходу и кончается рывком.
|
||||
assert.match(rule('.profile-support__panel'), /margin-top: var\(--ps-line\)/);
|
||||
assert.match(rule('.profile-support .profile-support-stats'), /margin-top: calc\(-1 \* var\(--ps-line\)\)/);
|
||||
assert.match(rule('.profile-support__summary'), /min-height: var\(--ps-line\)/);
|
||||
assert.match(rule(".profile-support[data-expanded='true'] .profile-support__panel"), /grid-template-rows: 1fr/);
|
||||
assert.match(rule(".profile-support[data-expanded='true'] .profile-support__line"), /visibility: hidden/);
|
||||
// Сияние ждёт конца перехода именно той панели, которая теперь анимируется.
|
||||
assert.match(file('../js/components/support-stats.js'), /panel\.getAnimations/);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user