Compare commits

...
Author SHA256 Message Date
PixelandClaude Opus 5.5 dd461eaa16 Смерджить карточку «Поддержка» и текст о шифровании в голосовые сообщения
Объединены ветки ui/dm-voice и ui/support-card-ethereal для одного PR.
Конфликты: index.html — в список стилей вошли оба файла (dm-voice.css и
profile-support.css); VERSION.properties — client 1.21.8, server 1.17.6.
chat-view.js, словари ru/en, ui-icon.js и WALLET_SHINE_SUPPORT.md слились
автоматически.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:19:38 +03:00
PixelandClaude Opus 5.5 5e61ca20cb Смерджить свежий main в голосовые сообщения
Подтянуты изменения main до d9a91875 (аудит API, учёт публикации блоков,
звонки и настройки). Конфликт только в VERSION.properties: client 1.21.7,
server 1.17.5 — выше main и PR очереди выплат.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:18:41 +03:00
PixelandClaude Opus 5.5 c778ab8a39 Слить ветку docs/api-contract-audit (Айдар) в ui/dm-voice
Подтянуты 10 коммитов Айдара от 29–30.11: сверка контрактов API с
обработчиками, проверка звука в браузере, подпись сигналов звонка,
ширина чата, меню настроек, скрытие тестовых версий связей.
Автоматически слиты app.js, словари ru/en и chat.css; конфликт только в
VERSION.properties — у Айдара продолжается откатившаяся линия
(1.20.82 / 1.16.51), взяты значения выше обеих сторон: client 1.21.4,
server 1.17.2 (ветка меняет и UI, и сервер).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:35:18 +03:00
PixelandClaude Opus 5.5 920f0d7217 Слить свежий main в ui/dm-voice
Подтянуты 4 коммита main (CORE/CONTENT, пополнение SOL). Конфликт только
в VERSION.properties: в main версии ушли назад (1.20.77 / 1.16.45 против
1.21.0 / 1.17.0 в точке ветвления), поэтому взяты значения выше обеих
сторон — client 1.21.3, server 1.17.1 (слияние приносит изменения и UI,
и сервера).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:08:16 +03:00
PixelandClaude Opus 5.5 e7349c7bf4 Вернуть очередь файлов с подписью и срок хранения вложений в личке
Коммит 780ca539 (18.11) случайно удалил из chat-view.js функции из
2dd0ed6d (17.11). Возвращены поверх текущего main (подпись в
sendFileAttachmentMessage уже была добавлена вместе с «Поделиться»):

- выбранные файлы копятся в очереди над полем ввода, лишний убирается,
  текст поля уходит подписью, всё отправляется одним сообщением;
- если не удалась загрузка — очередь и подпись остаются для повтора;
  если файлы загружены, а DM не ушёл — повтор без новой загрузки;
- у вложений DM v3 строка «Вложение доступно ещё N дн.», пока срок
  не истёк (срок — из DM_FILE_RETENTION_MS);
- ключи file_remove, remaining_less_day, remaining_days (ru/en).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:07:21 +03:00
PixelandClaude Opus 5.5 1c59b82ff7 Голосовые в личке: волна громкости, жесты записи, пауза и удаление
- Пузырь голосового показывает волну громкости с плавной закраской
  проигранной части; тап по волне перематывает (для webm без duration —
  по полю dur).
- Запись: удержание — запись, отпускание — отправка, влево — отмена с
  эффектом корзины (полоса рассыпается в пыльцу), вверх — замок с паузой,
  удалением и отправкой. Тап показывает подсказку, Enter/пробел сразу
  включают замок, Esc отменяет. Живая волна: столбик раз в 110 мс,
  плавный сдвиг и рост.
- Формат: необязательное поле wf у kind=voice (64 уровня по 5 бит,
  base64url), старые клиенты его игнорируют; получатель проверяет строку.
- Opus 32 кбит/с вместо ~170: файлы в 3–4 раза легче. Тост «Голосовое
  отправлено» убран — подтверждение даёт пузырь в ленте.
- app.js не перемонтирует текущий экран во время записи/отправки
  голосового: повторный рендер того же пути откладывается до конца записи.
- Код вынесен из chat-view.js в components/dm-voice-{recorder,card,waveform}.js,
  стили — в styles/features/dm-voice.css; старые стили записи удалены.
- Возвращены отмена и пауза, потерянные в 780ca539 (18.11).
- Документация: Personal_Messages/README.md, Технические_вставки_DM_v1.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:04:00 +03:00
PixelandClaude Opus 5.5 4d78e87447 Новый текст о шифровании в начале личного чата
Шесть абзацев заменены тремя пунктами: Zero-Knowledge Architecture,
Self-Custody & Open Source, Absolute Control (ru/en). Формулировка
«не имеет доступа к содержимому чатов» — сервер видит метаданные,
но не содержимое. Тест обновлён под редакцию от 27.11.2026.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:15:04 +03:00
PixelandClaude Opus 5.5 55f2d11721 Карточка «Поддержка» в профиле: блок-строка, раскрытие и эффекты
- Под «Сменить профиль» блок-строка с суммами ♡ · ↗ · ✦ в цветах метрик,
  тап раскрывает стеклянную карточку с суммами и историей переводов.
- Раскрытие с подкруткой в видимую область, сияние: кометы «пополнения»,
  блик по рамке со вспышкой, орбита; reduced-motion — статичный вид.
- Стили вынесены в styles/features/profile-support.css, эффекты —
  в js/components/support-shine-effects.js.
