Личный чат: голосовые с прослушиванием на паузе, фон «Северное сияние», запрет автоперевода

- Запись голосового: микрофон едет за пальцем, при отмене падает в корзину, с полпути
  пружинит обратно, а запись продолжается в режиме замка. На паузе запись можно
  прослушать и перемотать до отправки.
- Фон «Северное сияние» для тёмной и светлой темы: отправленные сообщения зелёные,
  входящие голубые. Отблески у кромки сообщений вынесены в общий блок has-dm-flash.
- Расшифрованная переписка помечена translate="no": автоперевод браузера отправлял бы
  её на сервер переводчика. Язык страницы объявляется сразу в index.html.

Формат SHiNE_DM и серверный API не менялись.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pixel
2026-12-03 19:10:18 +03:00
co-authored by Claude Opus 5.5
parent d09431da65
commit fdf3b4e8cb
21 changed files with 485 additions and 83 deletions
+8 -2
View File
@@ -117,11 +117,17 @@ test('оттенок сообщений привязан к фону, котор
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 = /);
assert.match(file('js/pages/chat-view.js'), /classList\.toggle\('has-dm-glow', Boolean\(background\?\.glow\)\)/);
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/);
});
+23 -1
View File
@@ -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'));
@@ -57,6 +57,28 @@ test('замок — значок приложения, шрифт справк
}
});
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']) 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('страница с первой секунды объявляет язык приложения', () => {
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/);
+37
View File
@@ -0,0 +1,37 @@
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('микрофон едет за пальцем без задержки, а на место возвращается пружиной', () => {
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+/);
});