- formatStarAmount() — число без символа звезды для вёрстки с SVG-иконкой.
- Ключ screens.support_phase2.summary (ru/en), подписи без emoji.
- DESIGN.md §11.3 и WALLET_SHINE_SUPPORT.md обновлены.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:14:59 +03:00
24 changed files with 2993 additions and 651 deletions
+2 -2
View File
@@ -1,2 +1,2 @@
client.version=1.20.85
server.version=1.16.52
client.version=1.21.8
server.version=1.17.6
+38 -6
View File
@@ -77,15 +77,47 @@ DM: серверный API, подпись и бинарный контейне
### Вложения и запись голосового в UI (17.11.2026)
В личной переписке выбранные файлы остаются в очереди у поля ввода: можно
В личной переписке выбранные файлы остаются в очереди над полем ввода: можно
дописать подпись, убрать файл и отправить всё одним сообщением. Текст
показывается под вложением. У вложений DM v3
показывается оставшийся срок хранения на основе `at` (14 дней). Запись
голосового начинается при нажатии микрофона: короткое нажатие закрепляет запись,
удержание с отпусканием отправляет, движение вверх закрепляет, влево отменяет.
В закреплённом режиме доступны пауза/продолжение, отправка и отмена. Текст в
показывается под вложением. Если не удалась загрузка, очередь и подпись
остаются для повтора; если файлы загружены, а сообщение не ушло, предлагается
повтор без новой загрузки. У вложений DM v3 показывается оставшийся срок
хранения на основе `at` (14 дней), пока он не истёк. Текст в
поле ввода переключает кнопку микрофона в кнопку отправки текста.
Очередь и срок хранения были случайно удалены коммитом `780ca539` (18.11.2026)
и возвращены 29.11.2026.
### Голосовые: волна и жесты записи (29.11.2026)
Запись ведёт `shine-UI/js/components/dm-voice-recorder.js`, пузырь —
`dm-voice-card.js`, волна — `dm-voice-waveform.js`, стили —
`styles/features/dm-voice.css`.
- Удержание микрофона пишет, отпускание отправляет. Во время записи видны
таймер, живая волна громкости (новый столбик раз в 110 мс, полоса едет
плавно) и подсказка «‹ Влево — отмена».
- Движение влево за порог отменяет запись: звук стирается из памяти, микрофон
освобождается, полоса волны растворяется справа налево в облако пыльцы, часть
пылинок втягивается в корзину. Движение вверх на 64 px
закрепляет запись (замок): дальше доступны «Удалить», пауза/продолжение и
отправка кнопкой справа. Esc во время записи отменяет её.
- Короткий тап (до 0,4 с) запись не начинает и показывает подсказку
«Удерживайте, чтобы записать». Enter/пробел на микрофоне начинают запись сразу
в режиме замка. Если система прервала жест (`pointercancel`), запись
закрепляется, а не отправляется и не теряется.
- Пузырь показывает волну из поля `wf` тех-блока (`Технические_вставки_DM_v1.md`)
без скачивания файла; проигранная часть закрашивается, тап по волне
перематывает. У голосовых без `wf` волна считается из звука после первой
загрузки файла и живёт до перезагрузки страницы.
- Запись — opus 32 кбит/с (`audioBitsPerSecond`), отдельного тоста об отправке
нет: подтверждением служит пузырь в ленте.
- Пока идёт запись или отправка голосового, `app.js` не перемонтирует текущий
экран: повторный рендер того же пути (например, после старта сессии)
откладывается до конца записи. Переход на другой маршрут не откладывается и
штатно прерывает запись.
- При `prefers-reduced-motion: reduce` анимаций нет, поведение то же.
HTTP resolver `/api/files/user-server` обязан возвращать JSON через Jetty,
поэтому Caddy должен направлять этот путь до SPA fallback. Если маршрута нет,
клиент показывает ошибку каталога серверов без вывода HTML в интерфейс.
@@ -215,3 +215,24 @@ fromLogin|toLogin|timeMs|nonce
Поле `url` у исторических DM v3 допустимо и обрабатывается по прежней логике.
Для v1/v2 `url` по-прежнему обязателен; криптографические поля и бинарный
контейнер DM не изменяются.
## Дополнение: волна голосового `wf` (29.11.2026)
У `kind=voice` (v2/v3) может быть необязательное поле `wf` — волна громкости
для пузыря голосового, чтобы получатель видел её, не скачивая файл:
```text
<S:file;v=3;id=...;key=...;ivp=...;name=...;mime=audio%2Fwebm;size=...;encsize=...;chunk=...;chunks=1;kind=voice;dur=4200;wf=BASE64URL_54_CHARS;at=1764400000000>
```
- 64 уровня громкости 0–31, по 5 бит подряд (старший бит первым), 40 байт,
base64url без `=` — 54 символа.
- Отправитель считает уровни во время записи (RMS каждые 50 мс, максимум по
64 отрезкам, нормировка по пику), паузы в волну не попадают.
- Поле приходит от собеседника, поэтому получатель принимает только
`^[A-Za-z0-9_-]{1,64}$` и успешно декодируемую строку; иначе голосовое
показывается без волны. У `kind=file` поле не пишется и не читается.
- Старые клиенты незнакомое поле игнорируют. При пересылке голосового `wf`
копируется вместе с блоком. Сервер поле не видит: оно внутри E2EE plaintext.
- Код: `shine-UI/js/components/dm-voice-waveform.js` (`encodeWaveform`,
`decodeWaveform`), сборка и разбор — `shine-UI/js/services/dm-tech-blocks.js`.
+30
View File
@@ -245,6 +245,35 @@ Safe area учитывается ровно один раз владельцем
Наследование визуальной системы не означает изменения протоколов или применения ленты каналов к личному диалогу. Каждый следующий раздел добавляет свои сценарии в отдельный документ со ссылкой на эту основу, а не копирует собственные палитры и наборы кнопок.
### 11.3. Карточка «Поддержка» в профиле — «Ethereal Monochrome»
Решение пользователя от 26–27.11.2026: статистика поддержки (свой и чужой профиль) — блок-строка с суммами под «Сменить профиль», которая по тапу «выезжает» в стеклянную карточку «Ethereal Monochrome» (тихое стекло, контурные иконки, эфирное свечение); тап по заголовку карточки сворачивает её обратно. Остальной профиль не меняется. Владельцы: разметка и данные `shine-UI/js/components/support-stats.js`, одноразовые эффекты `shine-UI/js/components/support-shine-effects.js`, стили `shine-UI/styles/features/profile-support.css`. Данные и логика прежние: суммы из `GetSupportStats`, Free-аккаунт — блок скрыт, ошибка сети не выдаётся за нули, история переводов подгружается при раскрытии.
| Элемент | Реализация |
| --- | --- |
| Строка | Блок как соседний «Сменить профиль»: `surface`, `border-subtle`, `radius-lg`, высота 64 px; по центру `♡ 0.30★ · ↗ 0.50★ · ✦ 1.00★ ⌄` кеглем `--text-lg` (до 380 px — `--text-md`, строка без переноса и на 320 px). Пока данных нет — неактивна и показывает «Загрузка…»/«Недоступна». Скринридер слышит всю сводку (`screens.support_phase2.summary`) |
| Раскрытие | Строка и карточка — две строки одной сетки (`grid-template-rows` 1fr↔0fr, 420 мс): строка сворачивается, карточка выезжает. Пока карточка выезжает, она подкручивается в видимую область (блок стоит внизу профиля, иначе уходил бы под панель навигации); так же подтягиваются записи открытой истории. `aria-expanded`/`aria-controls`; скрытая часть `inert`; фокус переходит на заголовок «Поддержка ⌃» и обратно на строку |
| Поверхность | Полупрозрачный градиент из `surface-raised`/`surface`, `backdrop-filter: blur(24px)`, радиус 20 px; грань — металлический кант 1 px из `text-primary` маской (блики на правом верхнем и левом нижнем углах, внутренняя фаска inset-тенью; интерьер не подсвечивается). Ночью тёмное стекло, днём светлое матовое — без отдельных констант цвета |
| Иконки | Общий `ui-icon.js`: `heart`, `trend-up`, `sparkle`, валюта — залитая `star`; толщина штриха общая для приложения (1.75). Emoji из подписей убраны |
| Суммы | Число + SVG-звезда; скринридер получает «0.10 ⭐» (`.sr-only`). В строке иконка, число и звезда — в цвете метрики; в карточке цветные иконка и звезда, число — `text-primary`. Нулевая сумма приглушена `text-secondary` |
| История переводов | `<summary>` 44 px по центру со стрелкой (поворот при раскрытии); строки «кому — сумма / дата · SOL — транзакция»; даты через `formatDateTime` |
Явные отклонения от §2/§4 (согласованы с пользователем):
1. **Цвета метрик** вместо монохрома: ♡ «Поддержал других» — `--accent`, ↗ «Получил поддержку» — `--success`, ✦ «Поддержал SHiNE» — `--warning` (в обеих темах — свои значения токенов).
2. **Дыхание иконок и звёзд** — пульсация `drop-shadow` с циклом 4 с только у ненулевых сумм и только в раскрытой карточке; текст без свечения. Аналог принятой ауры сияющего аватара.
3. **Сияние при раскрытии и при тапе по карточке** — одноразовое, по референсу пользователя:
- «пополнение»: в каждой ненулевой строке комета цвета метрики летит дугой от иконки под подписью к сумме (0.65 с, строки с задержкой 260 мс), оставляя светящийся хвост и пылинки; при попадании сумма вспыхивает искрами и досчитывается от нуля (0.7 с), на это время окрашиваясь в цвет метрики с мягким свечением (`text-shadow`) — затем плавно возвращается к обычному виду;
- золотой блик ровно по контуру рамки обходит её за 1.4 с и гаснет звёздочкой-вспышкой в правом верхнем углу; кант на это время слегка золотится;
- пунктирная орбита с золотыми точками вокруг карточки (2.4 с, не дальше 10 px за край — без горизонтальной прокрутки на 320 px).
Повторный запуск прерывает предыдущий; при сворачивании и уходе со страницы всё останавливается, суммы сразу итоговые. Слои `aria-hidden` и удаляются по `animationend`, единый цикл rAF проверяет жизнь страницы. Днём у головы кометы светлая сердцевина и узкий ореол (тёмный тон с широким ореолом на светлом стекле читается пятном).
4. **Вдавливание всей карточки** — тап по любой её части, кроме заголовка и истории: `scale(.97)` за 150 мс, пружинный возврат 400 мс (кривая с перелётом), затем повтор сияния.
5. **Жидкий свет при нажатии на «История переводов»** — 0.8 с: капля и две капельки сливаются SVG-фильтром `#profile-support-goo`. Фильтр стоит только на отдельном слое под текстом (на всю кнопку нельзя — порог альфы стирает буквы); капли непрозрачные, яркость задаёт `opacity` слоя. Капли удаляются по `animationend`/`animationcancel`, без таймеров.
6. **Мягкая тень глубины** у самой карточки.
Пружинный отклик строки и кнопки истории (`scale(.97)`, 180 мс) укладывается в правило §4. Всё движение в CSS объявлено внутри `@media (prefers-reduced-motion: no-preference)`: при reduced-motion вид статичный — без раскрывающего перехода, дыхания, вдавливания, сияния и капель света. Из исходного ТЗ сознательно не перенесено: постоянное свечение цифр (только кратко во время «пополнения»), жёсткие тёмные цвета.
## 12. Допущения и отложенные решения
Блокирующих вопросов для документа нет. Рабочие решения: тема по системе с ручным выбором, размеры из раздела 4, сохранение черновика внутри текущей сессии, единый редактор с адаптацией для desktop.
@@ -290,3 +319,4 @@ Safe area учитывается ровно один раз владельцем
| 22.09.2026 | 0.1 | Четыре самостоятельных HTML-направления для обсуждения |
| 22.09.2026 | 0.2 | Пользователь выбрал Ночной SHiNE, дневную тёплую палитру, компактную шапку, полноэкранный ответ; общее число лайков, оглавление в меню; плотность принята |
| 22.09.2026 | 0.2 | Специфицированы семантические цвета двух тем, общие компоненты, состояния, адаптация, правила расширения и матрица приёмки. Это документация будущего переноса, не выполненное изменение приложения |
| 26.11.2026 | 0.3 | «Поддержка» в профиле (§11.3): блок-строка с суммами под «Сменить профиль» (размером с соседний блок) раскрывается в стеклянную карточку «Ethereal Monochrome» и сворачивается по заголовку. Отклонения: цвета метрик, дыхание иконок 4 с, одноразовое сияние («пополнение» кометами со счётом сумм и искрами, блик по рамке со вспышкой в углу, орбита), вдавливание карточки 0.4 с, жидкий свет истории 0.8 с; постоянное свечение текста и тёмные константы цвета не переносятся |
+4
View File
@@ -18,6 +18,10 @@
Проверка: `node --test shine-UI/tests/support-phase2.test.mjs shine-UI/tests/wallet-donate-menu.test.mjs`.
## Карточка «Поддержка» в профиле (26.11.2026)
`attachSupportStats()` (`shine-UI/js/components/support-stats.js`) добавляет в свой и чужой профиль, сразу под «Сменить профиль», блок-строку с тремя суммами из `GetSupportStats`: «Поддержал других», «Получил поддержку», «Поддержал SHiNE» (`dao_direct`). Тап по строке раскрывает карточку с этими суммами и раскрываемой «Историей переводов» (`GetSupportHistory`, порциями по 20); тап по заголовку карточки сворачивает её. Для Free-аккаунта блок не показывается; ошибка сети не выдаётся за нули. Подписи — `screens.support_phase2.*` (без emoji, иконки SVG); суммы выводятся числом через `formatStarAmount()`, а `formatStars()` («0.10 ⭐») по-прежнему используется в окнах пожертвования и в голосовой сводке строки. Оформление «Ethereal Monochrome», эффекты (`support-shine-effects.js`) и их отклонения от общих правил — `docs/UI-Design/DESIGN.md` §11.3.
## Мультивалютный кошелёк и прямые переводы (17.11.2026)
Добавлен отдельный маршрут `wallet/transfer` и `wallet/transfer/<login>`: форма с валютой SOL/USDT, балансами и подтверждением суммы. Из чата получатель фиксирован (логин + найденный blockchainKey), из кошелька вводится только произвольный адрес Base58. Опциональное DM-уведомление доступно только при переводе из чата; при каждом открытии формы его галочка включена по умолчанию, пользователь может её снять.
+1 -1
View File
@@ -45,7 +45,7 @@ window.__SHINE_BUILD_HASH__ = '20261119-graph-v4c';
<script>
(function attachStylesWithBuildHash() {
const v = encodeURIComponent(window.__SHINE_BUILD_HASH__ || 'dev');
const cssFiles = ['./styles/main.css', './styles/layout.css', './styles/app-shell.css', './styles/buttons-white.css', './styles/components/topbar.css', './styles/components/dropdown-menu.css', './styles/components/primitives.css', './styles/components/feedback.css', './styles/components/tabs.css', './styles/components/chips.css', './styles/components/nav-list.css', './styles/components/palette-editor.css', './styles/components/avatar.css', './styles/components/modal.css', './styles/components/person-note.css', './styles/components/person-row.css', './styles/components/compose.css', './styles/components/attachments.css', './styles/components/media-viewer.css', './styles/components/channel-editor.css', './styles/components/emoji-picker.css', './styles/components/call-ui.css', './styles/components/scroll-to-bottom.css', './styles/components/overflow-dots.css', './styles/components/toolbar.css', './styles/features/preauth.css', './styles/features/messages.css', './styles/features/chat.css', './styles/features/channels-common.css', './styles/features/channels-list.css', './styles/features/channel.css', './styles/features/channel-thread.css', './styles/features/notifications.css', './styles/features/network.css', './styles/features/profile.css', './styles/features/profile-page.css', './styles/features/settings.css', './styles/features/devices.css', './styles/features/developer-tools.css', './styles/features/wallet-transfer.css', './styles/features/wallet-swap.css', './styles/network-graph.css', './styles/network-legacy.css'];
const cssFiles = ['./styles/main.css', './styles/layout.css', './styles/app-shell.css', './styles/buttons-white.css', './styles/components/topbar.css', './styles/components/dropdown-menu.css', './styles/components/primitives.css', './styles/components/feedback.css', './styles/components/tabs.css', './styles/components/chips.css', './styles/components/nav-list.css', './styles/components/palette-editor.css', './styles/components/avatar.css', './styles/components/modal.css', './styles/components/person-note.css', './styles/components/person-row.css', './styles/components/compose.css', './styles/components/attachments.css', './styles/components/media-viewer.css', './styles/components/channel-editor.css', './styles/components/emoji-picker.css', './styles/components/call-ui.css', './styles/components/scroll-to-bottom.css', './styles/components/overflow-dots.css', './styles/components/toolbar.css', './styles/features/preauth.css', './styles/features/messages.css', './styles/features/chat.css', './styles/features/dm-voice.css', './styles/features/channels-common.css', './styles/features/channels-list.css', './styles/features/channel.css', './styles/features/channel-thread.css', './styles/features/notifications.css', './styles/features/network.css', './styles/features/profile.css', './styles/features/profile-page.css', './styles/features/profile-support.css', './styles/features/settings.css', './styles/features/devices.css', './styles/features/developer-tools.css', './styles/features/wallet-transfer.css', './styles/features/wallet-swap.css', './styles/network-graph.css', './styles/network-legacy.css'];
// Стили, добавленные скриптом, браузер не ждёт перед первой отрисовкой: без этого
// на долю секунды виден экран без CSS (логотип 640×640), а потом он «прыгает» на место.
const root = document.documentElement;
+16
View File
@@ -1,6 +1,7 @@
import { restoreShare, activateShare, allowShareNavigation, restoreSharePath, checkShareOwner, getPendingShare, finishShare, isShareSending } from './services/share-flow.js';
import { isDmPreviewHidden } from './services/dm-preview-settings.js';
import { dmPreviewTarget, dmPreviewText, fetchDmPreview } from './services/dm-preview.js';
import { isVoiceRecordingActive, onVoiceRecordingIdle } from './components/dm-voice-recorder.js';
import { initI18n, onLanguageChange, t } from './i18n/index.js';
import { preventPagePinchZoom } from './services/pwa-viewport-gestures.js';
preventPagePinchZoom();
@@ -238,6 +239,9 @@ const CURRENT_BUILD_HASH = String(window.__SHINE_BUILD_HASH__ || '').trim();
const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/;
let currentCleanup = null;
// Путь смонтированного экрана: повторный рендер того же экрана во время записи голосового откладывается.
let mountedPath = '';
let renderDeferredByVoice = false;
let pingIntervalId = null;
let reconnectIntervalId = null;
let channelsPrefetchTimerId = null;
@@ -1440,6 +1444,14 @@ async function redirectToActiveKeyRotationIfNeeded() {
function renderApp() {
// Avoid remounting the composer while an encrypted share upload is in progress.
if (state.session.isAuthorized && isShareSending()) return;
// Перемонтирование того же экрана оборвало бы запись или отправку голосового (например,
// обновление после старта сессии при плохой сети). Ждём конца записи; переход на другой
// маршрут не откладывается — уход со страницы прерывает запись штатно.
if (isVoiceRecordingActive() && window.location.pathname === mountedPath) {
renderDeferredByVoice = true;
return;
}
renderDeferredByVoice = false;
if (state.session.isAuthorized && !keyRotationRouteLock) {
checkShareOwner(state.session.login);
if (activateShare(state.session.login) && window.location.pathname !== '/contacts') { navigate('contacts'); return; }
@@ -1509,6 +1521,7 @@ function renderApp() {
}
screenEl.append(screen);
mountedPath = window.location.pathname;
const pageCleanup = typeof screen.cleanup === 'function' ? screen.cleanup : null;
const scrollToBottomControl = attachPageScrollToBottom(pageId, screen);
currentCleanup = () => {
@@ -2100,6 +2113,9 @@ async function init() {
if (!allowShareNavigation(window.location.pathname)) { restoreSharePath(); return; }
renderApp();
});
onVoiceRecordingIdle(() => {
if (renderDeferredByVoice) renderApp();
});
document.addEventListener('pointerdown', () => {
void unlockDmAudio();
}, { passive: true });
+189
View File
@@ -0,0 +1,189 @@
// Пузырь голосового в личной переписке: кнопка воспроизведения, волна громкости
// с плавной закраской проигранной части и перемотка тапом по волне.
import { t } from '../i18n/index.js';
import { iconHtml } from './ui-icon.js';
import { decryptDmFileToBlob } from '../services/dm-file-service.js';
import { showToast } from '../services/channels-ux.js';
import { actionErrorText } from '../services/ui-error-texts.js';
import {
computeWaveformFromBlob,
computedWaveformFor,
decodeWaveform,
fillWaveformBars,
rememberComputedWaveform,
resampleWaveform,
} from './dm-voice-waveform.js';
const CARD_BARS = 40;
// Голосовые, отправленные до появления `wf`: ровная низкая полоса, пока файл не загружен.
const PLACEHOLDER_LEVEL = 0.16;
export function formatVoiceDuration(durationMs = 0) {
const total = Math.max(0, Math.round(Number(durationMs || 0) / 1000));
const minutes = Math.floor(total / 60);
const seconds = total % 60;
return `${minutes}:${String(seconds).padStart(2, '0')}`;
}
export function createDmVoiceAttachmentCard(attachment) {
const card = document.createElement('div');
card.className = 'dm-voice-card';
const playBtn = document.createElement('button');
playBtn.type = 'button';
playBtn.className = 'ui-button dm-voice-card__play';
const body = document.createElement('div');
body.className = 'dm-voice-card__body';
const track = document.createElement('button');
track.type = 'button';
track.className = 'ui-button dm-voice-card__track';
track.setAttribute('aria-label', t('dialogs.modals.chat_view.label_025'));
const wave = document.createElement('span');
wave.className = 'dm-voice-wave dm-voice-card__wave';
wave.setAttribute('aria-hidden', 'true');
const played = document.createElement('span');
played.className = 'dm-voice-wave dm-voice-card__wave dm-voice-card__wave--played';
played.setAttribute('aria-hidden', 'true');
track.append(wave, played);
const meta = document.createElement('div');
meta.className = 'dm-voice-card__meta';
const duration = document.createElement('span');
duration.textContent = formatVoiceDuration(attachment?.durationMs || 0);
const label = document.createElement('span');
label.textContent = t('dialogs.modals.chat_view.label_026');
meta.append(duration, label);
body.append(track, meta);
card.append(playBtn, body);
let values = decodeWaveform(attachment?.waveform) || computedWaveformFor(attachment?.id);
const paintWave = () => {
const levels = values ? resampleWaveform(values, CARD_BARS) : new Array(CARD_BARS).fill(PLACEHOLDER_LEVEL);
fillWaveformBars(wave, levels);
fillWaveformBars(played, levels);
card.classList.toggle('is-placeholder', !values);
};
paintWave();
let shownPlaying = null;
const setPlaying = (playing) => {
if (shownPlaying === playing) return;
shownPlaying = playing;
playBtn.innerHTML = iconHtml(playing ? 'pause' : 'play', !playing);
playBtn.setAttribute('aria-label', t(playing ? 'screens.chat_view.voice.pause_playback' : 'dialogs.modals.chat_view.label_024'));
};
setPlaying(false);
let audio = null;
let objectUrl = '';
let loading = false;
let frame = 0;
const release = () => {
window.cancelAnimationFrame(frame);
frame = 0;
try { audio?.pause(); } catch { /* уже остановлен */ }
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
objectUrl = '';
}
};
const totalSeconds = () => (Number.isFinite(audio?.duration) && audio.duration > 0
? audio.duration
: Math.max(0, Number(attachment?.durationMs || 0) / 1000));
const syncProgress = () => {
if (!audio) return;
if (!card.isConnected) {
release();
return;
}
const total = totalSeconds();
const current = Math.max(0, Number(audio.currentTime || 0));
track.style.setProperty('--progress', total > 0 ? Math.min(1, current / total).toFixed(4) : '0');
const text = `${formatVoiceDuration(current * 1000)} / ${formatVoiceDuration(total * 1000)}`;
if (duration.textContent !== text) duration.textContent = text;
setPlaying(!audio.paused);
};
// timeupdate приходит ~4 раза в секунду: закраска волны рывками. Пока играет — ведём её по кадрам.
const followPlayback = () => {
frame = 0;
syncProgress();
if (audio && !audio.paused && card.isConnected) frame = window.requestAnimationFrame(followPlayback);
};
const ensureAudio = async () => {
if (audio) return audio;
if (loading) return null;
loading = true;
playBtn.disabled = true;
try {
const blob = await decryptDmFileToBlob(attachment);
objectUrl = URL.createObjectURL(blob);
audio = new Audio(objectUrl);
audio.preload = 'metadata';
audio.addEventListener('timeupdate', syncProgress);
audio.addEventListener('loadedmetadata', syncProgress);
audio.addEventListener('pause', syncProgress);
audio.addEventListener('play', () => {
window.cancelAnimationFrame(frame);
followPlayback();
});
audio.addEventListener('ended', () => {
audio.currentTime = 0;
syncProgress();
});
audio.addEventListener('error', () => {
showToast(t('screens.chat_view.text_041'), { kind: 'error', timeoutMs: 2200 });
});
if (!values) {
// Волна старого голосового — украшение: если браузер не декодирует формат,
// остаётся заглушка, а воспроизведение работает как обычно.
computeWaveformFromBlob(blob).then((computed) => {
if (!computed) return;
rememberComputedWaveform(attachment?.id, computed);
values = computed;
if (card.isConnected) paintWave();
}).catch(() => {});
}
return audio;
} finally {
loading = false;
playBtn.disabled = false;
}
};
playBtn.addEventListener('click', async (event) => {
event.stopPropagation();
try {
const player = await ensureAudio();
if (!player) return;
if (player.paused) await player.play();
else player.pause();
syncProgress();
} catch (error) {
showToast(actionErrorText(t('screens.chat_view.text_042'), error), { kind: 'error' });
}
});
track.addEventListener('click', async (event) => {
event.stopPropagation();
try {
const player = await ensureAudio();
// У webm из MediaRecorder duration = Infinity до полной прокрутки: берём длительность из `dur`.
const total = player ? totalSeconds() : 0;
if (!player || total <= 0) return;
const rect = track.getBoundingClientRect();
const ratio = Math.min(1, Math.max(0, (event.clientX - rect.left) / Math.max(1, rect.width)));
player.currentTime = total * ratio;
syncProgress();
} catch (error) {
showToast(actionErrorText(t('screens.chat_view.text_043'), error), { kind: 'error' });
}
});
return card;
}
+686
View File
@@ -0,0 +1,686 @@
// Запись голосового в личной переписке.
// Удержание микрофона — запись; отпустил — отправка; влево — отмена с эффектом корзины;
// вверх — замок, в котором есть пауза, удаление и отправка. Короткий тап только подсказывает.
// Модуль — единственный владелец микрофона, MediaRecorder, анализатора громкости и панели
// записи. Кнопкой и загрузкой файла владеет страница чата: она передаёт сюда события
// указателя и получает готовый файл через onRecorded.
import { th } from '../i18n/index.js';
import { compressLevels, encodeWaveform, rmsLevel } from './dm-voice-waveform.js';
import { iconHtml } from './ui-icon.js';
const TAP_MS = 400;
const LOCK_DISTANCE = 64;
const CANCEL_MIN = 90;
const CANCEL_MAX = 150;
const CANCEL_RATIO = 0.4;
// Отсчёты громкости для поля wf: часто, чтобы волна в сообщении была точной.
const SAMPLE_MS = 50;
// Живая волна на экране идёт вдвое медленнее отсчётов: новый столбик раз в 110 мс,
// а между ними полоса едет плавно — без ряби от 20 скачков в секунду.
const LIVE_STEP_MS = 110;
const LIVE_BARS = 40;
const BAR_GROW_MS = 180;
const HALO_SMOOTHING = 0.2;
const TIP_MS = 2400;
const SNAP_MS = 380;
const RETURN_MS = 320;
const TRASH_MS = 1300;
const DISSOLVE_DELAY_MS = 120;
const DISSOLVE_MS = 480;
const DUST_COUNT = 64;
// Доля пылинок, которые втягиваются в корзину; остальные разлетаются облаком.
const DUST_TO_TRASH = 0.3;
const MIME_CANDIDATES = ['audio/webm;codecs=opus', 'audio/ogg;codecs=opus', 'audio/mp4', 'audio/webm'];
// Голосу хватает 32 кбит/с (opus): по умолчанию браузер пишет ~128–170 кбит/с,
// и файлы выходят в 4–5 раз тяжелее без слышимой разницы для речи.
const VOICE_BITRATE = 32_000;
const IDLE_EVENT = 'shine-voice-recording-idle';
const AUDIO_CONSTRAINTS = {
audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
video: false,
};
const LIVE_STATES = new Set(['holding', 'locked', 'paused']);
const PANEL_STATES = new Set(['holding', 'locked', 'paused', 'cancelling']);
const svg = (body, className = '') => `<svg${className ? ` class="${className}"` : ''} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
// Крышка корзины — отдельная группа: при удалении записи она откидывается и захлопывается.
const TRASH_SVG = svg('<g class="dm-voice-trash__lid"><path d="M4 7h16M9.5 7V4.8h5V7"/></g><path d="M6.5 7l.9 12.2a1.9 1.9 0 0 0 1.9 1.8h5.4a1.9 1.9 0 0 0 1.9-1.8L17.5 7M10 11v6M14 11v6"/>', 'dm-voice-trash');
// Дужка замка поднята, пока запись не закреплена.
const LOCK_SVG = svg('<path class="dm-voice-lock-icon__shackle" d="M8.5 11V8a3.5 3.5 0 0 1 7 0v3"/><rect x="5.5" y="11" width="13" height="9.5" rx="2.5"/>', 'dm-voice-lock-icon');
const CHEVRON_UP = svg('<path d="m7 14 5-5 5 5"/>', 'dm-voice-lock__arrow');
const CHEVRON_LEFT = svg('<path d="m14.5 6-6 6 6 6"/>');
const now = () => performance.now();
const vibrate = (pattern) => {
try { navigator.vibrate?.(pattern); } catch { /* вибрация есть не везде */ }
};
const prefersReducedMotion = () => Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches);
// RMS речи обычно 0.02–0.3: корень растягивает тихие звуки, чтобы живая волна не лежала плоско.
const displayLevel = (level) => Math.min(1, Math.sqrt(Math.max(0, level)) * 1.7);
function clock(ms) {
const total = Math.max(0, Math.floor(ms / 1000));
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
}
// Активные записи всех экземпляров. App не перерисовывает текущий экран, пока идёт запись
// или отправка голосового: иначе перемонтирование страницы оборвало бы её.
const activeRecorders = new Set();
export function isVoiceRecordingActive() {
return activeRecorders.size > 0;
}
/** Колбэк вызывается, когда не осталось ни одной активной записи. Возвращает отписку. */
export function onVoiceRecordingIdle(callback) {
window.addEventListener(IDLE_EVENT, callback);
return () => window.removeEventListener(IDLE_EVENT, callback);
}
function markRecorderActive(owner, active) {
const had = activeRecorders.has(owner);
if (active) activeRecorders.add(owner);
else activeRecorders.delete(owner);
if (!had || active || activeRecorders.size) return;
// Асинхронно: отложенная перерисовка не должна начаться посреди смены состояния записи.
window.setTimeout(() => {
if (!activeRecorders.size) window.dispatchEvent(new CustomEvent(IDLE_EVENT));
}, 0);
}
function pickMimeType() {
return MIME_CANDIDATES.find((mime) => globalThis.MediaRecorder?.isTypeSupported?.(mime)) || '';
}
function extensionFor(mime = '') {
const value = String(mime).toLowerCase();
if (value.includes('ogg')) return 'ogg';
if (value.includes('mp4') || value.includes('m4a')) return 'm4a';
return 'webm';
}
/**
* @param {object} options
* @param {HTMLFormElement} options.form — панель ввода (здесь живут замок и подсказка)
* @param {HTMLElement} options.bar — капсула ввода (здесь живёт панель записи)
* @param {() => boolean} options.canStart — страница проверяет свои запреты и сама объясняет отказ
* @param {(state: string) => void} options.onStateChange
* @param {(result: {file: File, durationMs: number, waveform: string}) => Promise<void>} options.onRecorded
* @param {(problem: {kind: 'unsupported'|'media'|'recorder'|'send', error?: unknown}) => void} options.onError
*/
export function createDmVoiceRecorder({ form, bar, canStart, onStateChange, onRecorded, onError }) {
const panel = document.createElement('div');
panel.className = 'dm-voice-panel';
panel.hidden = true;
// Точка записи и корзина делят одну ячейку: при удалении корзина появляется на месте точки
// и ничего в панели не сдвигается.
panel.innerHTML = `
<span class="dm-voice-panel__lead">
<span class="dm-voice-panel__dot" aria-hidden="true"></span>
<button type="button" class="dm-voice-panel__btn dm-voice-panel__delete" aria-label="${th('screens.chat_view.voice.delete')}">${TRASH_SVG}</button>
</span>
<span class="dm-voice-panel__time">0:00</span>
<span class="dm-voice-panel__wave" aria-hidden="true"><span class="dm-voice-panel__strip"></span></span>
<span class="dm-voice-panel__slide" aria-hidden="true">${CHEVRON_LEFT}<span>${th('screens.chat_view.voice.slide_cancel')}</span></span>
<button type="button" class="dm-voice-panel__btn dm-voice-panel__pause"></button>
`;
const deleteBtn = panel.querySelector('.dm-voice-panel__delete');
const dotEl = panel.querySelector('.dm-voice-panel__dot');
const timeEl = panel.querySelector('.dm-voice-panel__time');
const waveEl = panel.querySelector('.dm-voice-panel__wave');
const stripEl = panel.querySelector('.dm-voice-panel__strip');
const pauseBtn = panel.querySelector('.dm-voice-panel__pause');
const lock = document.createElement('div');
lock.className = 'dm-voice-lock';
lock.hidden = true;
lock.setAttribute('aria-hidden', 'true');
lock.innerHTML = `${LOCK_SVG}${CHEVRON_UP}`;
const tip = document.createElement('div');
tip.className = 'dm-voice-tip';
tip.setAttribute('role', 'status');
bar.insertBefore(panel, bar.querySelector('.dm-field'));
form.append(lock, tip);
let state = 'idle';
let rec = null;
let session = 0;
let destroyed = false;
let audioCtx = null;
let frame = 0;
let pointerId = null;
let startX = 0;
let startY = 0;
let pressedAt = 0;
let released = false;
let lastClock = '';
let tipTimer = 0;
let snapTimer = 0;
let returnTimer = 0;
let escBound = false;
let effect = null;
let barStep = 0;
const owner = {};
const canPause = () => typeof rec?.recorder?.pause === 'function' && typeof rec?.recorder?.resume === 'function';
function syncPauseButton() {
const paused = state === 'paused';
pauseBtn.hidden = !canPause();
pauseBtn.innerHTML = iconHtml(paused ? 'mic' : 'pause');
pauseBtn.setAttribute('aria-label', th(paused ? 'screens.chat_view.voice.resume' : 'screens.chat_view.voice.pause'));
}
const onKeydown = (event) => {
if (event.key !== 'Escape' || !LIVE_STATES.has(state)) return;
event.preventDefault();
void cancel();
};
function syncEscListener() {
const wanted = LIVE_STATES.has(state) && !destroyed;
if (wanted === escBound) return;
escBound = wanted;
if (wanted) document.addEventListener('keydown', onKeydown);
else document.removeEventListener('keydown', onKeydown);
}
function setState(next) {
const previous = state;
state = next;
markRecorderActive(owner, next !== 'idle' && !destroyed);
panel.hidden = !PANEL_STATES.has(next);
panel.dataset.state = next;
if (next !== 'holding') panel.style.removeProperty('--slide');
window.clearTimeout(snapTimer);
if (next === 'holding') {
lock.hidden = false;
lock.classList.remove('is-snapped');
lock.style.removeProperty('--lift');
} else if (previous === 'holding' && next === 'locked') {
// Замок защёлкивается на глазах и только потом исчезает.
lock.classList.add('is-snapped');
snapTimer = window.setTimeout(() => { lock.hidden = true; }, SNAP_MS);
} else {
lock.hidden = true;
}
if (PANEL_STATES.has(previous) && !PANEL_STATES.has(next)) playReturn();
syncPauseButton();
syncEscListener();
if (!destroyed) onStateChange(next);
}
// Панель записи ушла — поле ввода и кнопки проявляются, а не возникают рывком.
function playReturn() {
if (prefersReducedMotion()) return;
window.clearTimeout(returnTimer);
form.classList.remove('dm-voice-return');
void form.offsetWidth;
form.classList.add('dm-voice-return');
returnTimer = window.setTimeout(() => form.classList.remove('dm-voice-return'), RETURN_MS);
}
function ensureAudioContext() {
// iOS разрешает запуск звука только внутри жеста: контекст создаётся до запроса микрофона.
const Context = globalThis.AudioContext || globalThis.webkitAudioContext;
if (!Context) return;
try {
if (!audioCtx || audioCtx.state === 'closed') audioCtx = new Context();
void audioCtx.resume?.()?.catch?.(() => {});
} catch {
audioCtx = null;
}
}
function connectAnalyser(current) {
if (!audioCtx) return;
try {
current.source = audioCtx.createMediaStreamSource(current.stream);
current.analyser = audioCtx.createAnalyser();
current.analyser.fftSize = 1024;
current.samples = new Float32Array(current.analyser.fftSize);
current.source.connect(current.analyser);
} catch {
// Без анализатора запись работает, просто без живой волны и без поля wf.
current.analyser = null;
}
}
function readLevel() {
const analyser = rec?.analyser;
if (!analyser?.getFloatTimeDomainData) return 0;
analyser.getFloatTimeDomainData(rec.samples);
return rmsLevel(rec.samples);
}
function elapsedMs() {
if (!rec) return 0;
return rec.activeMs + (rec.segmentStartedAt ? now() - rec.segmentStartedAt : 0);
}
function paintClock(ms) {
const text = clock(ms);
if (text === lastClock) return;
lastClock = text;
timeEl.textContent = text;
}
function makeBar(level) {
const bar = document.createElement('span');
bar.className = 'dm-voice-wave__bar';
bar.style.setProperty('--level', level.toFixed(3));
return bar;
}
/** Полоса из LIVE_BARS + 1 столбика: лишний — тот, что сейчас въезжает справа. */
function resetStrip() {
stripEl.replaceChildren(...Array.from({ length: LIVE_BARS + 1 }, () => makeBar(0)));
stripEl.style.transform = '';
barStep = 0;
}
/** Новый столбик встаёт в конец полосы, самый старый уходит; высоты остальных не трогаем. */
function pushLiveBar(level) {
const bar = makeBar(level);
stripEl.append(bar);
while (stripEl.children.length > LIVE_BARS + 1) stripEl.firstElementChild.remove();
if (!prefersReducedMotion() && typeof bar.animate === 'function') {
// Столбик вырастает, а не появляется скачком: волна «дышит» мягко.
bar.animate(
[{ transform: 'scaleY(0.12)' }, { transform: `scaleY(${Math.max(0.12, level).toFixed(3)})` }],
{ duration: BAR_GROW_MS, easing: 'ease-out' },
);
}
}
function tick() {
frame = 0;
if (destroyed || !rec || (state !== 'holding' && state !== 'locked')) return;
const level = readLevel();
const ms = elapsedMs();
// Отсчёты по времени записи, а не по кадрам: в фоне кадров нет, а волна не должна сжиматься.
while (rec.nextSampleAt <= ms) {
rec.levels.push(level);
rec.nextSampleAt += SAMPLE_MS;
}
rec.windowSum += level;
rec.windowPeak = Math.max(rec.windowPeak, level);
rec.windowCount += 1;
while (rec.nextBarAt <= ms) {
// Высота столбика — среднее с пиком за его 110 мс, а не один случайный замер.
const mean = rec.windowCount ? rec.windowSum / rec.windowCount : level;
pushLiveBar(displayLevel((mean + rec.windowPeak) / 2));
rec.windowSum = 0;
rec.windowPeak = 0;
rec.windowCount = 0;
rec.nextBarAt += LIVE_STEP_MS;
}
if (!barStep && stripEl.children.length > 1) {
barStep = stripEl.children[1].offsetLeft - stripEl.children[0].offsetLeft;
}
// Между столбиками полоса едет плавно: новый въезжает справа ровно за LIVE_STEP_MS.
const shift = Math.max(0, Math.min(1, (rec.nextBarAt - ms) / LIVE_STEP_MS)) * barStep;
stripEl.style.transform = `translateX(${shift.toFixed(2)}px)`;
paintClock(ms);
rec.halo += (displayLevel(level) - rec.halo) * HALO_SMOOTHING;
form.style.setProperty('--voice-level', rec.halo.toFixed(3));
frame = window.requestAnimationFrame(tick);
}
function startLoop() {
if (!frame) frame = window.requestAnimationFrame(tick);
}
function stopLoop() {
window.cancelAnimationFrame(frame);
frame = 0;
form.style.removeProperty('--voice-level');
}
function releaseMedia(current) {
try { current.stream?.getTracks?.().forEach((track) => track.stop()); } catch { /* микрофон уже освобождён */ }
try { current.source?.disconnect(); } catch { /* граф уже разобран */ }
current.source = null;
current.analyser = null;
void audioCtx?.suspend?.()?.catch?.(() => {});
}
/** Бросить текущую запись: звук и уровни стираются, микрофон освобождается. */
function discardRecording() {
const current = rec;
rec = null;
stopLoop();
if (!current) return;
current.chunks.length = 0;
current.levels.length = 0;
try {
if (current.recorder.state !== 'inactive') current.recorder.stop();
} catch { /* уже остановлен */ }
releaseMedia(current);
}
async function openMicrophone(id) {
try {
const stream = await navigator.mediaDevices.getUserMedia(AUDIO_CONSTRAINTS);
if (destroyed || id !== session) {
stream.getTracks().forEach((track) => track.stop());
return false;
}
const mimeType = pickMimeType();
const options = mimeType ? { mimeType, audioBitsPerSecond: VOICE_BITRATE } : { audioBitsPerSecond: VOICE_BITRATE };
const recorder = new MediaRecorder(stream, options);
const current = {
stream, recorder, mimeType, chunks: [], levels: [],
activeMs: 0, segmentStartedAt: 0, nextSampleAt: 0,
nextBarAt: LIVE_STEP_MS, windowSum: 0, windowPeak: 0, windowCount: 0, halo: 0,
source: null, analyser: null, samples: null,
};
recorder.addEventListener('dataavailable', (event) => {
if (event.data?.size > 0) current.chunks.push(event.data);
});
recorder.addEventListener('error', (event) => {
if (rec === current) onError({ kind: 'recorder', error: event?.error });
});
rec = current;
connectAnalyser(current);
recorder.start(1000);
current.segmentStartedAt = now();
lastClock = '';
paintClock(0);
resetStrip();
return true;
} catch (error) {
if (destroyed || id !== session) return false;
discardRecording();
setState('idle');
onError({ kind: 'media', error });
return false;
}
}
async function begin({ locked }) {
if (destroyed || state !== 'idle') return;
hideTip();
if (!globalThis.MediaRecorder || !navigator.mediaDevices?.getUserMedia) {
onError({ kind: 'unsupported' });
return;
}
if (!canStart()) return;
released = false;
pressedAt = now();
const id = ++session;
ensureAudioContext();
setState('starting');
if (!(await openMicrophone(id))) return;
if (!locked && released) {
// Палец отпустили раньше, чем открылся микрофон (быстрый тап или окно разрешения).
discardRecording();
setState('idle');
showTip();
return;
}
setState(locked ? 'locked' : 'holding');
vibrate(10);
startLoop();
}
function stopRecorder(current) {
return new Promise((resolve) => {
const { recorder, chunks } = current;
const done = () => resolve(new Blob(chunks, { type: recorder.mimeType || current.mimeType || chunks[0]?.type || 'audio/webm' }));
if (recorder.state === 'inactive') {
done();
return;
}
recorder.addEventListener('stop', done, { once: true });
try {
recorder.stop();
} catch {
done();
}
});
}
async function finish() {
if (!rec || !LIVE_STATES.has(state)) return;
const current = rec;
const durationMs = Math.round(elapsedMs());
const waveform = current.levels.length ? encodeWaveform(compressLevels(current.levels)) : '';
stopLoop();
setState('busy');
const blob = await stopRecorder(current);
releaseMedia(current);
if (rec === current) rec = null;
if (destroyed) return;
if (!blob.size) {
setState('idle');
return;
}
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const file = new File([blob], `voice-${stamp}.${extensionFor(blob.type)}`, { type: blob.type, lastModified: Date.now() });
try {
await onRecorded({ file, durationMs, waveform });
} catch (error) {
if (!destroyed) onError({ kind: 'send', error });
} finally {
if (!destroyed) setState('idle');
}
}
function lockRecording() {
if (state !== 'holding') return;
setState('locked');
vibrate(15);
}
function togglePause() {
if (!rec || !canPause()) return;
if (state === 'locked' && rec.recorder.state === 'recording') {
rec.recorder.pause();
rec.activeMs += now() - rec.segmentStartedAt;
rec.segmentStartedAt = 0;
stopLoop();
setState('paused');
} else if (state === 'paused' && rec.recorder.state === 'paused') {
rec.recorder.resume();
rec.segmentStartedAt = now();
setState('locked');
startLoop();
}
}
function stopEffect() {
if (!effect) return;
effect.animations.forEach((animation) => animation.cancel());
effect.dust.forEach((node) => node.remove());
effect = null;
}
// Удаление записи: крышка корзины откидывается, полоса волны растворяется справа налево
// в облако пыльцы — большая часть пылинок разлетается вверх и вбок и гаснет, часть
// втягивается в корзину; крышка захлопывается, корзина вздрагивает и исчезает.
function playTrashEffect() {
if (prefersReducedMotion() || typeof panel.animate !== 'function') return Promise.resolve();
const lid = deleteBtn.querySelector('.dm-voice-trash__lid');
const panelRect = panel.getBoundingClientRect();
const waveRect = waveEl.getBoundingClientRect();
const trashRect = deleteBtn.getBoundingClientRect();
const targetX = trashRect.left + trashRect.width / 2 - panelRect.left;
const targetY = trashRect.top + trashRect.height / 2 - panelRect.top;
// Пыльца рождается только из видимых столбиков: у громких мест облако гуще.
const bars = [...stripEl.children]
.map((bar) => bar.getBoundingClientRect())
.filter((rect) => rect.right > waveRect.left && rect.left < waveRect.right);
const current = { animations: [], dust: [] };
effect = current;
const run = (node, keyframes, options) => {
if (!node) return;
current.animations.push(node.animate(keyframes, { fill: 'forwards', ...options }));
};
run(deleteBtn, [
{ transform: 'scale(.6)', opacity: 0 },
{ transform: 'scale(1)', opacity: 1, offset: 0.14 },
{ transform: 'scale(1) rotate(0deg)', offset: 0.8 },
{ transform: 'scale(1) rotate(-10deg)', offset: 0.85 },
{ transform: 'scale(1) rotate(8deg)', offset: 0.9 },
{ transform: 'scale(1) rotate(0deg)', opacity: 1, offset: 0.94 },
{ transform: 'scale(.7) translateY(6px)', opacity: 0 },
], { duration: TRASH_MS, easing: 'ease-out' });
run(lid, [
{ transform: 'rotate(0deg)' },
{ transform: 'rotate(-38deg)', offset: 0.16 },
{ transform: 'rotate(-38deg)', offset: 0.74 },
{ transform: 'rotate(0deg)', offset: 0.82 },
{ transform: 'rotate(0deg)' },
], { duration: TRASH_MS, easing: 'ease-in-out' });
run(dotEl, [{ opacity: 1 }, { opacity: 0 }], { duration: 160 });
run(timeEl, [{ opacity: 1 }, { opacity: 0 }], { duration: 240 });
// Фронт растворения идёт справа налево с постоянной скоростью — пылинки рождаются ровно на нём.
run(waveEl, [{ clipPath: 'inset(0 0 0 0)' }, { clipPath: 'inset(0 100% 0 0)' }], {
duration: DISSOLVE_MS, delay: DISSOLVE_DELAY_MS, easing: 'linear',
});
for (let i = 0; i < DUST_COUNT && bars.length; i += 1) {
const rect = bars[Math.floor(Math.random() * bars.length)];
const x = rect.left + rect.width * Math.random() - panelRect.left;
const y = rect.top + rect.height * Math.random() - panelRect.top;
const front = (x + panelRect.left - waveRect.left) / Math.max(1, waveRect.width);
const delay = DISSOLVE_DELAY_MS + (1 - Math.min(1, Math.max(0, front))) * DISSOLVE_MS;
const dust = document.createElement('span');
dust.className = Math.random() < 0.35 ? 'dm-voice-dust is-light' : 'dm-voice-dust';
dust.style.left = `${x}px`;
dust.style.top = `${y}px`;
const size = 1.4 + Math.random() * 1.8;
dust.style.width = `${size}px`;
dust.style.height = `${size}px`;
panel.append(dust);
current.dust.push(dust);
if (Math.random() < DUST_TO_TRASH) {
run(dust, [
{ transform: 'translate(0, 0) scale(1)', opacity: 0 },
{ opacity: 1, offset: 0.12 },
{ transform: `translate(${targetX - x}px, ${targetY - y}px) scale(.3)`, opacity: 0.2 },
], { duration: 420 + Math.random() * 160, delay, easing: 'cubic-bezier(.55, .05, .7, .2)' });
} else {
// Облако: небольшой разброс, дрейф вверх и слегка в сторону корзины, плавное затухание.
const dx = -16 + Math.random() * 24;
const dy = -(6 + Math.random() * 18);
run(dust, [
{ transform: 'translate(0, 0) scale(1)', opacity: 0 },
{ transform: `translate(${(dx * 0.3).toFixed(1)}px, ${(dy * 0.3).toFixed(1)}px) scale(1)`, opacity: 1, offset: 0.2 },
{ transform: `translate(${dx.toFixed(1)}px, ${dy.toFixed(1)}px) scale(.4)`, opacity: 0 },
], { duration: 450 + Math.random() * 150, delay, easing: 'cubic-bezier(.2, .6, .4, 1)' });
}
}
return Promise.allSettled(current.animations.map((animation) => animation.finished)).then(() => {
if (effect === current) stopEffect();
});
}
async function cancel() {
if (!LIVE_STATES.has(state)) return;
session += 1;
pointerId = null;
discardRecording();
setState('cancelling');
vibrate([12, 40, 12]);
await playTrashEffect();
if (!destroyed && state === 'cancelling') setState('idle');
}
function showTip() {
window.clearTimeout(tipTimer);
// Содержимое ставится заново на каждый показ, чтобы экранный диктор озвучил подсказку.
tip.innerHTML = `${LOCK_SVG}<span class="dm-voice-tip__text"><strong>${th('screens.chat_view.voice.hold_tip')}</strong><span>${th('screens.chat_view.voice.lock_tip')}</span></span>`;
tip.classList.add('is-visible');
tipTimer = window.setTimeout(hideTip, TIP_MS);
}
function hideTip() {
window.clearTimeout(tipTimer);
tip.classList.remove('is-visible');
}
function cancelDistance() {
return Math.min(CANCEL_MAX, Math.max(CANCEL_MIN, bar.clientWidth * CANCEL_RATIO));
}
deleteBtn.addEventListener('click', () => { void cancel(); });
pauseBtn.addEventListener('click', togglePause);
return {
get state() { return state; },
isRecording: () => PANEL_STATES.has(state),
/** Нажатие на микрофон указателем (палец, мышь, перо). */
press(event) {
pointerId = event.pointerId ?? null;
startX = Number(event.clientX || 0);
startY = Number(event.clientY || 0);
void begin({ locked: false });
},
move(event) {
if (state !== 'holding' || event.pointerId !== pointerId) return;
const dx = Math.max(0, startX - Number(event.clientX || 0));
const dy = Math.max(0, startY - Number(event.clientY || 0));
const cancelAt = cancelDistance();
panel.style.setProperty('--slide', Math.min(1, dx / cancelAt).toFixed(3));
lock.style.setProperty('--lift', Math.min(1, dy / LOCK_DISTANCE).toFixed(3));
if (dx >= cancelAt) void cancel();
else if (dy >= LOCK_DISTANCE) lockRecording();
},
release(event) {
if (pointerId == null || event.pointerId !== pointerId) return;
pointerId = null;
released = true;
if (state !== 'holding') return;
if (now() - pressedAt < TAP_MS) {
discardRecording();
setState('idle');
showTip();
return;
}
void finish();
},
/** Система забрала жест (звонок, системная панель): запись не теряем и не отправляем сами. */
interrupt(event) {
if (pointerId == null || event.pointerId !== pointerId) return;
pointerId = null;
released = true;
if (state === 'holding') lockRecording();
},
/** С клавиатуры удерживать нечего: запись сразу начинается в режиме замка. */
startLocked() {
pointerId = null;
void begin({ locked: true });
},
send() {
void finish();
},
destroy() {
if (destroyed) return;
destroyed = true;
session += 1;
discardRecording();
stopEffect();
window.clearTimeout(tipTimer);
window.clearTimeout(snapTimer);
window.clearTimeout(returnTimer);
syncEscListener();
try { void audioCtx?.close?.(); } catch { /* уже закрыт */ }
audioCtx = null;
state = 'idle';
markRecorderActive(owner, false);
},
};
}
+174
View File
@@ -0,0 +1,174 @@
// Волна голосового сообщения: 64 уровня громкости 0..31.
// В тех-блоке `<S:file;...;kind=voice;wf=...>` уровни упакованы по 5 бит в base64url,
// поэтому получатель рисует волну сразу, не скачивая и не расшифровывая файл.
// Поле приходит от собеседника внутри расшифрованного текста — это недоверенный ввод:
// decodeWaveform() принимает только короткую base64url-строку и иначе возвращает null.
export const WAVEFORM_POINTS = 64;
export const WAVEFORM_MAX_LEVEL = 31;
const BITS = 5;
const ENCODED_BYTES = Math.ceil((WAVEFORM_POINTS * BITS) / 8);
const WF_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
// Ниже этого RMS запись считается тишиной: шум микрофона не растягиваем до полной высоты.
const SILENCE_LEVEL = 0.002;
// Сжатие динамики: тихие слоги остаются видимыми рядом с громкими.
const CURVE = 0.75;
const FALLBACK_CACHE_LIMIT = 200;
function cleanLevel(value) {
const n = Number(value);
return Number.isFinite(n) && n > 0 ? n : 0;
}
/** Максимум по отрезку [from, to) — пики громкости при сжатии не теряются. */
function peakInRange(values, from, to, read) {
let peak = 0;
for (let i = from; i < to; i += 1) peak = Math.max(peak, read(values[i]));
return peak;
}
function spread(length, count, index) {
const from = Math.floor((index * length) / count);
const to = Math.max(from + 1, Math.floor(((index + 1) * length) / count));
return [Math.min(from, length - 1), Math.min(to, length)];
}
/** Уровни громкости (RMS 0..1, любой длины) → `points` значений 0..31. */
export function compressLevels(levels, points = WAVEFORM_POINTS) {
const clean = Array.from(levels ?? [], cleanLevel);
const out = new Uint8Array(points);
if (!clean.length) return out;
const buckets = Array.from({ length: points }, (_, i) => {
const [from, to] = spread(clean.length, points, i);
return peakInRange(clean, from, to, (v) => v);
});
const peak = Math.max(...buckets);
if (peak < SILENCE_LEVEL) return out;
buckets.forEach((value, i) => {
out[i] = Math.round(WAVEFORM_MAX_LEVEL * (value / peak) ** CURVE);
});
return out;
}
function toBase64Url(bytes) {
let binary = '';
bytes.forEach((byte) => { binary += String.fromCharCode(byte); });
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function fromBase64Url(text) {
const base64 = text.replace(/-/g, '+').replace(/_/g, '/');
const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, '='));
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
}
/** Ровно 64 значения (лишнее отбрасывается, недостающее = 0) → 54 символа base64url. */
export function encodeWaveform(values) {
const bytes = new Uint8Array(ENCODED_BYTES);
for (let i = 0; i < WAVEFORM_POINTS; i += 1) {
const raw = Number(values?.[i]);
const value = Number.isFinite(raw) ? Math.min(WAVEFORM_MAX_LEVEL, Math.max(0, Math.round(raw))) : 0;
for (let bit = BITS - 1; bit >= 0; bit -= 1) {
const position = i * BITS + (BITS - 1 - bit);
if ((value >> bit) & 1) bytes[position >> 3] |= 0x80 >> (position & 7);
}
}
return toBase64Url(bytes);
}
/** Строка из поля `wf` → значения 0..31 или null, если это не наша упаковка. */
export function decodeWaveform(text) {
if (typeof text !== 'string' || !WF_PATTERN.test(text)) return null;
let bytes;
try {
bytes = fromBase64Url(text);
} catch {
return null;
}
const count = Math.floor((bytes.length * 8) / BITS);
if (!count) return null;
const out = new Uint8Array(count);
for (let i = 0; i < count; i += 1) {
let value = 0;
for (let bit = 0; bit < BITS; bit += 1) {
const position = i * BITS + bit;
value = (value << 1) | ((bytes[position >> 3] >> (7 - (position & 7))) & 1);
}
out[i] = value;
}
return out;
}
/** Значения 0..31 → `count` высот столбиков 0..1 (сжатие по максимуму, растяжение по ближайшему). */
export function resampleWaveform(values, count) {
const length = values?.length || 0;
if (!length) return new Array(count).fill(0);
const read = (v) => Math.min(1, cleanLevel(v) / WAVEFORM_MAX_LEVEL);
return Array.from({ length: count }, (_, i) => {
const [from, to] = spread(length, count, i);
return peakInRange(values, from, to, read);
});
}
/** Среднеквадратичная громкость отрезка сигнала (-1..1). */
export function rmsLevel(samples) {
const length = samples?.length || 0;
if (!length) return 0;
let sum = 0;
for (let i = 0; i < length; i += 1) sum += samples[i] * samples[i];
return Math.sqrt(sum / length);
}
/** Волна по готовому звуку — для старых голосовых, отправленных без `wf`. */
export function waveformFromChannelData(data, points = WAVEFORM_POINTS) {
const length = data?.length || 0;
if (!length) return new Uint8Array(points);
const blocks = Math.min(length, points * 4);
const levels = Array.from({ length: blocks }, (_, i) => {
const [from, to] = spread(length, blocks, i);
return rmsLevel(data.subarray(from, to));
});
return compressLevels(levels, points);
}
export async function computeWaveformFromBlob(blob) {
const Offline = globalThis.OfflineAudioContext || globalThis.webkitOfflineAudioContext;
if (!Offline || !blob) return null;
const context = new Offline(1, 1, 44_100);
const buffer = await context.decodeAudioData(await blob.arrayBuffer());
return waveformFromChannelData(buffer.getChannelData(0));
}
// Волны старых голосовых живут до перезагрузки страницы: при перерисовке ленты
// столбики не возвращаются к заглушке и файл не декодируется повторно.
const computedWaveforms = new Map();
export function computedWaveformFor(id) {
return computedWaveforms.get(String(id || '')) || null;
}
export function rememberComputedWaveform(id, values) {
const key = String(id || '');
if (!key || !values) return;
computedWaveforms.delete(key);
computedWaveforms.set(key, values);
if (computedWaveforms.size > FALLBACK_CACHE_LIMIT) {
computedWaveforms.delete(computedWaveforms.keys().next().value);
}
}
/** Столбики в контейнере: `--level` 0..1 задаёт высоту, геометрия — в dm-voice.css. */
export function fillWaveformBars(container, levels) {
if (!container) return;
while (container.children.length < levels.length) {
const bar = document.createElement('span');
bar.className = 'dm-voice-wave__bar';
container.append(bar);
}
while (container.children.length > levels.length) container.lastElementChild.remove();
levels.forEach((level, i) => {
container.children[i].style.setProperty('--level', level.toFixed(3));
});
}
@@ -0,0 +1,335 @@
import { formatStarAmount } from '../services/shine-support-amount.js';
// Одноразовое «сияние» карточки «Поддержка» (после раскрытия и при тапе по ней):
// — «пополнение»: в каждой ненулевой строке комета цвета метрики летит дугой от иконки к сумме, оставляя
// светящийся хвост и пылинки; при попадании сумма вспыхивает искрами и досчитывается от нуля;
// — золотой блик обходит рамку по контуру и гаснет вспышкой-звёздочкой в правом верхнем углу;
// — пунктирная орбита с золотыми точками вокруг карточки.
// Всё декоративное (aria-hidden), каждый слой удаляет себя по окончании своей анимации, а единый цикл rAF
// останавливается, как только страница закрыта, — таймеров, переживающих страницу, нет.
const COMET_START_MS = 150;
const COMET_STAGGER_MS = 260;
const COMET_FLIGHT_MS = 650;
// Доля пути, которую занимает хвост кометы; после попадания хвост «втягивается» в сумму.
const COMET_TRAIL = 0.5;
const MOTE_EVERY_MS = 30;
const COUNT_MS = 700;
const ORBIT_MS = 2400;
const ORBIT_GAP = 6;
// Поле SVG орбиты вокруг карточки: эффекты не выходят за край дальше 10px (иначе на 320px появится горизонтальная прокрутка).
const ORBIT_PAD = 10;
const ORBIT_DOTS = 7;
const SPARKS = 8;
const SVG_NS = 'http://www.w3.org/2000/svg';
const runs = new WeakMap();
let fxSeq = 0;
export function prefersReducedMotion() {
return Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)').matches);
}
const easeOutCubic = (p) => 1 - (1 - p) ** 3;
const easeInOutCubic = (p) => (p < 0.5 ? 4 * p ** 3 : 1 - (-2 * p + 2) ** 3 / 2);
function removeAfterOwnAnimation(el) {
// animationend всплывает от дочерних слоёв — удаляем только по окончании анимации самого элемента.
const done = (event) => { if (event.target === el) el.remove(); };
el.addEventListener('animationend', done);
el.addEventListener('animationcancel', done);
}
// offsetLeft/offsetTop не зависят от transform: замеры верны, даже когда карточка вдавлена (scale .97).
function offsetWithin(el, ancestor) {
let x = 0;
let y = 0;
for (let node = el; node && node !== ancestor; node = node.offsetParent) {
x += node.offsetLeft;
y += node.offsetTop;
}
return { x, y };
}
function svgEl(name, attrs = {}) {
const el = document.createElementNS(SVG_NS, name);
for (const [key, value] of Object.entries(attrs)) el.setAttribute(key, String(value));
return el;
}
function overlaySvg(card, className, width = card.offsetWidth, height = card.offsetHeight) {
const svg = svgEl('svg', { width, height, viewBox: `0 0 ${width} ${height}`, 'aria-hidden': 'true', focusable: 'false' });
svg.setAttribute('class', `profile-support-fx ${className}`);
const defs = svgEl('defs');
svg.append(defs);
return { svg, defs, width, height };
}
// Свечение — SVG-фильтр, а не CSS filter: на вложенных элементах SVG CSS-фильтры поддерживаются не везде.
// Область фильтра задана в координатах холста: у тонкой линии рамка объекта почти нулевой высоты.
// layers — сколько раз наложить ореол: два слоя дают яркий «неоновый» росчерк.
function glowFilter(defs, width, height, deviation, layers = 1) {
const id = `profile-support-glow-${fxSeq += 1}`;
const filter = svgEl('filter', { id, filterUnits: 'userSpaceOnUse', x: 0, y: 0, width, height });
filter.append(svgEl('feGaussianBlur', { in: 'SourceGraphic', stdDeviation: deviation, result: 'blur' }));
const merge = svgEl('feMerge');
for (let i = 0; i < layers; i += 1) merge.append(svgEl('feMergeNode', { in: 'blur' }));
merge.append(svgEl('feMergeNode', { in: 'SourceGraphic' }));
filter.append(merge);
defs.append(filter);
return `url(#${id})`;
}
// Скруглённый прямоугольник по часовой стрелке от правого верхнего угла: блик, пройдя круг, гаснет в этом углу.
function roundedRectPath(x, y, w, h, r) {
const rr = Math.max(0, Math.min(r, w / 2, h / 2));
return `M ${x + w - rr} ${y} A ${rr} ${rr} 0 0 1 ${x + w} ${y + rr} V ${y + h - rr}`
+ ` A ${rr} ${rr} 0 0 1 ${x + w - rr} ${y + h} H ${x + rr} A ${rr} ${rr} 0 0 1 ${x} ${y + h - rr}`
+ ` V ${y + rr} A ${rr} ${rr} 0 0 1 ${x + rr} ${y} Z`;
}
// Четырёхлучевая звёздочка-вспышка с вогнутыми гранями.
function sparklePath(cx, cy, s) {
return `M ${cx} ${cy - s} Q ${cx} ${cy} ${cx + s} ${cy} Q ${cx} ${cy} ${cx} ${cy + s}`
+ ` Q ${cx} ${cy} ${cx - s} ${cy} Q ${cx} ${cy} ${cx} ${cy - s} Z`;
}
function cardRadius(card) {
return parseFloat(getComputedStyle(card).borderTopLeftRadius) || 20;
}
function rimGlint(card) {
const { svg, defs, width, height } = overlaySvg(card, 'profile-support-fx__rim');
const glow = glowFilter(defs, width, height, 2);
const r = cardRadius(card);
// Линия ложится ровно на грань: середина штриха — в 0.75px от края.
const d = roundedRectPath(0.75, 0.75, width - 1.5, height - 1.5, r - 0.75);
const tint = svgEl('path', { d });
tint.setAttribute('class', 'profile-support-fx__rim-tint');
const glint = svgEl('path', { d, pathLength: 1, filter: glow });
glint.setAttribute('class', 'profile-support-fx__rim-glint');
// Середина дуги правого верхнего угла: r·(1 − cos 45°) от каждого края. Вспышке — своё, более яркое свечение.
const corner = r * 0.29;
const flare = svgEl('path', { d: sparklePath(width - corner, corner, 11), filter: glowFilter(defs, width, height, 2.5, 2) });
flare.setAttribute('class', 'profile-support-fx__flare');
svg.append(tint, glint, flare);
removeAfterOwnAnimation(svg);
card.append(svg);
}
function orbit(card) {
const { svg, width, height } = overlaySvg(card, 'profile-support-fx__orbit', card.offsetWidth + ORBIT_PAD * 2, card.offsetHeight + ORBIT_PAD * 2);
svg.style.left = `${-ORBIT_PAD}px`;
svg.style.top = `${-ORBIT_PAD}px`;
const inset = ORBIT_PAD - ORBIT_GAP;
const ring = svgEl('path', { d: roundedRectPath(inset, inset, width - inset * 2, height - inset * 2, cardRadius(card) + ORBIT_GAP) });
ring.setAttribute('class', 'profile-support-fx__ring');
svg.append(ring);
const dots = [];
for (let i = 0; i < ORBIT_DOTS; i += 1) {
const el = svgEl('circle', { r: (1.2 + (i % 3) * 0.5).toFixed(1), opacity: 0 });
el.setAttribute('class', 'profile-support-fx__dot');
svg.append(el);
dots.push({ el, start: (i + Math.random() * 0.6) / ORBIT_DOTS, travel: 0.2 + Math.random() * 0.12, peak: 0.55 + Math.random() * 0.45 });
}
removeAfterOwnAnimation(svg);
card.append(svg);
// Длина пути доступна только у вставленного в документ SVG.
return { svg, ring, dots, length: ring.getTotalLength() };
}
function moveOrbitDots(fx, elapsed) {
const p = Math.min(1, elapsed / ORBIT_MS);
const envelope = Math.sin(Math.PI * p);
for (const dot of fx.dots) {
const point = fx.ring.getPointAtLength(((dot.start + dot.travel * easeOutCubic(p)) % 1) * fx.length);
dot.el.setAttribute('cx', point.x.toFixed(1));
dot.el.setAttribute('cy', point.y.toFixed(1));
dot.el.setAttribute('opacity', (envelope * dot.peak).toFixed(2));
}
return p < 1;
}
function sparkBurst(amount) {
const burst = document.createElement('span');
burst.className = 'profile-support-sparks';
burst.setAttribute('aria-hidden', 'true');
for (let i = 0; i < SPARKS; i += 1) {
const spark = document.createElement('span');
spark.className = 'profile-support-spark';
spark.style.setProperty('--a', `${Math.round(i * (360 / SPARKS) + Math.random() * 24 - 12)}deg`);
spark.style.setProperty('--d', `${14 + Math.round(Math.random() * 8)}px`);
burst.append(spark);
}
// Все искры одной длительности — достаточно дождаться первой.
const removeBurst = () => burst.remove();
burst.firstChild.addEventListener('animationend', removeBurst, { once: true });
burst.firstChild.addEventListener('animationcancel', removeBurst, { once: true });
amount.append(burst);
}
function spawnMote(card, point, tone) {
const mote = document.createElement('span');
mote.className = 'profile-support-fx profile-support-fx__mote';
mote.setAttribute('aria-hidden', 'true');
mote.style.left = `${(point.x + Math.random() * 8 - 4).toFixed(1)}px`;
mote.style.top = `${(point.y + Math.random() * 8 - 4).toFixed(1)}px`;
mote.style.setProperty('--ps-tone', tone);
mote.style.setProperty('--mx', `${Math.round(Math.random() * 10 - 5)}px`);
mote.style.setProperty('--my', `${Math.round(Math.random() * 10 - 8)}px`);
removeAfterOwnAnimation(mote);
card.append(mote);
}
// Хвост — штрих длиной COMET_TRAIL на пути длины 1, голова — светящаяся точка в HTML (у неё мягкая box-shadow).
// Градиент вдоль полёта гасит хвост к началу, поэтому свет «стекает» к сумме.
function prepareComets(card, counters) {
const { svg, defs, width, height } = overlaySvg(card, 'profile-support-fx__comets');
const glow = glowFilter(defs, width, height, 2.4, 2);
const comets = [];
for (const counter of counters) {
if (counter.cents === 0n) continue;
const icon = counter.row.querySelector('.profile-support-stat__icon');
if (!icon) continue;
const a = offsetWithin(icon, card);
const b = offsetWithin(counter.amount, card);
const x0 = a.x + icon.offsetWidth + 4;
const y0 = a.y + icon.offsetHeight / 2;
const x1 = b.x - 4;
const y1 = b.y + counter.amount.offsetHeight / 2;
const dx = x1 - x0;
const tone = getComputedStyle(icon).color;
const id = `profile-support-comet-${fxSeq += 1}`;
const gradient = svgEl('linearGradient', { id, gradientUnits: 'userSpaceOnUse', x1: x0, y1: y0, x2: x1, y2: y1 });
[[0, 0], [0.4, 0.55], [1, 1]].forEach(([offset, opacity]) => {
const stop = svgEl('stop', { offset });
stop.style.stopColor = tone;
stop.style.stopOpacity = String(opacity);
gradient.append(stop);
});
defs.append(gradient);
// Дуга ныряет под строку и поднимается в сумму — как росчерк на референсе.
const trail = svgEl('path', {
d: `M ${x0} ${y0} C ${x0 + dx * 0.35} ${y0 + 24}, ${x1 - dx * 0.3} ${y1 + 20}, ${x1} ${y1}`,
pathLength: 1,
stroke: `url(#${id})`,
filter: glow,
});
trail.setAttribute('class', 'profile-support-fx__trail');
trail.style.strokeDasharray = `${COMET_TRAIL} 3`;
trail.style.strokeDashoffset = String(COMET_TRAIL);
svg.append(trail);
const head = document.createElement('span');
head.className = 'profile-support-fx profile-support-fx__comet';
head.setAttribute('aria-hidden', 'true');
head.style.setProperty('--ps-tone', tone);
head.style.opacity = '0';
card.append(head);
comets.push({ counter, trail, head, tone, start: COMET_START_MS + comets.length * COMET_STAGGER_MS, length: 0, lastMote: -Infinity, done: false });
}
// Срок жизни слоя задаёт его CSS-анимация (дольше полёта последней кометы).
removeAfterOwnAnimation(svg);
card.append(svg);
for (const comet of comets) comet.length = comet.trail.getTotalLength();
return { svg, comets };
}
function moveComet(card, comet, elapsed, startCount) {
const p = (elapsed - comet.start) / COMET_FLIGHT_MS;
if (p < 0) return true;
const reach = easeInOutCubic(Math.min(1, p)) * (1 + COMET_TRAIL);
comet.trail.style.strokeDashoffset = (COMET_TRAIL - reach).toFixed(4);
if (reach < 1) {
const point = comet.trail.getPointAtLength(reach * comet.length);
comet.head.style.opacity = '1';
comet.head.style.transform = `translate(${point.x.toFixed(1)}px, ${point.y.toFixed(1)}px)`;
if (elapsed - comet.lastMote >= MOTE_EVERY_MS) {
comet.lastMote = elapsed;
spawnMote(card, comet.trail.getPointAtLength(Math.max(0, reach - 0.06) * comet.length), comet.tone);
}
} else if (comet.head.isConnected) {
// Попадание: голова растворяется в сумме, сумма вспыхивает и начинает досчитываться.
comet.head.remove();
startCount(comet.counter, elapsed);
}
if (p >= 1) comet.done = true;
return !comet.done;
}
/**
* Проигрывает сияние на карточке; повторный вызов прерывает предыдущий. Возвращает stop():
* суммы сразу становятся итоговыми, декоративные слои убираются. При reduced-motion ничего не делает.
*/
export function playSupportShine(card, { isActive = () => true } = {}) {
runs.get(card)?.();
if (prefersReducedMotion() || !card.isConnected) return () => {};
const alive = () => isActive() && card.isConnected;
const counters = [...card.querySelectorAll('.profile-support-stat')].map((row) => {
const value = row.querySelector('.profile-support-amount__value[data-cents]');
return value && { row, value, amount: value.parentElement, cents: BigInt(value.dataset.cents), countFrom: null, done: false };
}).filter(Boolean);
rimGlint(card);
const orbitFx = orbit(card);
const { comets } = prepareComets(card, counters);
for (const counter of counters) {
if (counter.cents === 0n) counter.done = true;
else counter.value.textContent = formatStarAmount(0n);
}
const startCount = (counter, elapsed) => {
counter.countFrom = elapsed;
counter.amount.classList.add('is-filling');
sparkBurst(counter.amount);
};
// Сумма без кометы (не нашлась иконка строки) досчитывается сразу — иначе зависла бы на нуле.
const withComet = new Set(comets.map((comet) => comet.counter));
for (const counter of counters) {
if (!counter.done && !withComet.has(counter)) startCount(counter, 0);
}
let frame = 0;
let finished = false;
// Видимое число — aria-hidden; итог всегда восстанавливается точным BigInt, без потерь округления.
const finish = () => {
if (finished) return;
finished = true;
cancelAnimationFrame(frame);
for (const counter of counters) {
counter.value.textContent = formatStarAmount(counter.cents);
counter.amount.classList.remove('is-filling');
}
if (runs.get(card) === stop) runs.delete(card);
};
function stop() {
finish();
card.querySelectorAll('.profile-support-fx, .profile-support-sparks').forEach((el) => el.remove());
}
const startedAt = performance.now();
const tick = (now) => {
if (!alive()) { finish(); return; }
const elapsed = now - startedAt;
let pending = false;
for (const comet of comets) {
if (!comet.done && moveComet(card, comet, elapsed, startCount)) pending = true;
}
for (const counter of counters) {
if (counter.done) continue;
pending = true;
if (counter.countFrom === null) continue;
const q = Math.min(1, (elapsed - counter.countFrom) / COUNT_MS);
if (q < 1) {
counter.value.textContent = formatStarAmount(BigInt(Math.round(Number(counter.cents) * easeOutCubic(q))));
} else {
counter.done = true;
counter.value.textContent = formatStarAmount(counter.cents);
// Цвет и свечение суммы плавно гаснут (переход в CSS).
counter.amount.classList.remove('is-filling');
}
}
if (orbitFx.svg.isConnected && moveOrbitDots(orbitFx, elapsed)) pending = true;
if (pending) frame = requestAnimationFrame(tick);
else finish();
};
frame = requestAnimationFrame(tick);
runs.set(card, stop);
return stop;
}
+260 -31
View File
@@ -1,7 +1,20 @@
import { t } from '../i18n/index.js';
import { formatDateTime } from '../i18n/format.js';
import { authService } from '../state.js';
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
import { formatStars } from '../services/shine-support-amount.js';
import { formatStarAmount, formatStars } from '../services/shine-support-amount.js';
import { iconHtml } from './ui-icon.js';
import { playSupportShine, prefersReducedMotion } from './support-shine-effects.js';
const GOO_FILTER_ID = 'profile-support-goo';
// Порядок совпадает с supportStatsValues(). tone — класс цвета метрики (CSS задаёт --ps-tone);
// подписи берутся при отрисовке: словари грузятся асинхронно и язык можно сменить.
const METRICS = [
{ tone: 'is-sent', icon: 'heart', key: 'sent' },
{ tone: 'is-received', icon: 'trend-up', key: 'received' },
{ tone: 'is-shine', icon: 'sparkle', key: 'shine' },
];
let panelSeq = 0;
export function supportStatsValues(stats = {}) {
const sent = BigInt(stats.supportSent ?? 0);
@@ -10,27 +23,211 @@ export function supportStatsValues(stats = {}) {
return [sent, received, daoDirect];
}
/** Adds an independent asynchronous block; failure/Free accounts do not get fictitious statistics. */
// Фильтр «жидкого света» один на документ (тот же приём, что fg-shine-glow у прежних «Связей»):
// размытие + порог альфы сливают капли света в одну вязкую форму. Применяется только к слою
// света под текстом кнопки — на всю кнопку его вешать нельзя, порог «съест» тонкие буквы.
function ensureGooFilter() {
if (typeof document === 'undefined' || document.getElementById(GOO_FILTER_ID)) return;
const holder = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
holder.setAttribute('width', '0');
holder.setAttribute('height', '0');
holder.setAttribute('aria-hidden', 'true');
holder.setAttribute('focusable', 'false');
holder.style.position = 'absolute';
holder.innerHTML = `<defs><filter id="${GOO_FILTER_ID}" x="-20%" y="-60%" width="140%" height="220%" color-interpolation-filters="sRGB">`
+ '<feGaussianBlur in="SourceGraphic" stdDeviation="5" result="blur"/>'
+ '<feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 18 -7" result="goo"/>'
+ '<feComposite in="SourceGraphic" in2="goo" operator="atop"/>'
+ '</filter></defs>';
document.body.append(holder);
}
// Видимо — только число и SVG-звезда; скринридер получает прежнюю полную запись «0.10 ⭐».
// data-cents — точная сумма для счёта от нуля (support-shine-effects.js).
function renderAmount(cents, sign = '') {
const wrap = document.createElement('span');
wrap.className = 'profile-support-amount';
const value = document.createElement('span');
value.className = 'profile-support-amount__value';
value.setAttribute('aria-hidden', 'true');
value.dataset.cents = String(cents);
value.textContent = `${sign}${formatStarAmount(cents)}`;
const spoken = document.createElement('span');
spoken.className = 'sr-only';
spoken.textContent = `${sign}${formatStars(cents)}`;
wrap.append(value);
wrap.insertAdjacentHTML('beforeend', iconHtml('star', true, 'profile-support-amount__star'));
wrap.append(spoken);
return wrap;
}
function renderChip({ tone, icon }, cents) {
const chip = document.createElement('span');
chip.className = cents === 0n ? `profile-support-chip ${tone} is-zero` : `profile-support-chip ${tone}`;
chip.innerHTML = iconHtml(icon, false, 'profile-support-chip__icon');
const value = document.createElement('span');
value.textContent = formatStarAmount(cents);
chip.append(value);
chip.insertAdjacentHTML('beforeend', iconHtml('star', true, 'profile-support-chip__star'));
return chip;
}
// Капля света из точки касания + две капельки-спутника: фильтр сливает их в жидкую вспышку.
// Удаляется по окончании своей анимации — без таймеров, переживающих страницу.
function spawnLiquidLight(layer, event) {
if (prefersReducedMotion()) return;
const rect = layer.getBoundingClientRect();
const group = document.createElement('span');
group.className = 'profile-support-goo';
group.style.left = `${event.clientX - rect.left}px`;
group.style.top = `${event.clientY - rect.top}px`;
const main = document.createElement('span');
main.className = 'profile-support-goo__drop is-main';
const left = document.createElement('span');
left.className = 'profile-support-goo__drop is-left';
const right = document.createElement('span');
right.className = 'profile-support-goo__drop is-right';
group.append(main, left, right);
// animationcancel — на случай прерванной анимации (элемент скрыли/сменили), иначе капли остались бы в DOM.
const removeGroup = () => group.remove();
main.addEventListener('animationend', removeGroup, { once: true });
main.addEventListener('animationcancel', removeGroup, { once: true });
layer.append(group);
}
/**
* Adds an independent asynchronous block: a thin totals line that expands into the support card.
* Failure/Free accounts do not get fictitious statistics.
*/
export function attachSupportStats(parent, { login, isActive = () => true }) {
ensureGooFilter();
const panelId = `profile-support-panel-${panelSeq += 1}`;
const section = document.createElement('section');
section.className = 'card stack profile-support-stats';
section.style.cssText = 'margin-top:12px;gap:8px;';
const title = document.createElement('strong');
title.textContent = t('screens.support_phase2.statistics');
section.className = 'profile-support';
section.dataset.expanded = 'false';
// Свёрнутый блок-строка: ♡ сумма · ↗ сумма · ✦ сумма ⌄. Пока данных нет — неактивен и показывает статус.
const line = document.createElement('div');
line.className = 'profile-support__line';
const summary = document.createElement('button');
summary.type = 'button';
summary.className = 'profile-support__summary';
summary.disabled = true;
summary.setAttribute('aria-expanded', 'false');
summary.setAttribute('aria-controls', panelId);
summary.textContent = t('screens.support_phase2.loading');
line.append(summary);
// Раскрываемая карточка. inert, пока свёрнута: её кнопки не ловят фокус и не читаются скринридером.
const panel = document.createElement('div');
panel.className = 'profile-support__panel';
panel.id = panelId;
panel.inert = true;
const card = document.createElement('div');
card.className = 'profile-support-stats';
const title = document.createElement('button');
title.type = 'button';
title.className = 'profile-support-stats__title';
title.setAttribute('aria-expanded', 'true');
title.setAttribute('aria-controls', panelId);
const titleLabel = document.createElement('span');
titleLabel.textContent = t('screens.support_phase2.statistics');
title.append(titleLabel);
title.insertAdjacentHTML('beforeend', iconHtml('chevron-up', false, 'profile-support-stats__title-chevron'));
const content = document.createElement('div');
content.className = 'meta-muted';
content.textContent = t('screens.support_phase2.loading');
section.append(title, content);
content.className = 'profile-support-stats__content';
card.append(title, content);
const history = document.createElement('details');
history.className = 'profile-support-history';
const historySummary = document.createElement('summary');
historySummary.textContent = t('screens.support_phase2.history');
historySummary.className = 'profile-support-history__toggle';
const light = document.createElement('span');
light.className = 'profile-support-history__light';
light.setAttribute('aria-hidden', 'true');
const historyLabel = document.createElement('span');
historyLabel.className = 'profile-support-history__label';
historyLabel.textContent = t('screens.support_phase2.history');
historySummary.append(light, historyLabel);
historySummary.insertAdjacentHTML('beforeend', iconHtml('chevron', false, 'profile-support-history__chevron'));
// is-pressed дублирует :active: iOS Safari не включает :active без обработчика касаний.
const setPressed = (pressed) => historySummary.classList.toggle('is-pressed', pressed);
historySummary.addEventListener('pointerdown', (event) => {
if (event.button > 0) return;
setPressed(true);
spawnLiquidLight(light, event);
});
for (const type of ['pointerup', 'pointercancel', 'pointerleave']) {
historySummary.addEventListener(type, () => setPressed(false));
}
const historyRows = document.createElement('div');
historyRows.className = 'stack';
historyRows.style.cssText = 'gap:8px;margin-top:10px;';
historyRows.className = 'profile-support-history__rows';
history.append(historySummary, historyRows);
section.append(history);
card.append(history);
panel.append(card);
section.append(line, panel);
parent.append(section);
let expanded = false;
let toggleSeq = 0;
let stopShine = null;
const shine = () => {
stopShine = playSupportShine(card, { isActive });
};
// Карточка раскрывается вниз: если строка стоит у нижнего края экрана, без подкрутки карточка и её сияние
// оказались бы под панелью навигации. Пока идёт «выезд», каждый кадр держим карточку в видимой области.
const followReveal = (seq) => {
const step = () => {
if (seq !== toggleSeq || !expanded || !isActive() || !section.isConnected) return;
card.scrollIntoView({ block: 'nearest' });
if (!section.classList.contains('is-settled')) requestAnimationFrame(step);
};
requestAnimationFrame(step);
};
const setExpanded = (next) => {
if (next === expanded || !section.isConnected) return;
expanded = next;
const seq = toggleSeq += 1;
section.dataset.expanded = String(next);
section.classList.remove('is-settled');
summary.setAttribute('aria-expanded', String(next));
// Сначала снимаем inert, потом переводим фокус: в inert-поддерево фокус не попадает.
line.inert = next;
panel.inert = !next;
if (!next) {
stopShine?.();
stopShine = null;
card.classList.remove('is-pressed');
}
(next ? title : summary).focus({ preventScroll: true });
if (!next) return;
followReveal(seq);
// Пока карточка «выезжает», панель обрезает содержимое; орбита и искры выходят за край карточки,
// поэтому сияние запускается после окончания перехода. Нет перехода (reduced-motion) — сразу.
const transitions = section.getAnimations?.() ?? [];
Promise.all(transitions.map((animation) => animation.finished)).then(() => {
if (seq !== toggleSeq || !isActive() || !section.isConnected) return;
section.classList.add('is-settled');
card.scrollIntoView({ block: 'nearest' });
shine();
}, () => {});
};
summary.addEventListener('click', () => setExpanded(true));
title.addEventListener('click', () => setExpanded(false));
// Тап по карточке (кроме заголовка и истории): вдавливание .97, пружинный возврат и повтор сияния.
const isCardSurface = (target) => !target.closest('.profile-support-stats__title, .profile-support-history');
card.addEventListener('pointerdown', (event) => {
if (event.button > 0 || !isCardSurface(event.target)) return;
card.classList.add('is-pressed');
});
for (const type of ['pointerup', 'pointercancel', 'pointerleave']) {
card.addEventListener(type, () => card.classList.remove('is-pressed'));
}
card.addEventListener('click', (event) => {
if (expanded && section.classList.contains('is-settled') && isCardSurface(event.target)) shine();
});
let historyOffset = 0;
let loadingHistory = false;
let historyLoaded = false;
@@ -60,24 +257,24 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
const cents = transfer.kind === 'DAO' || outgoing
? transfer.amountStarCents : transfer.recipientStarCents;
const row = document.createElement('div');
row.className = 'row';
row.style.cssText = 'display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:6px;';
row.className = 'profile-support-transfer';
const info = document.createElement('span');
info.className = 'profile-support-transfer__peer';
info.textContent = transfer.kind === 'DAO'
? t('screens.support_phase2.history_dao')
: `${outgoing ? '→' : '←'} ${outgoing ? transfer.recipientLogin : transfer.senderLogin}`;
const value = document.createElement('strong');
value.textContent = `${outgoing ? '−' : '+'}${formatStars(cents)}`;
const value = renderAmount(cents, outgoing ? '−' : '+');
const detail = document.createElement('small');
detail.className = 'meta-muted';
const date = transfer.blockTime ? new Date(Number(transfer.blockTime) * 1000).toLocaleString() : '';
detail.className = 'profile-support-transfer__detail meta-muted';
const date = transfer.blockTime ? formatDateTime(Number(transfer.blockTime) * 1000) : '';
const lamports = BigInt(transfer.amountLamports || '0');
const sol = `${lamports / 1_000_000_000n}.${String(lamports % 1_000_000_000n).padStart(9, '0').replace(/0+$/, '') || '0'} SOL`;
detail.textContent = `${date} · ${sol}`;
detail.textContent = date ? `${date} · ${sol}` : sol;
const explorer = document.createElement('a');
const sig = String(transfer.signature || '');
if (/^[1-9A-HJ-NP-Za-km-z]{64,90}$/.test(sig)) {
const network = getSolanaCluster();
explorer.className = 'profile-support-transfer__link';
explorer.href = `https://explorer.solana.com/tx/${sig}${network && network !== 'mainnet-beta' ? `?cluster=${encodeURIComponent(network)}` : ''}`;
explorer.target = '_blank'; explorer.rel = 'noopener noreferrer';
explorer.textContent = t('screens.support_phase2.transaction');
@@ -100,7 +297,14 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
} finally { loadingHistory = false; }
};
history.addEventListener('toggle', () => {
if (history.open && !historyLoaded) void loadHistory();
if (!history.open) return;
// Записи истории тоже появляются ниже — подтягиваем их в видимую область, когда они на месте.
const reveal = () => {
if (!history.open || !isActive() || !section.isConnected) return;
history.scrollIntoView({ block: 'nearest', behavior: prefersReducedMotion() ? 'auto' : 'smooth' });
};
if (historyLoaded) reveal();
else void loadHistory().then(reveal);
});
let pendingRefresh = null;
const scheduleRetry = () => {
@@ -110,13 +314,19 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
if (isActive() && section.isConnected) void refresh();
}, 10_000);
};
const showLineStatus = (text) => {
setExpanded(false);
summary.disabled = true;
summary.removeAttribute('aria-label');
summary.textContent = text;
};
const refresh = async () => {
try {
const stats = await authService.getSupportStats(login);
if (!isActive() || !section.isConnected) return;
if (!stats.ready) {
// Первичная индексация ещё идёт. Повторим запрос к кешу без RPC Solana.
content.textContent = t('screens.support_phase2.loading');
showLineStatus(t('screens.support_phase2.loading'));
scheduleRetry();
return;
}
@@ -130,23 +340,42 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
supportReceived: stats.supportReceivedStarCents,
daoDirect: stats.daoDirectStarCents,
});
stopShine?.();
stopShine = null;
summary.replaceChildren();
METRICS.forEach((metric, idx) => {
if (idx) {
const sep = document.createElement('span');
sep.className = 'profile-support__sep';
sep.textContent = '·';
summary.append(sep);
}
summary.append(renderChip(metric, values[idx]));
});
summary.insertAdjacentHTML('beforeend', iconHtml('chevron-down', false, 'profile-support__chevron'));
// Видимые чипы — числа и значки; скринридер получает всю сводку целиком.
summary.setAttribute('aria-label', t('screens.support_phase2.summary', {
sent: formatStars(values[0]), received: formatStars(values[1]), shine: formatStars(values[2]),
}));
summary.disabled = false;
content.replaceChildren();
content.className = 'stack';
[t('screens.support_phase2.sent'), t('screens.support_phase2.received'), t('screens.support_phase2.shine')].forEach((label, idx) => {
METRICS.forEach((metric, idx) => {
const row = document.createElement('div');
row.className = 'row';
row.style.cssText = 'display:flex;justify-content:space-between;gap:8px;';
// Нулевые суммы приглушены и не «дышат»: свечение — только там, где поддержка есть.
row.className = values[idx] === 0n ? `profile-support-stat ${metric.tone} is-zero` : `profile-support-stat ${metric.tone}`;
const iconSlot = document.createElement('span');
iconSlot.className = 'profile-support-stat__icon';
iconSlot.innerHTML = iconHtml(metric.icon);
const name = document.createElement('span');
const amount = document.createElement('strong');
name.textContent = label;
amount.textContent = formatStars(values[idx]);
row.append(name, amount);
name.className = 'profile-support-stat__label';
name.textContent = t(`screens.support_phase2.${metric.key}`);
row.append(iconSlot, name, renderAmount(values[idx]));
content.append(row);
});
} catch {
if (!isActive() || !section.isConnected) return;
// A missing Paid PDA means Free, but network errors must not be displayed as zero.
content.textContent = t('screens.support_phase2.unavailable');
showLineStatus(t('screens.support_phase2.unavailable'));
}
};
void refresh();
+4
View File
@@ -15,6 +15,8 @@ const paths = {
emoji: '<circle cx="12" cy="12" r="9"/><path d="M8.3 14.2a4.6 4.6 0 0 0 7.4 0"/><circle cx="9" cy="9.8" r=".9" fill="currentColor" stroke="none"/><circle cx="15" cy="9.8" r=".9" fill="currentColor" stroke="none"/>',
send: '<path d="M12 19V5M5.5 11.5 12 5l6.5 6.5"/>',
mic: '<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/>',
play: '<path d="M8.2 5.6v12.8a1 1 0 0 0 1.5.86l10.4-6.4a1 1 0 0 0 0-1.72L9.7 4.74a1 1 0 0 0-1.5.86Z"/>',
pause: '<path d="M8.5 5.5v13M15.5 5.5v13"/>',
camera: '<path d="M4.5 7.5h2.8l1.7-2.5h6l1.7 2.5h2.8A1.5 1.5 0 0 1 21 9v9a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18V9a1.5 1.5 0 0 1 1.5-1.5Z"/><circle cx="12" cy="13" r="3.5"/>',
image: '<rect x="3" y="4.5" width="18" height="15" rx="2.5"/><circle cx="8.5" cy="9.5" r="1.6"/><path d="m21 16-4.7-4.7-8.2 8.2"/>',
list: '<path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4.5" cy="6" r=".9" fill="currentColor" stroke="none"/><circle cx="4.5" cy="12" r=".9" fill="currentColor" stroke="none"/><circle cx="4.5" cy="18" r=".9" fill="currentColor" stroke="none"/>',
@@ -50,6 +52,8 @@ const paths = {
'user-plus': '<circle cx="10" cy="8" r="3.5"/><path d="M3.5 20a6.5 6.5 0 0 1 13 0M19 8v6M16 11h6"/>',
refresh: '<path d="M20 12a8 8 0 1 1-2.3-5.6"/><path d="M20 4v4.4h-4.4"/>',
sparkle: '<path d="M11 4c.6 4.4 2.6 6.4 7 7-4.4.6-6.4 2.6-7 7-.6-4.4-2.6-6.4-7-7 4.4-.6 6.4-2.6 7-7Z"/><path d="M19 2.5v3M17.5 4h3"/>',
'trend-up': '<path d="m3 17 6.5-6.5 4 4L21 7"/><path d="M15 7h6v6"/>',
star: '<path d="m12 2.8 2.85 5.78 6.38.93-4.62 4.5 1.09 6.35L12 17.36l-5.7 3 1.09-6.35-4.62-4.5 6.38-.93Z"/>',
rings: '<circle cx="12" cy="12" r="2"/><circle cx="12" cy="12" r="5.5"/><circle cx="12" cy="12" r="9"/>',
place: '<path d="M12 21s-6.5-5.6-6.5-11a6.5 6.5 0 0 1 13 0c0 5.4-6.5 11-6.5 11Z"/><circle cx="12" cy="10" r="2.4"/>',
groups: '<circle cx="9" cy="8" r="3"/><path d="M3.5 19a5.5 5.5 0 0 1 11 0"/><circle cx="17" cy="9.5" r="2.5"/><path d="M15.6 14.1A4.6 4.6 0 0 1 21 18.5"/>',
+23 -16
View File
@@ -375,10 +375,8 @@
"label_030": "Stop and send voice",
"label_031": "Encrypting and sending voice",
"label_032": "Record Voice Message",
"label_033": "↑ swipe up to secure",
"label_034": "Encrypting and Uploading Files",
"label_035": "File",
"label_036": "Record pinned · click ■to submit",
"add_user_prefix": "Add User",
"add_user_suffix": "to contacts?"
},
@@ -1023,7 +1021,9 @@
"text_005": "File downloaded",
"text_006": "file",
"text_007": "Download {value1}",
"file_expired": "File no longer available: encrypted attachments are kept for up to 14 days."
"file_expired": "File no longer available: encrypted attachments are kept for up to 14 days.",
"remaining_less_day": "Attachment available for less than a day",
"remaining_days": "Attachment available for {value1} more days"
},
"palette_editor": {
"text_001": "Failed to read palette, please make sure the whole text is copied.",
@@ -2288,15 +2288,23 @@
"chat_view": {
"security_notice": {
"title": "Private chat security",
"encryption": "Messages in this chat are encrypted on the participants' devices.",
"servers": "The server delivers encrypted data but should not be able to read the conversation.",
"derivation": "Chat keys are derived from account keys and stored on the devices.",
"rotation": "After key rotation, some messages may require the keys to be received again.",
"source": "Before sending, make sure you are communicating with the intended user and server.",
"warning_label": "Important:",
"warning": "never share private keys or your account password with anyone.",
"recovery": "Access recovery depends on your saved keys and password. Keep them secure."
"zero_knowledge_label": "Zero-Knowledge Architecture:",
"zero_knowledge": "We don't trust servers. SHiNE does not store your private keys and has no technical access to chat content.",
"self_custody_label": "Self-Custody & Open Source:",
"self_custody": "Your key is generated locally from your login and password. No hidden algorithms — the code is fully open.",
"control_label": "Absolute Control:",
"control": "Forget your password and you lose access to your messages forever."
},
"voice": {
"hold_tip": "Hold to record",
"lock_tip": "Swipe up to keep recording hands-free",
"slide_cancel": "Slide to cancel",
"delete": "Delete recording",
"pause": "Pause recording",
"resume": "Resume recording",
"pause_playback": "Pause voice message"
},
"file_remove": "Remove file {value1}",
"text_002": "Muted",
"text_015": "Search",
"text_020": "Clear history",
@@ -2336,7 +2344,6 @@
"text_041": "Could not play voice message",
"text_034": "Encrypted data uploaded, but the key-sharing direct message was not sent.",
"text_037": "Could not load direct-message history",
"text_051": "Voicemailed",
"text_052": "No voice mail",
"text_045": "Added to contacts",
"text_046": "Could not add to contacts",
@@ -2407,7 +2414,6 @@
"text_110": "Delete",
"text_117": "File",
"text_118": "File",
"text_119": "↑ swipe up to secure",
"text_120": "Message",
"text_123": "Record Voice Message",
"text_124": "Record Voice Message",
@@ -4345,9 +4351,10 @@
"support_phase2": {
"statistics": "Support",
"loading": "Loading support totals…",
"sent": "❤️ Supported others",
"received": "💚 Support received",
"shine": "✨ Supported SHiNE",
"sent": "Supported others",
"received": "Support received",
"shine": "Supported SHiNE",
"summary": "Support: supported others {sent}, received {received}, supported SHiNE {shine}",
"unavailable": "Totals unavailable (Free account or Solana error)",
"donate_shine": "✨ Support SHiNE",
"donate": "Donate",
+23 -16
View File
@@ -472,10 +472,8 @@
"label_030": "Остановить и отправить голосовое",
"label_031": "Шифрование и отправка голосового",
"label_032": "Записать голосовое сообщение",
"label_033": "↑ проведите вверх, чтобы закрепить",
"label_034": "Шифрование и загрузка файлов",
"label_035": "Файл",
"label_036": "Запись закреплена · нажмите ■, чтобы отправить",
"add_user_prefix": "Добавить пользователя ",
"add_user_suffix": " в контакты?"
},
@@ -1023,7 +1021,9 @@
"text_005": "Файл скачан",
"text_006": "файл",
"text_007": "Скачать {value1}",
"file_expired": "Файл больше недоступен: зашифрованные вложения хранятся не более 14 дней."
"file_expired": "Файл больше недоступен: зашифрованные вложения хранятся не более 14 дней.",
"remaining_less_day": "Вложение доступно ещё менее дня",
"remaining_days": "Вложение доступно ещё {value1} дн."
},
"palette_editor": {
"text_001": "Не удалось прочитать палитру: проверьте, что текст скопирован целиком.",
@@ -2423,15 +2423,23 @@
"chat_view": {
"security_notice": {
"title": "Ваша переписка защищена сквозным шифрованием",
"encryption": "Все личные сообщения шифруются с использованием современных криптографических алгоритмов. Ключи шифрования хранятся ТОЛЬКО на устройствах участников переписки.",
"servers": "Сервера SHiNE не имеют ваших приватных ключей и даже технически никак не могут прочитать ваши сообщения.",
"derivation": "Ваш ключ шифрования высчитывается из вашего логина и пароля",
"rotation": "При смене пароля перекодирование всех ваших сообщений со старого пароля на новый происходит на устройстве пользователя.",
"source": "Код наших приложений полностью открыт и вы легко можете проверить всё это сами.",
"warning_label": "Важно:",
"warning": "если вы забудете свой пароль, восстановить доступ к вашей зашифрованной переписке будет невозможно.",
"recovery": "SHiNE не хранит ваши секретные ключи и никак не сможет помочь вам восстановить вашу переписку"
"zero_knowledge_label": "Zero-Knowledge Architecture:",
"zero_knowledge": "Мы не доверяем серверам. SHiNE не хранит ваши приватные ключи и технически не имеет доступа к содержимому чатов.",
"self_custody_label": "Self-Custody & Open Source:",
"self_custody": "Ваш ключ генерируется локально из вашего логина и пароля. Никаких скрытых алгоритмов — код полностью открыт.",
"control_label": "Absolute Control:",
"control": "Забудете пароль — навсегда потеряете доступ к переписке."
},
"voice": {
"hold_tip": "Удерживайте, чтобы записать",
"lock_tip": "Проведите вверх — запись закрепится",
"slide_cancel": "Влево — отмена",
"delete": "Удалить запись",
"pause": "Приостановить запись",
"resume": "Продолжить запись",
"pause_playback": "Приостановить голосовое сообщение"
},
"file_remove": "Убрать файл {value1}",
"text_001": "Чат",
"text_002": "Без звука",
"text_003": "Показать связи",
@@ -2482,7 +2490,6 @@
"text_048": "Сначала завершите редактирование сообщения.",
"text_049": "Этот браузер не поддерживает запись голосовых сообщений.",
"text_050": "Запись с микрофона прервалась",
"text_051": "Голосовое отправлено",
"text_052": "Голосовое не отправлено",
"text_053": "Не удалось начать запись",
"text_054": "Передача файлов отключена в дополнительных настройках.",
@@ -2550,7 +2557,6 @@
"text_116": "Камера",
"text_117": "Файл",
"text_118": "Файл",
"text_119": "↑ проведите вверх, чтобы закрепить",
"text_120": "Сообщение",
"text_121": "Эмодзи",
"text_122": "Эмодзи",
@@ -4345,9 +4351,10 @@
"support_phase2": {
"statistics": "Поддержка",
"loading": "Загрузка статистики…",
"sent": "❤️ Поддержал других",
"received": "💚 Получил поддержку",
"shine": "✨ Поддержал SHiNE",
"sent": "Поддержал других",
"received": "Получил поддержку",
"shine": "Поддержал SHiNE",
"summary": "Поддержка: поддержал других {sent}, получил поддержку {received}, поддержал SHiNE {shine}",
"unavailable": "Статистика недоступна (Free или ошибка Solana)",
"donate_shine": "✨ Поддержать SHiNE",
"donate": "Пожертвовать",
+189 -382
View File
@@ -38,13 +38,12 @@ import { dayKey, formatClockTime, formatDayLabel, showToast } from '../services/
import { buildDmFileTechBlock, buildDmReplyTechBlock, parseDmTechBlocks, sanitizeUserDmTextForSend } from '../services/dm-tech-blocks.js';
import { isDmFileTransferEnabled } from '../services/feature-settings.js';
import {
decryptDmFileToBlob,
encryptAndUploadDmFile,
DM_MAX_ATTACHMENTS_PER_MESSAGE,
} from '../services/dm-file-service.js';
import { createAttachmentCarouselElement } from '../services/attachment-format.js';
import { createDmFileAttachmentCard, createDmExpiredAttachmentCard, isDmInlineMedia, resolveDmMediaUrl } from '../components/dm-attachments.js';
import { isDmFileExpired } from '../services/dm-file-service.js';
import { DM_FILE_RETENTION_MS, isDmFileExpired } from '../services/dm-file-service.js';
import {
DM_HISTORY_PAGE_SIZE,
isDmHistoryFullyLoaded,
@@ -57,6 +56,8 @@ import {
import { DM_CHAT_PREFS_EVENT, isDmChatMuted, isDmChatPinned, setDmChatPinned } from '../services/dm-chat-prefs.js';
import { createDmMuteMenuItem } from '../components/dm-mute-menu.js';
import { actionErrorText, mediaAccessErrorText } from '../services/ui-error-texts.js';
import { createDmVoiceAttachmentCard } from '../components/dm-voice-card.js';
import { createDmVoiceRecorder } from '../components/dm-voice-recorder.js';
import { scrollNodeIntoContainer } from '../services/scroll-utils.js';
import { loadProfileSnapshot } from '../services/user-profile-params.js';
import { makeProfileLinksRoute, makeProfileRoute } from '../services/shine-routes.js';
@@ -1020,123 +1021,6 @@ function isTwemojiOnlyMessage(messageText) {
}
function formatVoiceDuration(durationMs = 0) {
const total = Math.max(0, Math.round(Number(durationMs || 0) / 1000));
const minutes = Math.floor(total / 60);
const seconds = total % 60;
return `${minutes}:${String(seconds).padStart(2, '0')}`;
}
function createDmVoiceAttachmentCard(attachment) {
const card = document.createElement('div');
card.className = 'dm-voice-card';
const playBtn = document.createElement('button');
playBtn.type = 'button';
playBtn.className = 'ui-button dm-voice-card__play';
playBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_024'));
playBtn.textContent = '▶';
const body = document.createElement('div');
body.className = 'dm-voice-card__body';
const track = document.createElement('button');
track.type = 'button';
track.className = 'ui-button dm-voice-card__track';
track.setAttribute('aria-label', t('dialogs.modals.chat_view.label_025'));
const fill = document.createElement('span');
fill.className = 'dm-voice-card__fill';
track.append(fill);
const meta = document.createElement('div');
meta.className = 'dm-voice-card__meta';
const duration = document.createElement('span');
duration.textContent = formatVoiceDuration(attachment?.durationMs || 0);
const label = document.createElement('span');
label.textContent = t('dialogs.modals.chat_view.label_026');
meta.append(duration, label);
body.append(track, meta);
card.append(playBtn, body);
let audio = null;
let objectUrl = '';
let loading = false;
const syncProgress = () => {
if (!audio) return;
if (!card.isConnected) {
try { audio.pause(); } catch { /* ignore */ }
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
objectUrl = '';
}
return;
}
const total = Number.isFinite(audio.duration) && audio.duration > 0
? audio.duration
: Math.max(0, Number(attachment?.durationMs || 0) / 1000);
const current = Math.max(0, Number(audio.currentTime || 0));
fill.style.width = `${total > 0 ? Math.min(100, (current / total) * 100) : 0}%`;
duration.textContent = `${formatVoiceDuration(current * 1000)} / ${formatVoiceDuration(total * 1000)}`;
playBtn.textContent = audio.paused ? '▶' : 'Ⅱ';
};
const ensureAudio = async () => {
if (audio) return audio;
if (loading) return null;
loading = true;
playBtn.disabled = true;
playBtn.textContent = '…';
try {
const blob = await decryptDmFileToBlob(attachment);
objectUrl = URL.createObjectURL(blob);
audio = new Audio(objectUrl);
audio.preload = 'metadata';
audio.addEventListener('timeupdate', syncProgress);
audio.addEventListener('loadedmetadata', syncProgress);
audio.addEventListener('play', syncProgress);
audio.addEventListener('pause', syncProgress);
audio.addEventListener('ended', syncProgress);
audio.addEventListener('error', () => {
showToast(t('screens.chat_view.text_041'), { kind: 'error', timeoutMs: 2200 });
});
return audio;
} finally {
loading = false;
playBtn.disabled = false;
if (!audio) playBtn.textContent = '▶';
}
};
playBtn.addEventListener('click', async (event) => {
event.stopPropagation();
try {
const player = await ensureAudio();
if (!player) return;
if (player.paused) await player.play();
else player.pause();
syncProgress();
} catch (error) {
showToast(actionErrorText(t('screens.chat_view.text_042'), error), { kind: 'error' });
}
});
track.addEventListener('click', async (event) => {
event.stopPropagation();
try {
const player = await ensureAudio();
if (!player || !Number.isFinite(player.duration) || player.duration <= 0) return;
const rect = track.getBoundingClientRect();
const ratio = Math.min(1, Math.max(0, (event.clientX - rect.left) / Math.max(1, rect.width)));
player.currentTime = player.duration * ratio;
syncProgress();
} catch (error) {
showToast(actionErrorText(t('screens.chat_view.text_043'), error), { kind: 'error' });
}
});
return card;
}
function scrollToLatestMessageSmart(list, { smoothIfNearBottom = false } = {}) {
if (!list) return;
const scrollContainer = findChatScrollContainer(list);
@@ -1186,27 +1070,17 @@ function createDmEncryptionNotice() {
heading.textContent = `🔒 ${t('screens.chat_view.security_notice.title')}`;
notice.append(heading);
for (const text of [
t('screens.chat_view.security_notice.encryption'),
t('screens.chat_view.security_notice.servers'),
t('screens.chat_view.security_notice.derivation'),
t('screens.chat_view.security_notice.rotation'),
t('screens.chat_view.security_notice.source'),
for (const [label, text] of [
[t('screens.chat_view.security_notice.zero_knowledge_label'), t('screens.chat_view.security_notice.zero_knowledge')],
[t('screens.chat_view.security_notice.self_custody_label'), t('screens.chat_view.security_notice.self_custody')],
[t('screens.chat_view.security_notice.control_label'), t('screens.chat_view.security_notice.control')],
]) {
const paragraph = document.createElement('p');
paragraph.textContent = text;
const strong = document.createElement('strong');
strong.textContent = `${label} `;
paragraph.append(strong, document.createTextNode(text));
notice.append(paragraph);
}
const warning = document.createElement('p');
const warningLabel = document.createElement('strong');
warningLabel.textContent = `${t('screens.chat_view.security_notice.warning_label')} `;
warning.append(warningLabel, document.createTextNode(t('screens.chat_view.security_notice.warning')));
notice.append(warning);
const recovery = document.createElement('p');
recovery.textContent = t('screens.chat_view.security_notice.recovery');
notice.append(recovery);
return notice;
}
@@ -1331,6 +1205,23 @@ function renderLog(
);
}
bubble.append(attachmentsWrap);
// Вложения DM v3 живут 14 дней: показываем остаток, пока срок не вышел.
// Истёкшие и так отрисованы карточкой «файл больше недоступен».
const expiresAt = dmAttachments
.filter((item) => Number(item?.version || 1) >= 3)
.map((item) => Number(item.uploadedAtMs || item.messageTimestampMs || 0))
.filter((uploadedAt) => uploadedAt > 0)
.map((uploadedAt) => uploadedAt + DM_FILE_RETENTION_MS);
const remaining = expiresAt.length ? Math.min(...expiresAt) - Date.now() : 0;
if (remaining > 0) {
const dayMs = 24 * 60 * 60 * 1000;
const expiry = document.createElement('div');
expiry.className = 'dm-attachment-expiry';
expiry.textContent = remaining < dayMs
? t('screens.dm_attachments.remaining_less_day')
: t('screens.dm_attachments.remaining_days', { value1: Math.ceil(remaining / dayMs) });
bubble.append(expiry);
}
}
const textNode = document.createElement('div');
@@ -1931,17 +1822,14 @@ export function render({ navigate, route, chrome }) {
<button class="ghost-btn dm-edit-banner__close" type="button" id="chat-edit-cancel" title="${th('screens.chat_view.text_112')}">✕</button>
</div>
<div class="emoji-picker-slot" id="chat-emoji-picker-slot" hidden></div>
<!-- Выбранные файлы ждут здесь: можно убрать лишний и дописать подпись, отправка – одним сообщением. -->
<div class="dm-file-queue" id="chat-file-queue" hidden></div>
<!-- Капсула как строка ответа в обсуждениях. В покое – один ряд: фото · текст · смайлик · отправка.
При вводе текст занимает весь верхний ряд, а все кнопки – нижний (как в терминале Claude). -->
<div class="dm-composer-bar">
<button class="dm-bar-icon dm-media-btn" type="button" id="chat-media-toggle" aria-label="${th('screens.chat_view.text_113')}" title="${th('screens.chat_view.text_114')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('image')}</button>
<button class="dm-bar-icon dm-camera-btn" type="button" id="chat-camera-toggle" aria-label="${th('screens.chat_view.text_115')}" title="${th('screens.chat_view.text_116')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('camera')}</button>
<button class="dm-bar-icon dm-file-btn" type="button" id="chat-file-toggle" aria-label="${th('screens.chat_view.text_117')}" title="${th('screens.chat_view.text_118')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('clip')}</button>
<div class="dm-voice-recording-status" id="chat-voice-recording-status" hidden>
<span class="dm-voice-recording-dot" aria-hidden="true"></span>
<span class="dm-voice-recording-time" id="chat-voice-recording-time">0:00</span>
<span class="dm-voice-recording-hint" id="chat-voice-recording-hint">${th('screens.chat_view.text_119')}</span>
</div>
<div class="dm-field">
<textarea class="input dm-input" name="message" rows="1" placeholder="${th('screens.chat_view.text_120')}" maxlength="12000" enterkeyhint="enter"></textarea>
</div>
@@ -1971,6 +1859,7 @@ export function render({ navigate, route, chrome }) {
const emojiToggle = form.querySelector('#chat-emoji-toggle');
const fileToggle = form.querySelector('#chat-file-toggle');
const fileInput = form.querySelector('#chat-file-input');
const fileQueue = form.querySelector('#chat-file-queue');
// Три входа для вложений: галерея (фото/видео), камера и любой файл – дальше путь один.
const attachSources = [
[fileToggle, fileInput],
@@ -1979,9 +1868,6 @@ export function render({ navigate, route, chrome }) {
];
const attachButtons = attachSources.map(([button]) => button).filter(Boolean);
const sendBtn = form.querySelector('.dm-send-btn');
const voiceStatus = form.querySelector('#chat-voice-recording-status');
const voiceTime = form.querySelector('#chat-voice-recording-time');
const voiceHint = form.querySelector('#chat-voice-recording-hint');
const fileTransferEnabled = isDmFileTransferEnabled();
const editBanner = form.querySelector('#chat-edit-banner');
const editBannerText = form.querySelector('#chat-edit-banner-text');
@@ -1994,18 +1880,11 @@ export function render({ navigate, route, chrome }) {
let emojiLongPressTimer = null;
let emojiLongPressTriggered = false;
let fileActionVisible = false;
let voiceRecorder = null;
let voiceStream = null;
let voiceChunks = [];
let voiceStartedAt = 0;
let voiceTimer = null;
let voiceLocked = false;
let voicePointerHeld = false;
let voiceReleaseRequested = false;
let voiceStartY = 0;
let voicePointerId = null;
let voiceBusy = false;
// Создаётся ниже, когда готовы обработчики страницы; до этого кнопка — обычный микрофон.
let voice = null;
let suppressVoiceClick = false;
let queuedFiles = [];
let fileSending = false;
let historyLoaderTimer = 0;
const setHistoryLoadingState = (isLoading) => {
@@ -2028,8 +1907,8 @@ export function render({ navigate, route, chrome }) {
let composerPressing = false;
const syncComposerLayout = () => {
if (!input) return;
const expanded = inputFocused || composerPressing || emojiPickerOpen || Boolean(activeEdit)
|| Boolean(String(input.value || '').trim());
const expanded = !voice?.isRecording() && (inputFocused || composerPressing || emojiPickerOpen
|| Boolean(activeEdit) || Boolean(String(input.value || '').trim()));
if (expanded === form.classList.contains('dm-chat-input--expanded')) return;
form.classList.toggle('dm-chat-input--expanded', expanded);
autoResizeComposer(input);
@@ -2074,58 +1953,35 @@ export function render({ navigate, route, chrome }) {
const sendIconMarkup = (mode) => {
if (mode === 'send') {
if (mode === 'send' || mode === 'voice-send') {
return iconHtml('send');
}
if (mode === 'stop') {
return '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor"/></svg>';
}
if (mode === 'busy') {
return '<span class="dm-send-busy-dot">…</span>';
}
return iconHtml('mic');
};
const currentVoiceDurationMs = () => voiceStartedAt > 0 ? Math.max(0, Date.now() - voiceStartedAt) : 0;
const syncVoiceTimer = () => {
if (voiceTime) voiceTime.textContent = formatVoiceDuration(currentVoiceDurationMs());
};
const clearVoiceTimer = () => {
if (voiceTimer != null) {
window.clearInterval(voiceTimer);
voiceTimer = null;
}
};
const stopVoiceStreamTracks = () => {
try {
voiceStream?.getTracks?.().forEach((track) => track.stop());
} catch {
// ignore microphone cleanup failures
}
voiceStream = null;
};
const updateSendButtonMode = () => {
if (!sendBtn) return;
const recording = Boolean(voiceRecorder && voiceRecorder.state !== 'inactive');
const voiceState = voice?.state || 'idle';
const recording = Boolean(voice?.isRecording());
let mode = 'voice';
if (voiceBusy) mode = 'busy';
else if (recording && voiceLocked) mode = 'stop';
else if (recording) mode = 'voice';
else if (activeEdit || shared || String(input?.value || '').trim()) mode = 'send';
if (voiceState === 'busy' || fileSending) mode = 'busy';
else if (voiceState === 'locked' || voiceState === 'paused') mode = 'voice-send';
else if (voiceState !== 'idle') mode = 'voice';
else if (activeEdit || shared || queuedFiles.length || String(input?.value || '').trim()) mode = 'send';
sendBtn.dataset.mode = mode;
sendBtn.innerHTML = sendIconMarkup(mode);
sendBtn.classList.toggle('is-holding', voiceState === 'starting' || voiceState === 'holding');
sendBtn.classList.toggle('is-recording', recording);
sendBtn.classList.toggle('is-locked', recording && voiceLocked);
sendBtn.disabled = isShareSending() || voiceBusy || (mode === 'voice' && !recording && !fileTransferEnabled);
sendBtn.disabled = isShareSending() || mode === 'busy' || voiceState === 'cancelling'
|| (mode === 'voice' && voiceState === 'idle' && !fileTransferEnabled);
if (mode === 'send') {
sendBtn.title = t('screens.chat_view.text_029');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_029'));
} else if (mode === 'stop') {
} else if (mode === 'voice-send') {
sendBtn.title = t('screens.chat_view.text_030');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_030'));
} else if (mode === 'busy') {
@@ -2136,149 +1992,62 @@ export function render({ navigate, route, chrome }) {
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_032'));
}
form.classList.toggle('dm-chat-input--recording', recording);
if (voiceStatus) voiceStatus.hidden = !recording;
if (input) input.hidden = recording;
if (emojiToggle) emojiToggle.hidden = recording;
attachButtons.forEach((button) => { button.hidden = recording || !fileTransferEnabled; });
if (!recording && voiceHint) voiceHint.textContent = t('dialogs.modals.chat_view.label_033');
syncVoiceTimer();
};
const selectVoiceMimeType = () => {
const candidates = [
'audio/webm;codecs=opus',
'audio/ogg;codecs=opus',
'audio/mp4',
'audio/webm',
];
return candidates.find((mime) => globalThis.MediaRecorder?.isTypeSupported?.(mime)) || '';
};
const voiceExtension = (mime = '') => {
const value = String(mime || '').toLowerCase();
if (value.includes('ogg')) return 'ogg';
if (value.includes('mp4') || value.includes('m4a')) return 'm4a';
return 'webm';
};
const stopVoiceRecording = ({ send = true } = {}) => {
voicePointerHeld = false;
voiceReleaseRequested = true;
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
voiceRecorder.__shineShouldSend = Boolean(send);
try {
voiceRecorder.stop();
} catch {
stopVoiceStreamTracks();
}
};
const startVoiceRecording = async ({ pointerY = 0, pointerId = null } = {}) => {
if (voiceBusy || (voiceRecorder && voiceRecorder.state !== 'inactive')) return;
if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
return;
}
if (activeEdit) {
showToast(t('screens.chat_view.text_048'), { kind: 'error', timeoutMs: 1600 });
return;
}
if (!globalThis.MediaRecorder || !navigator.mediaDevices?.getUserMedia) {
showToast(t('screens.chat_view.text_049'), { kind: 'error', timeoutMs: 2400 });
return;
}
voicePointerHeld = true;
voiceReleaseRequested = false;
voiceLocked = false;
voiceStartY = Number(pointerY || 0);
voicePointerId = pointerId;
suppressVoiceClick = false;
try {
closeEmojiPicker();
setFileActionVisible(false);
voiceStream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
},
video: false,
});
const mimeType = selectVoiceMimeType();
const recorder = mimeType
? new MediaRecorder(voiceStream, { mimeType })
: new MediaRecorder(voiceStream);
voiceRecorder = recorder;
voiceChunks = [];
recorder.__shineShouldSend = true;
recorder.addEventListener('dataavailable', (event) => {
if (event.data?.size > 0) voiceChunks.push(event.data);
});
recorder.addEventListener('error', (event) => {
showToast(actionErrorText(t('screens.chat_view.text_050'), event?.error), { kind: 'error' });
});
recorder.addEventListener('stop', async () => {
const shouldSend = recorder.__shineShouldSend !== false;
const durationMs = currentVoiceDurationMs();
const chunks = voiceChunks.slice();
voiceChunks = [];
voiceRecorder = null;
voiceLocked = false;
voiceStartedAt = 0;
clearVoiceTimer();
stopVoiceStreamTracks();
voiceBusy = shouldSend && chunks.some((chunk) => chunk.size > 0);
updateSendButtonMode();
if (!voiceBusy) return;
try {
const mime = String(recorder.mimeType || mimeType || chunks[0]?.type || 'audio/webm');
const blob = new Blob(chunks, { type: mime });
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const file = new File([blob], `voice-${timestamp}.${voiceExtension(mime)}`, { type: mime, lastModified: Date.now() });
const attachment = await encryptAndUploadDmFile({
file,
login: state.session.login,
sessionId: state.session.sessionId,
wsUrl: authService.serverUrl,
kind: 'voice',
durationMs,
onProgress: ({ processedBytes, totalBytes }) => {
if (!totalBytes) return;
const percent = Math.round((processedBytes / totalBytes) * 100);
if (voiceHint) voiceHint.textContent = t('screens.chat_view.text_090', { value1: Math.min(100, percent) });
},
});
await sendFileAttachmentMessage([attachment]);
showToast(t('screens.chat_view.text_051'), { timeoutMs: 1200 });
} catch (error) {
showToast(actionErrorText(t('screens.chat_view.text_052'), error), { kind: 'error' });
} finally {
voiceBusy = false;
updateSendButtonMode();
}
}, { once: true });
voiceStartedAt = Date.now();
recorder.start(1000);
voiceTimer = window.setInterval(syncVoiceTimer, 250);
// Микрофон, жесты, панель записи и эффект удаления принадлежат dm-voice-recorder.
// Страница отвечает за свои запреты, вид кнопки и отправку готового файла.
voice = createDmVoiceRecorder({
form,
bar: form.querySelector('.dm-composer-bar'),
canStart: () => {
if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
return false;
}
if (activeEdit) {
showToast(t('screens.chat_view.text_048'), { kind: 'error', timeoutMs: 1600 });
return false;
}
return true;
},
onStateChange: (voiceState) => {
if (disposed) return;
if (voiceState === 'starting') {
closeEmojiPicker();
setFileActionVisible(false);
}
updateSendButtonMode();
if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
} catch (error) {
voicePointerHeld = false;
voiceReleaseRequested = false;
voiceLocked = false;
voiceRecorder = null;
voiceStartedAt = 0;
clearVoiceTimer();
stopVoiceStreamTracks();
updateSendButtonMode();
const mediaReason = mediaAccessErrorText(error);
showToast(mediaReason ? t('screens.chat_view.text_091', { value1: mediaReason }) : actionErrorText(t('screens.chat_view.text_053'), error), { kind: 'error' });
}
};
syncComposerLayout();
},
onRecorded: async ({ file, durationMs, waveform }) => {
const attachment = await encryptAndUploadDmFile({
file,
login: state.session.login,
sessionId: state.session.sessionId,
wsUrl: authService.serverUrl,
kind: 'voice',
durationMs,
});
// Без тоста «отправлено»: появившийся пузырь в ленте и есть подтверждение.
await sendFileAttachmentMessage([{ ...attachment, waveform }]);
},
onError: ({ kind, error }) => {
if (disposed) return;
if (kind === 'unsupported') {
showToast(t('screens.chat_view.text_049'), { kind: 'error', timeoutMs: 2400 });
} else if (kind === 'media') {
const mediaReason = mediaAccessErrorText(error);
showToast(mediaReason ? t('screens.chat_view.text_091', { value1: mediaReason }) : actionErrorText(t('screens.chat_view.text_053'), error), { kind: 'error' });
} else if (kind === 'recorder') {
showToast(actionErrorText(t('screens.chat_view.text_050'), error), { kind: 'error' });
} else {
showToast(actionErrorText(t('screens.chat_view.text_052'), error), { kind: 'error' });
}
},
});
// На сенсорных устройствах фокус в textarea поднимает клавиатуру поверх пикера —
// поэтому при вставке эмодзи фокусируем поле только там, где есть «точный» указатель.
@@ -2664,7 +2433,7 @@ export function render({ navigate, route, chrome }) {
};
// Файлы уже лежат на сервере – повторить можно одно сообщение с ключами, без новой загрузки.
const offerAttachmentsRetry = (attachments, error) => {
const offerAttachmentsRetry = (attachments, error, caption = '') => {
showToast(actionErrorText(attachments.length === 1 ? t('screens.chat_view.text_075') : t('screens.chat_view.text_076'), error), {
kind: 'error',
action: {
@@ -2672,10 +2441,10 @@ export function render({ navigate, route, chrome }) {
onClick: async () => {
if (disposed) return;
try {
await sendFileAttachmentMessage(attachments);
await sendFileAttachmentMessage(attachments, caption);
if (!disposed) showToast(attachments.length === 1 ? t('screens.chat_view.text_077') : t('screens.chat_view.text_100', { value1: attachments.length }), { timeoutMs: 1300 });
} catch (again) {
if (!disposed) offerAttachmentsRetry(attachments, again);
if (!disposed) offerAttachmentsRetry(attachments, again, caption);
}
},
},
@@ -2738,7 +2507,33 @@ export function render({ navigate, route, chrome }) {
}
};
const handleSelectedFiles = async (fileList) => {
// Очередь вложений у поля ввода: файлы копятся, лишний можно убрать, подпись берётся из поля.
const renderQueuedFiles = () => {
fileQueue.replaceChildren();
fileQueue.hidden = !queuedFiles.length;
queuedFiles.forEach((file, index) => {
const fileName = String(file?.name || 'file');
const chip = document.createElement('span');
chip.className = 'dm-file-queue__chip';
const name = document.createElement('span');
name.textContent = fileName;
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = '✕';
remove.disabled = fileSending;
remove.setAttribute('aria-label', t('screens.chat_view.file_remove', { value1: fileName }));
remove.addEventListener('click', () => {
if (fileSending) return;
queuedFiles.splice(index, 1);
renderQueuedFiles();
});
chip.append(name, remove);
fileQueue.append(chip);
});
updateSendButtonMode();
};
const queueSelectedFiles = (files) => {
if (shared) return;
if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
@@ -2748,13 +2543,28 @@ export function render({ navigate, route, chrome }) {
showToast(t('screens.chat_view.text_055'), { kind: 'error', timeoutMs: 1600 });
return;
}
const allFiles = Array.from(fileList || []).filter(Boolean);
if (!allFiles.length) return;
if (allFiles.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
if (queuedFiles.length + files.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
showToast(t('screens.chat_view.text_101', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }), { kind: 'error', timeoutMs: 2200 });
return;
}
queuedFiles.push(...files);
renderQueuedFiles();
};
const sendQueuedFiles = async () => {
if (fileSending || !queuedFiles.length) return;
if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
return;
}
if (activeEdit) {
showToast(t('screens.chat_view.text_055'), { kind: 'error', timeoutMs: 1600 });
return;
}
const allFiles = queuedFiles.slice();
const caption = String(input?.value || '').trim();
fileSending = true;
renderQueuedFiles();
attachButtons.forEach((button) => {
button.disabled = true;
button.classList.add('is-busy');
@@ -2781,13 +2591,27 @@ export function render({ navigate, route, chrome }) {
attachments.push(attachment);
}
uploaded = true;
await sendFileAttachmentMessage(attachments);
await sendFileAttachmentMessage(attachments, caption);
queuedFiles = [];
// Подпись ушла вместе с файлами; если её успели поменять во время загрузки — не трогаем.
if (caption && String(input?.value || '').trim() === caption) {
input.value = '';
autoResizeComposer(input);
syncComposerLayout();
}
setFileActionVisible(false);
showToast(attachments.length === 1 ? t('screens.chat_view.text_078') : t('screens.chat_view.text_103', { value1: attachments.length }), { timeoutMs: 1300 });
} catch (error) {
if (uploaded) offerAttachmentsRetry(attachments, error);
else showToast(actionErrorText(allFiles.length === 1 ? t('screens.chat_view.text_079') : t('screens.chat_view.text_080'), error), { kind: 'error' });
if (uploaded) {
// Файлы уже на сервере: повтор отправит то же сообщение без новой загрузки.
queuedFiles = [];
offerAttachmentsRetry(attachments, error, caption);
} else {
// Загрузка не удалась: очередь остаётся, повторить можно той же кнопкой «Отправить».
showToast(actionErrorText(allFiles.length === 1 ? t('screens.chat_view.text_079') : t('screens.chat_view.text_080'), error), { kind: 'error' });
}
} finally {
fileSending = false;
attachButtons.forEach((button) => {
button.disabled = false;
button.classList.remove('is-busy');
@@ -2796,7 +2620,7 @@ export function render({ navigate, route, chrome }) {
fileToggle.title = t('screens.chat_view.text_036');
fileToggle.setAttribute('aria-label', t('dialogs.modals.chat_view.label_035'));
}
attachSources.forEach(([, picker]) => { if (picker) picker.value = ''; });
renderQueuedFiles();
}
};
@@ -3052,7 +2876,9 @@ export function render({ navigate, route, chrome }) {
});
picker?.addEventListener('change', () => {
const files = Array.from(picker.files || []);
if (files.length) void handleSelectedFiles(files);
// Сброс сразу: тот же файл можно выбрать снова, если его убрали из очереди.
picker.value = '';
if (files.length) queueSelectedFiles(files);
});
});
screen.addEventListener('pointerdown', (event) => {
@@ -3075,47 +2901,22 @@ export function render({ navigate, route, chrome }) {
}
return;
}
if (mode === 'stop') {
event.preventDefault();
suppressVoiceClick = true;
stopVoiceRecording({ send: true });
event.preventDefault();
// Жест указателем обработан здесь; следующий за ним click не должен сработать второй раз.
suppressVoiceClick = true;
if (mode === 'voice-send') {
voice.send();
return;
}
event.preventDefault();
voicePointerHeld = true;
voiceReleaseRequested = false;
voiceStartY = Number(event.clientY || 0);
voicePointerId = event.pointerId;
try { sendBtn.setPointerCapture?.(event.pointerId); } catch { /* optional */ }
void startVoiceRecording({ pointerY: voiceStartY, pointerId: event.pointerId });
voice.press(event);
});
sendBtn?.addEventListener('pointermove', (event) => {
if (!voicePointerHeld || voiceLocked || voicePointerId !== event.pointerId) return;
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
if (Number(event.clientY || 0) <= voiceStartY - 64) {
voiceLocked = true;
voiceReleaseRequested = false;
if (voiceHint) voiceHint.textContent = t('dialogs.modals.chat_view.label_036');
updateSendButtonMode();
try { navigator.vibrate?.(18); } catch { /* ignore */ }
}
sendBtn?.addEventListener('pointermove', (event) => voice.move(event));
sendBtn?.addEventListener('pointerup', (event) => {
try { sendBtn.releasePointerCapture?.(event.pointerId); } catch { /* optional */ }
voice.release(event);
});
const finishVoicePointerGesture = (event) => {
if (!voicePointerHeld && voicePointerId == null) return;
if (voicePointerId != null && event.pointerId !== voicePointerId) return;
voicePointerHeld = false;
voiceReleaseRequested = true;
try { sendBtn?.releasePointerCapture?.(event.pointerId); } catch { /* optional */ }
voicePointerId = null;
if (!voiceLocked) {
suppressVoiceClick = true;
stopVoiceRecording({ send: true });
}
};
sendBtn?.addEventListener('pointerup', finishVoicePointerGesture);
sendBtn?.addEventListener('pointercancel', finishVoicePointerGesture);
sendBtn?.addEventListener('pointercancel', (event) => voice.interrupt(event));
sendBtn?.addEventListener('contextmenu', (event) => {
if (String(sendBtn.dataset.mode || '') !== 'send') event.preventDefault();
});
@@ -3128,8 +2929,11 @@ export function render({ navigate, route, chrome }) {
const mode = String(sendBtn.dataset.mode || 'voice');
if (mode === 'send') {
form.requestSubmit();
} else if (mode === 'stop') {
stopVoiceRecording({ send: true });
} else if (mode === 'voice-send') {
voice.send();
} else if (mode === 'voice') {
// Enter/пробел дают click без pointerdown: удерживать нечего, запись сразу в замке.
voice.startLocked();
}
});
@@ -3138,7 +2942,7 @@ export function render({ navigate, route, chrome }) {
input.addEventListener('keydown', (event) => {
if (!isDmSendEnter(event)) return;
event.preventDefault();
if (shared?.files.length || String(input.value || '').trim()) form.requestSubmit();
if (shared?.files.length || queuedFiles.length || String(input.value || '').trim()) form.requestSubmit();
});
form.addEventListener('submit', async (event) => {
@@ -3148,6 +2952,11 @@ export function render({ navigate, route, chrome }) {
if (text || shared.files.length) await sendSharedDraft(text);
return;
}
if (queuedFiles.length) {
closeEmojiPicker();
await sendQueuedFiles();
return;
}
if (!text) return;
input.value = '';
autoResizeComposer(input);
@@ -3225,9 +3034,7 @@ export function render({ navigate, route, chrome }) {
hideUnreadSeparator({ rerender: false });
stopAllTwemojiAnimations();
clearEmojiLongPress();
try { stopVoiceRecording({ send: false }); } catch { /* ignore */ }
clearVoiceTimer();
stopVoiceStreamTracks();
voice?.destroy();
window.removeEventListener('shine-chat-messages-updated', handleIncomingChatRefresh);
window.removeEventListener('shine-dm-delivery-updated', handleDeliveryRefresh);
window.removeEventListener(DM_CHAT_PREFS_EVENT, handleChatPrefsUpdated);
+6 -1
View File
@@ -1,4 +1,5 @@
import { t } from '../i18n/index.js';
import { decodeWaveform } from '../components/dm-voice-waveform.js';
function defaultParsed(rawText = '') {
const text = String(rawText || '');
return {
@@ -134,6 +135,8 @@ function normalizeFileAttachment(fields = {}) {
} : {}),
kind,
durationMs,
// Волна голосового (wf) — недоверенный ввод собеседника: берём только валидную упаковку.
waveform: kind === 'voice' && decodeWaveform(fields.wf) ? fields.wf : '',
uploadedAtMs: Number(fields.at || 0) || 0,
};
}
@@ -176,12 +179,14 @@ export function buildDmFileTechBlock(attachment = {}) {
const piecesRoot = String(attachment?.torrentV2PiecesRootB64Url || '').trim();
const kind = String(attachment?.kind || 'file') === 'voice' ? 'voice' : 'file';
const durationMs = Math.max(0, Math.floor(Number(attachment?.durationMs || 0)));
const waveform = String(attachment?.waveform || '');
const waveformField = kind === 'voice' && decodeWaveform(waveform) ? `;wf=${waveform}` : '';
const torrentFields = version === 2 ? `;th=${torrentHash};pr=${piecesRoot}` : '';
// Новые DM v3: в E2EE передаём идентификаторы и ключи, а домен — через senderLogin.
// URL ранее созданных v3 и legacy v2/v1 продолжаем читать без изменения.
const urlField = version >= 3 ? '' : `;url=${encodedUrl}`;
const uploadTime = version >= 3 ? `;at=${Math.max(0, Math.floor(Number(attachment?.uploadedAtMs || 0)))}` : '';
return `<S:file;v=${version};id=${id}${urlField};key=${keyB64Url};ivp=${ivPrefix};name=${name};mime=${mime};size=${size};encsize=${encryptedSize};chunk=${chunkSize};chunks=${chunkCount}${torrentFields};kind=${kind};dur=${durationMs}${uploadTime}>`;
return `<S:file;v=${version};id=${id}${urlField};key=${keyB64Url};ivp=${ivPrefix};name=${name};mime=${mime};size=${size};encsize=${encryptedSize};chunk=${chunkSize};chunks=${chunkCount}${torrentFields};kind=${kind};dur=${durationMs}${waveformField}${uploadTime}>`;
}
const ivB64Url = String(attachment?.ivB64Url || '').trim();
+6 -2
View File
@@ -28,9 +28,13 @@ export function parseStarCents(input) {
if (cents < 10n || cents > 0xffff_ffff_ffff_ffffn) throw new Error('Минимальная поддержка — 0,10 ⭐');
return cents;
}
export function formatStars(value) {
/** Только число («0.10»): для вёрстки, где единица показана отдельной SVG-иконкой. */
export function formatStarAmount(value) {
const cents = BigInt(value);
return `${cents / 100n}.${String(cents % 100n).padStart(2, '0')} ⭐`;
return `${cents / 100n}.${String(cents % 100n).padStart(2, '0')}`;
}
export function formatStars(value) {
return `${formatStarAmount(value)} ⭐`;
}
export function splitStarCents(value) {
const cents = BigInt(value);
-184
View File
@@ -1053,21 +1053,6 @@
margin: auto;
}
.dm-send-icon-btn.is-recording {
transform: scale(1.04);
box-shadow: 0 0 0 5px color-mix(in srgb, var(--danger) 8%, transparent), 0 0 24px color-mix(in srgb, var(--danger) 18%, transparent);
}
.dm-send-icon-btn.is-recording:not(.is-locked) {
color: var(--text-primary);
}
.dm-send-icon-btn.is-locked {
color: var(--text-primary);
background: color-mix(in srgb, var(--danger) 28%, transparent);
border-color: color-mix(in srgb, var(--danger) 32%, transparent);
}
.dm-send-busy-dot {
display: inline-grid;
place-items: center;
@@ -1077,68 +1062,6 @@
line-height: 1;
}
.dm-voice-recording-status {
grid-column: 1;
min-height: 42px;
display: grid;
grid-template-columns: auto auto auto minmax(0, 1fr) auto;
align-items: center;
gap: 8px;
padding: 0 12px;
border: 1px solid var(--border-subtle);
border-radius: 14px;
background: color-mix(in srgb, var(--text-primary) 4%, transparent);
overflow: hidden;
}
.dm-voice-recording-status[hidden] {
display: none;
}
.dm-voice-recording-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: color-mix(in srgb, var(--danger) 96%, transparent);
box-shadow: 0 0 12px color-mix(in srgb, var(--danger) 55%, transparent);
animation: dmVoicePulse 1s ease-in-out infinite;
}
@keyframes dmVoicePulse {
0%, 100% { opacity: 0.55; transform: scale(0.82); }
50% { opacity: 1; transform: scale(1); }
}
.dm-voice-recording-time {
font-variant-numeric: tabular-nums;
font-size: 13px;
font-weight: 720;
color: var(--text-primary);
}
.dm-voice-recording-hint {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: right;
font-size: 11px;
color: var(--text-secondary);
}
.dm-voice-cancel, .dm-voice-pause {
width: 32px;
height: 32px;
border: 0;
border-radius: 50%;
background: var(--surface-selected);
color: var(--text-primary);
cursor: pointer;
font-size: 18px;
touch-action: manipulation;
}
.dm-voice-cancel { color: var(--danger); }
.dm-voice-pause[hidden] { display: none; }
.dm-chat-input--voice-paused .dm-voice-recording-dot { animation-play-state: paused; opacity: .35; }
.dm-attachment-expiry {
margin-top: 6px;
color: var(--text-secondary);
@@ -1166,97 +1089,6 @@
.dm-file-queue__chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dm-file-queue__chip button { border: 0; background: none; color: var(--text-secondary); cursor: pointer; }
.dm-chat-input--recording .dm-actions-col {
align-self: center;
}
.dm-voice-card {
min-width: min(280px, 72vw);
max-width: min(330px, 76vw);
display: grid;
grid-template-columns: 42px minmax(0, 1fr);
align-items: center;
gap: 10px;
}
.dm-voice-card__play {
width: 42px;
height: 42px;
min-width: 42px;
padding: 0;
border-radius: 50%;
display: grid;
place-items: center;
font-size: 15px;
line-height: 1;
background: color-mix(in srgb, var(--accent) 12%, transparent);
border: 1px solid color-mix(in srgb, var(--accent) 22%, transparent);
}
.dm-voice-card__play:disabled {
opacity: 0.65;
cursor: progress;
}
.dm-voice-card__body {
min-width: 0;
display: grid;
gap: 6px;
}
.dm-voice-card__track {
position: relative;
width: 100%;
height: 18px;
min-height: 18px;
padding: 0;
border: 0;
background: transparent;
overflow: hidden;
}
.dm-voice-card__track::before {
content: '';
position: absolute;
left: 0;
right: 0;
top: 8px;
height: 2px;
border-radius: 999px;
background: color-mix(in srgb, var(--text-primary) 20%, transparent);
}
.dm-voice-card__fill {
position: absolute;
left: 0;
top: 7px;
width: 0;
height: 4px;
border-radius: 999px;
background: currentColor;
box-shadow: 0 0 8px color-mix(in srgb, var(--accent) 35%, transparent);
pointer-events: none;
}
.dm-voice-card__meta {
display: flex;
justify-content: space-between;
gap: 10px;
font-size: 11px;
color: var(--text-secondary);
font-variant-numeric: tabular-nums;
}
@media (max-width: 390px) {
.dm-voice-card {
min-width: min(252px, 76vw);
}
.dm-voice-recording-hint {
max-width: 150px;
}
}
/* Пересылка DM: выбор чата и подтверждение остаются внутри одного feature-owned modal. */
.dm-forward-modal {
align-items: center;
@@ -1567,23 +1399,7 @@
}
.dm-chat-input .dm-composer-bar .dm-send-btn[data-mode='send'] { color: var(--on-accent); background: var(--accent); }
@media (hover: hover) { .dm-chat-input .dm-composer-bar .dm-send-btn[data-mode='send']:hover { color: var(--on-accent); background: var(--accent-pressed); filter: none; text-shadow: none; } }
.dm-chat-input .dm-composer-bar .dm-send-btn.is-recording { color: var(--text-primary); }
.dm-chat-input .dm-composer-bar .dm-send-btn.is-locked { background: color-mix(in srgb, var(--danger) 28%, transparent); }
.dm-chat-input .dm-composer-bar :is(.dm-bar-icon, .dm-send-btn):focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 1px; }
.dm-chat-input .dm-composer-bar .dm-voice-recording-status {
grid-area: text;
align-self: center;
min-height: 44px;
padding: 0 8px;
border: 0;
background: transparent;
}
.dm-chat-input--recording .dm-composer-bar {
border-color: color-mix(in srgb, var(--danger) 45%, var(--border-control));
}
.dm-chat-input--recording .dm-send-btn {
touch-action: none;
}
/* ===== Нижняя панель ввода – одна для чатов, обсуждений и каналов =====
+549
View File
@@ -0,0 +1,549 @@
/* ===== Голосовые в личной переписке =====
* Пузырь с волной (components/dm-voice-card.js), запись: кнопка микрофона, панель записи,
* замок, подсказка и эффект удаления (components/dm-voice-recorder.js).
* Капсулой ввода и кнопкой отправки в обычном режиме владеет chat.css. */
/* --- Волна: столбики для пузыря и живой записи --- */
.dm-voice-wave {
display: flex;
align-items: center;
justify-content: space-between;
gap: 2px;
min-width: 0;
height: 100%;
}
.dm-voice-wave__bar {
flex: 0 0 3px;
height: 100%;
border-radius: 999px;
background: currentColor;
transform: scaleY(max(0.12, var(--level, 0)));
}
/* --- Пузырь голосового --- */
.dm-voice-card {
min-width: min(260px, 72vw);
max-width: min(330px, 76vw);
display: grid;
grid-template-columns: 42px minmax(0, 1fr);
align-items: center;
gap: 10px;
}
.dm-voice-card__play {
width: 42px;
height: 42px;
min-width: 42px;
padding: 0;
border-radius: 50%;
display: grid;
place-items: center;
background: color-mix(in srgb, var(--accent) 12%, transparent);
border: 1px solid color-mix(in srgb, var(--accent) 22%, transparent);
}
.dm-voice-card__play svg {
width: 20px;
height: 20px;
}
.dm-voice-card__play:disabled {
opacity: 0.65;
cursor: progress;
}
.dm-voice-card__body {
min-width: 0;
display: grid;
gap: 6px;
}
.dm-voice-card__track {
position: relative;
display: block;
width: 100%;
height: 28px;
min-height: 28px;
padding: 0;
border: 0;
background: transparent;
cursor: pointer;
}
.dm-voice-card__wave {
position: absolute;
inset: 0;
gap: 1.5px;
overflow: hidden;
color: color-mix(in srgb, currentColor 45%, transparent);
}
/* Ширина пузыря зависит от экрана: столбики сжимаются, а не вылезают за край. */
.dm-voice-card__wave .dm-voice-wave__bar {
flex: 0 1 3px;
min-width: 1.5px;
}
/* Проигранная часть — та же волна поверх, открытая слева на долю --progress. */
.dm-voice-card__wave--played {
color: inherit;
clip-path: inset(0 calc((1 - var(--progress, 0)) * 100%) 0 0);
}
.dm-voice-card.is-placeholder .dm-voice-card__wave {
opacity: 0.8;
}
.dm-voice-card__meta {
display: flex;
justify-content: space-between;
gap: 10px;
font-size: 11px;
color: var(--text-secondary);
font-variant-numeric: tabular-nums;
}
@media (max-width: 390px) {
.dm-voice-card {
min-width: min(240px, 76vw);
}
}
/* --- Кнопка микрофона --- */
/* Свайпы влево/вверх не должны превращаться в прокрутку страницы — с первого касания. */
.dm-chat-input .dm-send-btn:is([data-mode='voice'], [data-mode='voice-send']) {
touch-action: none;
}
/* Удержание: кнопка вырастает, под ней диск акцента и ореол, дышащий от громкости голоса. */
.dm-chat-input .dm-composer-bar .dm-send-btn.is-holding {
position: relative;
z-index: 2;
transform: scale(1.5);
}
.dm-chat-input .dm-composer-bar .dm-send-btn.is-holding::before,
.dm-chat-input .dm-composer-bar .dm-send-btn.is-holding::after {
content: '';
position: absolute;
border-radius: 50%;
pointer-events: none;
}
.dm-chat-input .dm-composer-bar .dm-send-btn.is-holding::before {
inset: 0;
z-index: -1;
background: var(--accent);
}
.dm-chat-input .dm-composer-bar .dm-send-btn.is-holding::after {
inset: -6px;
z-index: -2;
background: color-mix(in srgb, var(--accent) 24%, transparent);
transform: scale(calc(1 + var(--voice-level, 0) * 0.55));
}
.dm-chat-input .dm-composer-bar .dm-send-btn.is-holding svg {
color: var(--on-accent);
}
/* Замок: правая кнопка отправляет записанное. */
.dm-chat-input .dm-composer-bar .dm-send-btn[data-mode='voice-send'] {
color: var(--on-accent);
background: var(--accent);
}
@media (hover: hover) {
.dm-chat-input .dm-composer-bar .dm-send-btn[data-mode='voice-send']:hover {
color: var(--on-accent);
background: var(--accent-pressed);
filter: none;
text-shadow: none;
}
}
/* --- Капсула во время записи --- */
.dm-chat-input--recording .dm-composer-bar {
border-color: color-mix(in srgb, var(--danger) 45%, var(--border-control));
}
/* Пустое поле текста занимает ту же ячейку, что и панель, и перехватывало бы нажатия. */
.dm-chat-input--recording .dm-composer-bar .dm-field {
display: none;
}
.dm-voice-panel {
grid-area: text;
align-self: center;
position: relative;
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
min-height: 44px;
padding: 0 4px 0 2px;
color: var(--text-primary);
}
.dm-voice-panel[hidden] {
display: none;
}
.dm-voice-panel__lead {
position: relative;
flex: none;
display: grid;
place-items: center;
width: 36px;
height: 36px;
}
.dm-voice-panel__lead > * {
grid-area: 1 / 1;
}
.dm-voice-panel__btn {
flex: none;
display: grid;
place-items: center;
width: 36px;
height: 36px;
padding: 0;
border: 0;
border-radius: 50%;
background: transparent;
color: var(--text-secondary);
cursor: pointer;
touch-action: manipulation;
}
.dm-voice-panel__btn[hidden] {
display: none;
}
.dm-voice-panel__btn svg {
width: 22px;
height: 22px;
}
.dm-voice-panel__btn:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}
@media (hover: hover) {
.dm-voice-panel__btn:hover {
color: var(--text-primary);
background: var(--surface-selected);
}
}
.dm-voice-panel .dm-voice-panel__delete {
color: var(--danger);
}
.dm-voice-panel__dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--danger);
box-shadow: 0 0 10px color-mix(in srgb, var(--danger) 55%, transparent);
}
.dm-voice-panel__time {
flex: none;
min-width: 34px;
font-size: 14px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
/* Окно живой волны: полоса прижата вправо, старые столбики уходят за левый край. */
.dm-voice-panel__wave {
flex: 1 1 auto;
display: flex;
justify-content: flex-end;
min-width: 0;
height: 22px;
overflow: hidden;
color: var(--accent);
}
/* Полоса едет по translateX из dm-voice-recorder.js: новый столбик въезжает справа. */
.dm-voice-panel__strip {
flex: none;
display: flex;
align-items: center;
gap: 2px;
height: 100%;
will-change: transform;
}
.dm-voice-panel__slide {
flex: none;
display: inline-flex;
align-items: center;
gap: 2px;
font-size: 13px;
white-space: nowrap;
color: var(--text-secondary);
transform: translateX(calc(var(--slide, 0) * -48px));
opacity: calc(1 - var(--slide, 0) * 0.85);
}
.dm-voice-panel__slide svg {
width: 16px;
height: 16px;
}
/* Удержание: в ячейке слева точка записи, корзины и паузы нет, справа подсказка про отмену.
Отступ справа — под увеличенным микрофоном подсказка не должна прятаться. */
.dm-voice-panel[data-state='holding'] {
padding-right: 16px;
}
.dm-voice-panel[data-state='holding'] .dm-voice-panel__delete {
visibility: hidden;
}
.dm-voice-panel[data-state='holding'] .dm-voice-panel__pause,
.dm-voice-panel[data-state='cancelling'] .dm-voice-panel__pause,
.dm-voice-panel:not([data-state='holding']) .dm-voice-panel__slide {
display: none;
}
/* Замок и пауза: в ячейке корзина. При удалении корзина остаётся, точка гаснет. */
.dm-voice-panel:not([data-state='holding']) .dm-voice-panel__dot {
visibility: hidden;
}
.dm-voice-panel[data-state='cancelling'] .dm-voice-panel__delete {
pointer-events: none;
}
.dm-voice-panel[data-state='paused'] .dm-voice-panel__wave {
opacity: 0.55;
}
.dm-voice-trash__lid {
transform-box: fill-box;
transform-origin: 0% 100%;
}
.dm-voice-dust {
position: absolute;
z-index: 1;
margin: -1.5px 0 0 -1.5px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 4px color-mix(in srgb, var(--accent) 70%, transparent);
pointer-events: none;
}
/* Светлые пылинки дают облаку мерцание. */
.dm-voice-dust.is-light {
background: color-mix(in srgb, var(--accent) 45%, var(--text-primary));
}
/* --- Замок над микрофоном --- */
.dm-voice-lock {
position: absolute;
right: calc(var(--page-gutter) + 4px);
bottom: calc(100% + 12px);
z-index: 3;
display: grid;
justify-items: center;
gap: 2px;
width: 40px;
padding: 10px 0 8px;
border: 1px solid var(--border-subtle);
border-radius: 20px;
background: var(--surface-raised);
box-shadow: var(--shadow-sm);
color: var(--text-secondary);
transform: translateY(calc(var(--lift, 0) * -14px));
pointer-events: none;
}
.dm-voice-lock[hidden] {
display: none;
}
.dm-voice-lock svg {
width: 22px;
height: 22px;
}
.dm-voice-lock .dm-voice-lock__arrow {
width: 18px;
height: 18px;
opacity: calc(1 - var(--lift, 0));
}
.dm-voice-lock-icon__shackle {
transform: translateY(calc((1 - var(--lift, 0)) * -2.5px));
}
.dm-voice-lock.is-snapped {
color: var(--accent);
}
.dm-voice-lock.is-snapped .dm-voice-lock-icon__shackle {
transform: none;
}
.dm-voice-lock.is-snapped .dm-voice-lock__arrow {
opacity: 0;
}
/* --- Подсказка на короткий тап --- */
.dm-voice-tip {
position: absolute;
right: calc(var(--page-gutter) - 2px);
bottom: calc(100% + 10px);
z-index: 4;
display: flex;
align-items: center;
gap: 10px;
max-width: min(300px, calc(100% - 2 * var(--page-gutter)));
padding: 10px 14px;
border: 1px solid var(--border-subtle);
border-radius: 16px;
background: var(--surface-raised);
color: var(--text-primary);
box-shadow: var(--shadow);
opacity: 0;
visibility: hidden;
transform: translateY(6px);
pointer-events: none;
}
.dm-voice-tip.is-visible {
opacity: 1;
visibility: visible;
transform: none;
}
/* Хвостик указывает на микрофон. */
.dm-voice-tip::after {
content: '';
position: absolute;
right: 22px;
bottom: -6px;
width: 10px;
height: 10px;
border-right: 1px solid var(--border-subtle);
border-bottom: 1px solid var(--border-subtle);
background: var(--surface-raised);
transform: rotate(45deg);
}
.dm-voice-tip > svg {
flex: none;
width: 22px;
height: 22px;
color: var(--accent);
}
.dm-voice-tip__text {
display: grid;
gap: 2px;
font-size: 13px;
line-height: 1.3;
}
.dm-voice-tip__text strong {
font-weight: 600;
}
.dm-voice-tip__text span {
font-size: 12px;
color: var(--text-secondary);
}
@media (max-width: 360px) {
.dm-voice-panel__slide {
font-size: 12px;
}
}
/* --- Движение: только если пользователь его не отключил --- */
@media (prefers-reduced-motion: no-preference) {
.dm-chat-input .dm-send-btn:is([data-mode='voice'], [data-mode='voice-send']) {
transition: transform 200ms cubic-bezier(0.2, 0.9, 0.3, 1.25);
}
.dm-chat-input .dm-composer-bar .dm-send-btn.is-holding::after {
transition: transform 90ms linear;
}
.dm-voice-panel:not([hidden]) {
animation: dm-voice-panel-in 180ms ease-out;
}
.dm-voice-panel[data-state='holding'] .dm-voice-panel__dot {
animation: dm-voice-pulse 1s ease-in-out infinite;
}
.dm-voice-lock:not([hidden]) {
animation: dm-voice-lock-in 220ms cubic-bezier(0.2, 0.9, 0.3, 1.2);
}
.dm-voice-lock .dm-voice-lock__arrow {
animation: dm-voice-lock-arrow 1.2s ease-in-out infinite;
}
.dm-voice-lock.is-snapped {
animation: dm-voice-lock-snap 380ms ease-out forwards;
}
.dm-voice-lock-icon__shackle {
transition: transform 120ms ease;
}
.dm-voice-tip {
transition: opacity 180ms ease, transform 180ms ease, visibility 0s linear 180ms;
}
.dm-voice-tip.is-visible {
transition: opacity 180ms ease, transform 180ms ease, visibility 0s;
}
.dm-voice-panel[data-state='paused'] .dm-voice-panel__wave {
transition: opacity 200ms ease;
}
/* После записи поле ввода и кнопки капсулы проявляются, а не возникают рывком. */
.dm-chat-input.dm-voice-return .dm-composer-bar > :is(.dm-field, .dm-bar-icon) {
animation: dm-voice-return 260ms ease-out both;
}
}
@keyframes dm-voice-return {
from { opacity: 0; transform: translateY(4px); }
}
@keyframes dm-voice-pulse {
0%, 100% { opacity: 0.55; transform: scale(0.82); }
50% { opacity: 1; transform: scale(1); }
}
@keyframes dm-voice-panel-in {
from { opacity: 0; transform: translateX(8px); }
}
@keyframes dm-voice-lock-in {
from { opacity: 0; transform: translateY(10px) scale(0.9); }
}
@keyframes dm-voice-lock-arrow {
0%, 100% { translate: 0 0; }
50% { translate: 0 -3px; }
}
@keyframes dm-voice-lock-snap {
0% { transform: translateY(-14px); }
45% { transform: translateY(-14px) scale(1.15); opacity: 1; }
100% { transform: translateY(-22px) scale(0.9); opacity: 0; }
}
@@ -0,0 +1,292 @@
/* «Поддержка» в профиле (js/components/support-stats.js + support-shine-effects.js), свой и чужой профиль.
Блок-строка с тремя суммами под «Сменить профиль»; тап — «выезд» стеклянной карточки «Ethereal Monochrome»,
тап по её заголовку — обратно. Цвет метрики: ♡ --accent, ↗ --success, ✦ --warning. Только семантические
переменные, обе темы. Всё движение — в блоке prefers-reduced-motion: no-preference внизу файла, поэтому
при reduced-motion вид статичный без переопределений. Решение и отклонения: docs/UI-Design/DESIGN.md §11.3. */
/* Строка и карточка — две строки одной сетки: одна сворачивается (0fr), другая раскрывается (1fr). */
.profile-support { display: grid; grid-template-rows: 1fr 0fr; }
.profile-support[data-expanded='true'] { grid-template-rows: 0fr 1fr; }
.profile-support__line,
.profile-support__panel { display: grid; min-height: 0; overflow: hidden; }
/* После «выезда» орбита и искры выходят за край карточки (до 10px) — обрезку снимаем. */
.profile-support.is-settled .profile-support__panel { overflow: visible; }
.profile-support .is-sent { --ps-tone: var(--accent); }
.profile-support .is-received { --ps-tone: var(--success); }
.profile-support .is-shine { --ps-tone: var(--warning); }
/* Свёрнутый блок: ♡ 0.30★ · ↗ 0.50★ · ✦ 1.00★ ⌄ — по размеру и поверхности как соседний блок «Сменить профиль»
(nav-list: surface, border-subtle, radius-lg; высота 64px — как у его строки с подписью), суммы — кеглем
крупных чисел профиля (--text-lg). */
.profile-support__summary {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: var(--space-1) var(--space-2);
width: 100%;
min-height: 64px;
padding: 10px 14px;
border: 1px solid var(--border-subtle);
border-radius: var(--radius-lg);
background: var(--surface);
color: var(--text-primary);
font-size: var(--text-lg);
line-height: var(--leading-lg);
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
@media (hover: hover) { .profile-support__summary:hover:not(:disabled) { background: var(--surface-selected); } }
.profile-support__summary:active:not(:disabled) { background: var(--surface-selected); }
/* Строка обрезается при сворачивании — фокусное кольцо рисуем внутри кнопки. */
.profile-support__summary:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: -2px; }
.profile-support__summary:disabled { color: var(--text-secondary); font-size: var(--text-md); cursor: default; }
.profile-support__sep { color: var(--text-secondary); }
.profile-support__chevron { width: 18px; height: 18px; flex: none; margin-left: var(--space-1); color: var(--text-secondary); }
.profile-support-chip { display: inline-flex; align-items: center; gap: 5px; color: var(--ps-tone); font-weight: var(--weight-bold); font-variant-numeric: tabular-nums; white-space: nowrap; }
.profile-support-chip.is-zero { color: var(--text-secondary); }
.profile-support-chip__icon { width: 20px; height: 20px; flex: none; }
.profile-support-chip__star { width: 14px; height: 14px; flex: none; }
/* Узкий телефон: та же строка без переноса — чуть меньше кегль и зазоры. */
@media (max-width: 380px) {
.profile-support__summary { gap: var(--space-1) 6px; padding-inline: 10px; font-size: var(--text-md); }
.profile-support__chevron { margin-left: 0; }
.profile-support-chip { gap: 4px; }
.profile-support-chip__icon { width: 18px; height: 18px; }
.profile-support-chip__star { width: 12px; height: 12px; }
}
/* Карточка: ночью тёмное стекло, днём светлое матовое. */
.profile-support-stats {
--ps-edge: color-mix(in srgb, var(--text-primary) 14%, transparent);
--ps-edge-lo: color-mix(in srgb, var(--text-primary) 7%, transparent);
--ps-edge-hi: color-mix(in srgb, var(--text-primary) 42%, transparent);
position: relative;
/* Подкрутка к раскрытой карточке оставляет воздух у края экрана (и место орбите). */
scroll-margin: var(--space-4);
display: grid;
gap: var(--space-1);
padding: var(--space-4) var(--space-4) var(--space-2);
border-radius: var(--radius-xl);
background: linear-gradient(180deg,
color-mix(in srgb, var(--surface-raised) 78%, transparent) 0%,
color-mix(in srgb, var(--surface) 92%, transparent) 100%);
-webkit-backdrop-filter: blur(24px) saturate(1.15);
backdrop-filter: blur(24px) saturate(1.15);
box-shadow:
inset 0 1px 0 color-mix(in srgb, var(--text-primary) 10%, transparent),
inset 0 0 0 2px color-mix(in srgb, var(--text-primary) 3%, transparent),
0 18px 40px -24px rgb(0 0 0 / 0.55);
color: var(--text-primary);
-webkit-tap-highlight-color: transparent;
}
/* Грань стекла — металлический кант 1px градиентом маской (интерьер не подсвечивается): блики на правом верхнем
и левом нижнем углах, тёмная середина; внутренняя фаска — второй inset-тенью выше. */
.profile-support-stats::before {
content: "";
position: absolute;
inset: 0;
padding: 1px;
border-radius: inherit;
background: linear-gradient(225deg, var(--ps-edge-hi) 0%, var(--ps-edge) 18%, var(--ps-edge-lo) 45%, var(--ps-edge-lo) 55%, var(--ps-edge) 82%, var(--ps-edge-hi) 100%);
-webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
-webkit-mask-composite: xor;
mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
mask-composite: exclude;
pointer-events: none;
}
/* Заголовок «Поддержка ⌃» — кнопка сворачивания карточки. */
.profile-support-stats__title {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
width: 100%;
min-height: 44px;
margin: calc(-1 * var(--space-2)) 0 0;
padding: 0;
border: 0;
border-radius: var(--radius-md);
background: transparent;
color: var(--text-primary);
font-size: 1rem;
line-height: 1.5;
font-weight: var(--weight-bold);
text-align: start;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
.profile-support-stats__title:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
.profile-support-stats__title-chevron { width: 18px; height: 18px; flex: none; color: var(--text-secondary); }
@media (hover: hover) { .profile-support-stats__title:hover .profile-support-stats__title-chevron { color: var(--text-primary); } }
.profile-support-stats__content { display: grid; }
.profile-support-stat {
display: grid;
grid-template-columns: 22px minmax(0, 1fr) auto;
align-items: center;
column-gap: var(--space-3);
min-height: 44px;
font-size: var(--text-md);
line-height: var(--leading-md);
}
.profile-support-stat__icon { display: inline-flex; color: var(--ps-tone); }
.profile-support-stat__icon svg { width: 22px; height: 22px; }
.profile-support-stat__label { min-width: 0; overflow-wrap: anywhere; }
.profile-support-stat .profile-support-amount__star { color: var(--ps-tone); }
.profile-support-stat.is-zero .profile-support-stat__icon,
.profile-support-stat.is-zero .profile-support-amount,
.profile-support-stat.is-zero .profile-support-amount__star { color: var(--text-secondary); }
.profile-support-amount { position: relative; display: inline-flex; align-items: center; gap: 6px; font-size: 1rem; font-weight: var(--weight-bold); font-variant-numeric: tabular-nums; white-space: nowrap; }
.profile-support-amount__star { width: 14px; height: 14px; flex: none; }
.profile-support-history { margin-top: var(--space-2); padding-top: var(--space-1); border-top: 1px solid var(--border-subtle); scroll-margin: var(--space-4); }
/* Кнопка истории — <summary>: пружинный отклик и слой жидкого света под текстом. */
.profile-support-history__toggle {
position: relative;
isolation: isolate;
display: flex;
align-items: center;
justify-content: center;
gap: var(--space-1);
min-height: 44px;
margin: 0 calc(-1 * var(--space-2));
padding: var(--space-2) var(--space-3);
overflow: hidden;
border-radius: var(--radius-md);
color: var(--text-secondary);
font-size: var(--text-md);
list-style: none;
cursor: pointer;
user-select: none;
-webkit-tap-highlight-color: transparent;
}
.profile-support-history__toggle::-webkit-details-marker { display: none; }
.profile-support-history__toggle::marker { content: ""; }
.profile-support-history__toggle:hover { color: var(--text-primary); }
.profile-support-history__toggle:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 2px; }
.profile-support-history__toggle:active,
.profile-support-history__toggle.is-pressed { background-color: color-mix(in srgb, var(--text-primary) 6%, transparent); color: var(--text-primary); }
.profile-support-history__label,
.profile-support-history__chevron { position: relative; z-index: 1; }
.profile-support-history__chevron { width: 18px; height: 18px; flex: none; }
.profile-support-history[open] .profile-support-history__chevron { transform: rotate(90deg); }
/* Фильтр #profile-support-goo — только на этом слое: капли непрозрачные (порог альфы их не стирает),
интенсивность задаёт opacity слоя, текст над ним остаётся чётким. */
.profile-support-history__light { position: absolute; inset: 0; z-index: 0; overflow: hidden; border-radius: inherit; filter: url(#profile-support-goo); opacity: .22; pointer-events: none; }
:root[data-theme='light'] .profile-support-history__light { opacity: .14; }
.profile-support-goo { position: absolute; width: 0; height: 0; }
.profile-support-goo__drop { position: absolute; left: calc(var(--drop) / -2); top: calc(var(--drop) / -2); width: var(--drop); height: var(--drop); border-radius: 50%; background: var(--text-primary); }
.profile-support-history__rows { display: grid; gap: var(--space-2); padding: var(--space-2) 0 var(--space-3); }
/* Перевод: «кому/от кого — сумма» сверху, «дата · SOL — транзакция» снизу (порядок DOM задаёт сетку). */
.profile-support-transfer { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; column-gap: var(--space-2); row-gap: 2px; }
.profile-support-transfer__peer { min-width: 0; overflow-wrap: anywhere; }
.profile-support-transfer__link { justify-self: end; font-size: var(--text-sm); }
.profile-support-transfer .profile-support-amount { font-size: var(--text-md); }
/* Слои сияния (support-shine-effects.js) — декоративные, клики проходят сквозь них. */
.profile-support-fx { position: absolute; pointer-events: none; }
.profile-support-fx__rim,
.profile-support-fx__comets { left: 0; top: 0; overflow: visible; }
/* Рамка на время сияния: кант чуть золотится, по нему ровно по контуру обходит тонкий блик
и гаснет звёздочкой-вспышкой в правом верхнем углу. */
.profile-support-fx__rim-tint { fill: none; stroke: var(--warning); stroke-width: 1; opacity: 0; }
.profile-support-fx__rim-glint { fill: none; stroke: var(--warning); stroke-width: 2; stroke-linecap: round; stroke-dasharray: .12 2; stroke-dashoffset: .12; }
.profile-support-fx__flare { fill: color-mix(in srgb, var(--warning) 65%, var(--text-primary)); opacity: 0; transform-box: fill-box; transform-origin: center; }
/* Комета «пополнения»: хвост — штрих по дуге (его смещение ведёт JS), голова — светящаяся точка, пылинки — за ней. */
.profile-support-fx__trail { fill: none; stroke-width: 2.5; stroke-linecap: round; }
.profile-support-fx__comet { left: -4px; top: -4px; width: 8px; height: 8px; border-radius: 50%; background: color-mix(in srgb, var(--ps-tone) 55%, var(--text-primary)); box-shadow: 0 0 6px 3px var(--ps-tone), 0 0 20px 7px color-mix(in srgb, var(--ps-tone) 50%, transparent); }
/* Днём широкий ореол тёмного тона на светлом стекле выглядит пятном: светлая сердцевина и узкий прозрачный ореол. */
:root[data-theme='light'] .profile-support-fx__comet { background: color-mix(in srgb, var(--ps-tone) 60%, var(--surface)); box-shadow: 0 0 3px 1px color-mix(in srgb, var(--ps-tone) 70%, transparent), 0 0 10px 3px color-mix(in srgb, var(--ps-tone) 22%, transparent); }
.profile-support-fx__mote { width: 3.5px; height: 3.5px; margin: -1.75px 0 0 -1.75px; border-radius: 50%; background: var(--ps-tone); box-shadow: 0 0 5px 1px var(--ps-tone); opacity: 0; }
/* Сумма в момент пополнения — в цвете метрики с мягким свечением, затем плавно возвращается к обычному виду. */
.profile-support-stat .profile-support-amount.is-filling { color: var(--ps-tone); text-shadow: 0 0 12px color-mix(in srgb, var(--ps-tone) 60%, transparent); }
.profile-support-fx__orbit { overflow: visible; filter: drop-shadow(0 0 3px color-mix(in srgb, var(--warning) 70%, transparent)); }
.profile-support-fx__ring { fill: none; stroke: var(--warning); stroke-opacity: .4; stroke-width: 1; stroke-dasharray: 1 7; stroke-linecap: round; }
.profile-support-fx__dot { fill: var(--warning); }
.profile-support-sparks { position: absolute; left: 50%; top: 50%; width: 0; height: 0; pointer-events: none; }
.profile-support-spark { position: absolute; left: -2.5px; top: -2.5px; width: 5px; height: 5px; border-radius: 50%; background: var(--ps-tone, var(--warning)); box-shadow: 0 0 8px var(--ps-tone, var(--warning)); opacity: 0; }
@media (prefers-reduced-motion: no-preference) {
.profile-support { transition: grid-template-rows 420ms cubic-bezier(0.22, 1, 0.36, 1); }
.profile-support__summary { transition: background-color var(--duration-fast) ease, transform 180ms cubic-bezier(0.175, 0.885, 0.32, 1.275); }
.profile-support__summary:active:not(:disabled) { transform: scale(0.97); }
/* Тап по карточке: вдавливание за 0.15 с, отпускание — пружина 0.4 с (кривая с перелётом). */
.profile-support-stats { transition: transform 400ms cubic-bezier(0.175, 0.885, 0.32, 1.275); }
.profile-support-stats.is-pressed { transform: scale(0.97); transition-duration: 150ms; transition-timing-function: ease-out; }
/* «Дыхание» иконок и звёзд у ненулевых сумм: цикл 4 с, только пока карточка раскрыта. */
.profile-support[data-expanded='true'] .profile-support-stat:not(.is-zero) .profile-support-stat__icon svg,
.profile-support[data-expanded='true'] .profile-support-stat:not(.is-zero) .profile-support-amount__star { animation: profile-support-breathe 2s ease-in-out infinite alternate; }
.profile-support[data-expanded='true'] .profile-support-stat:nth-child(2) :is(.profile-support-stat__icon svg, .profile-support-amount__star) { animation-delay: -.67s; }
.profile-support[data-expanded='true'] .profile-support-stat:nth-child(3) :is(.profile-support-stat__icon svg, .profile-support-amount__star) { animation-delay: -1.33s; }
.profile-support-history__toggle { transition: transform 180ms cubic-bezier(0.175, 0.885, 0.32, 1.275), color var(--duration-fast) ease, background-color var(--duration-fast) ease; }
.profile-support-history__toggle:active,
.profile-support-history__toggle.is-pressed { transform: scale(0.97); }
.profile-support-history__chevron { transition: transform var(--duration-fast) ease; }
/* Жидкий свет на «Истории переводов» — 0.8 с. */
.profile-support-goo__drop.is-main { --drop: 44px; animation: profile-support-goo-main 800ms cubic-bezier(0.22, 1, 0.36, 1) forwards; }
.profile-support-goo__drop.is-left,
.profile-support-goo__drop.is-right { --drop: 18px; animation: profile-support-goo-drop 720ms 60ms cubic-bezier(0.22, 1, 0.36, 1) both; }
.profile-support-goo__drop.is-left { --dir: -1; }
.profile-support-goo__drop.is-right { --dir: 1; }
.profile-support-fx__rim { animation: profile-support-fx-life 2.2s linear forwards; }
.profile-support-fx__rim-tint { animation: profile-support-rim-tint 1.8s ease-in-out forwards; }
.profile-support-fx__rim-glint { animation: profile-support-rim-glint 1.4s cubic-bezier(0.45, 0, 0.25, 1) forwards; }
.profile-support-fx__flare { animation: profile-support-flare 700ms 1.3s ease-out forwards; }
.profile-support-fx__comets { animation: profile-support-fx-life 1.8s linear forwards; }
.profile-support-fx__mote { animation: profile-support-mote 800ms ease-out forwards; }
.profile-support-fx__orbit { animation: profile-support-fx-fade 2.4s ease-in-out forwards; }
.profile-support-spark { animation: profile-support-spark 800ms ease-out forwards; }
.profile-support-stat .profile-support-amount { transition: color 600ms ease, text-shadow 600ms ease; }
}
@keyframes profile-support-breathe {
from { filter: drop-shadow(0 0 1px color-mix(in srgb, var(--ps-tone) 25%, transparent)); opacity: .82; }
to { filter: drop-shadow(0 0 6px color-mix(in srgb, var(--ps-tone) 70%, transparent)); opacity: 1; }
}
@keyframes profile-support-goo-main {
0% { transform: scale(.35); opacity: 1; }
60% { opacity: .85; }
100% { transform: scale(6); opacity: 0; }
}
@keyframes profile-support-goo-drop {
0% { transform: translateX(0) scale(.6); opacity: 1; }
100% { transform: translateX(calc(var(--dir) * 96px)) scale(1.6); opacity: 0; }
}
@keyframes profile-support-fx-fade {
0% { opacity: 0; }
15%, 75% { opacity: 1; }
100% { opacity: 0; }
}
/* Срок жизни слоя: держится и гаснет в самом конце — по его animationend слой удаляется. */
@keyframes profile-support-fx-life {
0%, 90% { opacity: 1; }
100% { opacity: 0; }
}
@keyframes profile-support-rim-tint {
0%, 100% { opacity: 0; }
45% { opacity: .5; }
}
/* Блик проходит полный круг (путь длиной 1) и уходит за конец — в правый верхний угол, где загорается вспышка. */
@keyframes profile-support-rim-glint { to { stroke-dashoffset: -1; } }
@keyframes profile-support-flare {
0% { opacity: 0; transform: scale(0) rotate(0deg); }
35% { opacity: 1; transform: scale(1.15) rotate(20deg); }
100% { opacity: 0; transform: scale(.2) rotate(90deg); }
}
@keyframes profile-support-mote {
0% { opacity: .95; transform: translate(0, 0) scale(1); }
100% { opacity: 0; transform: translate(var(--mx), var(--my)) scale(.4); }
}
/* Искра держит яркость до середины пути и гаснет на излёте — иначе вспышка не успевает читаться. */
@keyframes profile-support-spark {
0% { transform: rotate(var(--a)) translateX(6px) scale(1); opacity: 1; }
50% { opacity: 1; }
100% { transform: rotate(var(--a)) translateX(var(--d)) scale(.3); opacity: 0; }
}
+8 -10
View File
@@ -11,23 +11,21 @@ const en = JSON.parse(source('../js/i18n/locales/en.json'));
for (const [locale, language] of [['ru', ru], ['en', en]]) {
test(`в ${locale} есть полный текст предупреждения DM`, () => {
const note = language.screens.chat_view.security_notice;
for (const key of ['title', 'encryption', 'servers', 'derivation', 'rotation', 'source', 'warning_label', 'warning', 'recovery']) {
for (const key of ['title', 'zero_knowledge_label', 'zero_knowledge', 'self_custody_label', 'self_custody', 'control_label', 'control']) {
assert.ok(typeof note[key] === 'string' && note[key].trim(), `${locale}/${key}`);
}
});
}
test('русский текст DM соответствует утверждённой пользователем редакции от 13.11.2026', () => {
test('русский текст DM соответствует утверждённой пользователем редакции от 27.11.2026', () => {
assert.deepEqual(ru.screens.chat_view.security_notice, {
"title": "Ваша переписка защищена сквозным шифрованием",
"encryption": "Все личные сообщения шифруются с использованием современных криптографических алгоритмов. Ключи шифрования хранятся ТОЛЬКО на устройствах участников переписки.",
"servers": "Сервера SHiNE не имеют ваших приватных ключей и даже технически никак не могут прочитать ваши сообщения.",
"derivation": "Ваш ключ шифрования высчитывается из вашего логина и пароля",
"rotation": "При смене пароля перекодирование всех ваших сообщений со старого пароля на новый происходит на устройстве пользователя.",
"source": "Код наших приложений полностью открыт и вы легко можете проверить всё это сами.",
"warning_label": "Важно:",
"warning": "если вы забудете свой пароль, восстановить доступ к вашей зашифрованной переписке будет невозможно.",
"recovery": "SHiNE не хранит ваши секретные ключи и никак не сможет помочь вам восстановить вашу переписку"
"zero_knowledge_label": "Zero-Knowledge Architecture:",
"zero_knowledge": "Мы не доверяем серверам. SHiNE не хранит ваши приватные ключи и технически не имеет доступа к содержимому чатов.",
"self_custody_label": "Self-Custody & Open Source:",
"self_custody": "Ваш ключ генерируется локально из вашего логина и пароля. Никаких скрытых алгоритмов — код полностью открыт.",
"control_label": "Absolute Control:",
"control": "Забудете пароль — навсегда потеряете доступ к переписке."
});
// Текст должен отображаться напрямую через textContent, без HTML-сущностей.
for (const text of Object.values(ru.screens.chat_view.security_notice)) {
@@ -0,0 +1,59 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { buildDmFileTechBlock, parseDmTechBlocks } from '../js/services/dm-tech-blocks.js';
import { encodeWaveform } from '../js/components/dm-voice-waveform.js';
const wf = encodeWaveform(Array.from({ length: 64 }, (_, i) => i % 32));
const voice = {
version: 3,
id: 'Root58Id',
keyB64Url: 'KEYb64',
ivPrefixB64Url: 'IVPx',
name: 'voice.webm',
mime: 'audio/webm',
size: 100,
encryptedSize: 120,
chunkSize: 64,
chunkCount: 1,
kind: 'voice',
durationMs: 4200,
uploadedAtMs: 1_700_000_000_000,
};
const attachmentOf = (text) => parseDmTechBlocks(text).fileAttachments[0];
test('голосовое с волной: поле wf уходит в блок и возвращается при разборе', () => {
const block = buildDmFileTechBlock({ ...voice, waveform: wf });
assert.ok(block.includes(`;wf=${wf}`));
const parsed = attachmentOf(`${block}🎤`);
assert.equal(parsed.kind, 'voice');
assert.equal(parsed.durationMs, 4200);
assert.equal(parsed.waveform, wf);
});
test('пересылка сохраняет волну: блок после разбора собирается тем же', () => {
const block = buildDmFileTechBlock({ ...voice, waveform: wf });
assert.equal(buildDmFileTechBlock(attachmentOf(block)), block);
});
test('без волны, с мусором и у обычного файла поле wf не пишется', () => {
assert.ok(!buildDmFileTechBlock(voice).includes(';wf='));
assert.ok(!buildDmFileTechBlock({ ...voice, waveform: 'bad$wf' }).includes(';wf='));
assert.ok(!buildDmFileTechBlock({ ...voice, kind: 'file', waveform: wf }).includes(';wf='));
assert.equal(attachmentOf(buildDmFileTechBlock(voice)).waveform, '');
});
test('чужой мусор в wf не попадает в вложение, остальное читается', () => {
const block = buildDmFileTechBlock(voice).replace('>', ';wf=%3Cscript%3E>');
const parsed = attachmentOf(block);
assert.equal(parsed.kind, 'voice');
assert.equal(parsed.waveform, '');
});
test('старый блок голосового v2 без wf читается как раньше', () => {
const old = '<S:file;v=2;id=ROOT;url=https%3A%2F%2Fx;key=K;ivp=P;name=v.webm;mime=audio%2Fwebm;size=1;encsize=2;chunk=3;chunks=1;th=T;pr=R;kind=voice;dur=1500>';
const parsed = attachmentOf(old);
assert.equal(parsed.kind, 'voice');
assert.equal(parsed.durationMs, 1500);
assert.equal(parsed.waveform, '');
});
+78
View File
@@ -0,0 +1,78 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
WAVEFORM_POINTS,
WAVEFORM_MAX_LEVEL,
compressLevels,
decodeWaveform,
encodeWaveform,
resampleWaveform,
rmsLevel,
waveformFromChannelData,
} from '../js/components/dm-voice-waveform.js';
test('compressLevels: всегда 64 значения 0..31, пик громкости = 31', () => {
const levels = Array.from({ length: 500 }, (_, i) => (i === 250 ? 0.4 : 0.1));
const wave = compressLevels(levels);
assert.equal(wave.length, WAVEFORM_POINTS);
assert.ok(wave.every((v) => Number.isInteger(v) && v >= 0 && v <= WAVEFORM_MAX_LEVEL));
assert.equal(Math.max(...wave), WAVEFORM_MAX_LEVEL);
assert.ok(wave.filter((v) => v === WAVEFORM_MAX_LEVEL).length === 1, 'пик не размазывается по всей волне');
});
test('compressLevels: тишина и пустой ввод дают нули, короткий ввод растягивается', () => {
assert.deepEqual([...compressLevels([])], new Array(WAVEFORM_POINTS).fill(0));
assert.deepEqual([...compressLevels(new Array(100).fill(0.0001))], new Array(WAVEFORM_POINTS).fill(0));
const short = compressLevels([0.1, 0.2, 0.4]);
assert.equal(short.length, WAVEFORM_POINTS);
assert.ok(short[0] < short[WAVEFORM_POINTS - 1], 'форма сохраняется при растяжении');
});
test('compressLevels: возрастающая громкость даёт неубывающую волну, мусор не ломает', () => {
const ramp = compressLevels(Array.from({ length: 640 }, (_, i) => i / 640));
for (let i = 1; i < ramp.length; i += 1) assert.ok(ramp[i] >= ramp[i - 1]);
const dirty = compressLevels([NaN, -1, Infinity, 0.2, '0.3', null]);
assert.ok(dirty.every((v) => v >= 0 && v <= WAVEFORM_MAX_LEVEL));
});
test('encodeWaveform/decodeWaveform: точный круговой обход, 54 символа base64url', () => {
const values = Uint8Array.from({ length: WAVEFORM_POINTS }, (_, i) => (i * 7) % 32);
const encoded = encodeWaveform(values);
assert.equal(encoded.length, 54);
assert.match(encoded, /^[A-Za-z0-9_-]+$/);
assert.deepEqual([...decodeWaveform(encoded)].slice(0, WAVEFORM_POINTS), [...values]);
});
test('encodeWaveform ограничивает значения и длину', () => {
const decoded = decodeWaveform(encodeWaveform([99, -5, 3.6, 31]));
assert.deepEqual([...decoded].slice(0, 4), [31, 0, 4, 31]);
assert.equal(encodeWaveform(new Array(200).fill(5)).length, 54);
});
test('decodeWaveform отвергает чужой мусор', () => {
for (const bad of ['', null, undefined, 42, 'abc$', 'a b', '<S:x>', 'A'.repeat(65), 'A']) {
assert.equal(decodeWaveform(bad), null, String(bad));
}
});
test('resampleWaveform: нужное число столбиков 0..1, пик сохраняется', () => {
const values = new Uint8Array(WAVEFORM_POINTS).fill(3);
values[33] = 31;
const bars = resampleWaveform(values, 40);
assert.equal(bars.length, 40);
assert.ok(bars.every((v) => v >= 0 && v <= 1));
assert.equal(Math.max(...bars), 1);
assert.equal(resampleWaveform(Uint8Array.from([31, 0]), 6).length, 6);
assert.deepEqual(resampleWaveform(null, 3), [0, 0, 0]);
});
test('rmsLevel и waveformFromChannelData: громкая половина выше тихой', () => {
assert.equal(rmsLevel(new Float32Array(16)), 0);
assert.ok(Math.abs(rmsLevel(Float32Array.from([1, -1, 1, -1])) - 1) < 1e-9);
const data = new Float32Array(48_000);
for (let i = 24_000; i < data.length; i += 1) data[i] = Math.sin(i / 7) * 0.5;
const wave = waveformFromChannelData(data);
assert.equal(wave.length, WAVEFORM_POINTS);
const avg = (part) => part.reduce((s, v) => s + v, 0) / part.length;
assert.ok(avg([...wave.slice(32)]) > avg([...wave.slice(0, 32)]) + 20);
});