Compare commits

..
13 Commits
Author SHA1 Message Date
RarDog c7f507836b fix: fullscreen playback state retention and responsive control buttons (v3.1.8)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 23:33:42 +03:00
RarDog 1395cfd414 fix: remove unsafe libmpv setProperty FFI calls causing SIGSEGV crash (v3.1.7)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 23:17:15 +03:00
RarDog 15bebd6e47 fix: fullscreen play-pause button, search clear providers, video volume persistence & codec fallback (v3.1.6)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 23:09:23 +03:00
RarDog 295499ca4b feat: persist video volume, fix fullscreen controls, search providers & comments headroom (v3.1.5)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 22:50:15 +03:00
RarDog 9a0fd282b7 feat(video): optimize video player aspect ratio sizing and seekbar positioning v3.1.4
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 21:50:17 +03:00
RarDog 254f0e3d59 feat: Liquid Glass redesign for providers and network check, and tab back navigation (v3.1.3)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 21:29:25 +03:00
RarDog 5a568a3df9 perf: optimize post tags scrolling performance and eliminate frame drops (v3.1.2)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 21:11:03 +03:00
RarDog d58b512020 feat: colored tag categories division like e621/gelbooru/rule34 and fix search for tags with parentheses
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 20:56:35 +03:00
RarDog 384c07955c feat(ui): iPhone Liquid Glass redesign for Search, Favorites, and History, fix cheat sheet clearance and update sheet
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 19:06:37 +03:00
RarDog ec594595c9 fix: adjust settings button position and backup/json buttons layout (v3.0.9)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 18:42:00 +03:00
RarDog 586e3fc4db feat: iPhone-style liquid glass settings and floating button (v3.0.8)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 18:32:16 +03:00
RarDog 61c2d0561c feat: liquid glass bottom navigation bar with animated pill and tap micro-animations (v3.0.7)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 18:19:58 +03:00
RarDog dff2cd806d feat: improve recent searches and tags visibility, deduplication and UI (v3.0.6)
Build and Release / Build Windows x64 (push) Has been cancelled
2026-09-04 18:06:46 +03:00
33 changed files with 5825 additions and 1522 deletions
+1 -1
View File
@@ -10,7 +10,7 @@
</p> </p>
<p align="center"> <p align="center">
<a href="https://github.com/RarDog/Lunaris/releases"><img src="https://img.shields.io/badge/Version-3.0.5-8A2BE2?style=for-the-badge&logo=semver&logoColor=white" alt="Version 3.0.5" /></a> <a href="https://github.com/RarDog/Lunaris/releases"><img src="https://img.shields.io/badge/Version-3.1.8-8A2BE2?style=for-the-badge&logo=semver&logoColor=white" alt="Version 3.1.8" /></a>
<img src="https://img.shields.io/badge/Flutter-3.47+-02569B?style=for-the-badge&logo=flutter&logoColor=white" alt="Flutter" /> <img src="https://img.shields.io/badge/Flutter-3.47+-02569B?style=for-the-badge&logo=flutter&logoColor=white" alt="Flutter" />
<img src="https://img.shields.io/badge/Platform-Android%20%7C%20Linux%20%7C%20Windows-00C853?style=for-the-badge" alt="Platforms" /> <img src="https://img.shields.io/badge/Platform-Android%20%7C%20Linux%20%7C%20Windows-00C853?style=for-the-badge" alt="Platforms" />
<a href="https://github.com/RarDog/Lunaris/wiki"><img src="https://img.shields.io/badge/Wiki-Documentation-FF6F00?style=for-the-badge&logo=gitbook&logoColor=white" alt="Wiki" /></a> <a href="https://github.com/RarDog/Lunaris/wiki"><img src="https://img.shields.io/badge/Wiki-Documentation-FF6F00?style=for-the-badge&logo=gitbook&logoColor=white" alt="Wiki" /></a>
+2 -2
View File
@@ -1,3 +1,3 @@
const appDisplayVersion = '3.0.5'; const appDisplayVersion = '3.1.8';
const appBuildNumber = 56; const appBuildNumber = 69;
const appReleaseChannel = 'Stable'; const appReleaseChannel = 'Stable';
+130
View File
@@ -1,4 +1,134 @@
const lunarisChangelog = [ const lunarisChangelog = [
LunarisChange(
version: '3.1.8',
title: 'Безупречный полноэкранный плеер: устранение остановки при развертывании и отзывчивые кнопки управления',
bullets: [
'Непрерывное воспроизведение при открытии на весь экран: видео больше не останавливается самопроизвольно при входе в полноэкранный режим или смене ориентации устройства.',
'Корректный статус воспроизведения: устранен сброс кнопки на «Пуск» при переходе в полный экран — видео продолжает воспроизведение без ложных остановок.',
'Мгновенный отклик кнопок «Пуск/Пауза» и перемотки: жесты управления поверхностью (двойной тап, смахивание громкости) перемещены в фоновый слой, исключая перехват и отмену нажатий по кнопкам управления.',
'Синхронизация состояния при сворачивании: плеер точно запоминает состояние паузы/воспроизведения при выходе из полноэкранного режима обратно в пост.',
],
),
LunarisChange(
version: '3.1.7',
title: 'Устранение критического сбоя при открытии видеопоста (SIGSEGV в libmpv)',
bullets: [
'Устранение нативного вылета: полностью удалены небезопасные прямые FFI-вызовы setProperty к mpv, приводившие к немедленному падению приложения на Android при инициализации видео.',
'Безопасная конфигурация декодирования: перевод настроек аппаратного ускорения и фоллбэка кодеков на официальный типобезопасный VideoControllerConfiguration (media_kit_video).',
'Надежный фоллбэк при редких ошибках кодека: при несовместимости аппаратного декодера плеер бесшовно переключается на программный FFmpeg-декодер без риска краша.',
],
),
LunarisChange(
version: '3.1.6',
title: 'Надежный полноэкранный плеер, сохранение провайдеров в поиске, громкость и устранение ошибки кодека',
bullets: [
'Полноэкранный плеер — отзывчивая кнопка Пуск/Пауза: центральная кнопка управления воспроизведением полностью переработана на непроницаемый GestureDetector со сквиркл-откликом, гарантируя мгновенное срабатывание без перехвата внешними жестами.',
'Сохранение источников при нажатии на крестик в поиске: клик по кнопке сброса в строке поиска теперь очищает только поисковый запрос и теги, никогда не сбрасывая выбранные источники до «Все».',
'Безупречное сохранение громкости: громкость видеоплеера корректно инициализируется из настроек, сохраняется при регулировках жестом и переходе между постами, не сбрасываясь на 100% при открытии нового видео и перезапуске приложения.',
'Автоматический fallback для ошибки Could not open codec: видеоплеер получил безопасные профили декодирования и автопереключение на программный лавк-декодер (FFmpeg software fallback) при редких сбоях аппаратного ускорения.',
],
),
LunarisChange(
version: '3.1.5',
title: 'Сохранение громкости видео, исправление полноэкранного плеера, фильтрации и удобства комментариев',
bullets: [
'Сохранение уровня громкости (Persistent Volume): выбранная громкость видеоплеера теперь сохраняется при свайп-регулировке и переключениях между видео и сохраняется даже после перезапуска приложения.',
'Исправление кнопок в полноэкранном режиме: кнопки паузы/воспроизведения и быстрой перемотки на ±10 секунд в центре экрана теперь работают мгновенно и надежно с анимацией визуального отклика (Seek Ripple).',
'Сохранение выбранных источников при очистке тегов: удаление всех тегов в строке поиска больше не сбрасывает выбранные провайдеры до значения «Все», сохраняя ваши активные источники.',
'Плавная строка поиска: при выборе тега из подсказок поле ввода больше не сдвигается слишком далеко в сторону, оставляя тег и курсор в поле зрения.',
'Удобный доступ к комментариям в посте: увеличен отступ снизу в деталях поста и расширена зона клика блока комментариев, позволяя комфортно прокрутить их выше системных жестов навигации.',
],
),
LunarisChange(
version: '3.1.4',
title: 'Оптимизация видеоплеера — адаптивная высота и идеальное прилегание полосы воспроизведения',
bullets: [
'Устранение зазора под видео: контейнер плеера на мобильных устройствах и ПК теперь динамически подстраивается под пропорции видео (aspect ratio) вместо жестко фиксированной высоты 62% экрана, устраняя огромные пустые черные полосы сверху и снизу.',
'Точное позиционирование полосы воспроизведения: исправлен отступ снизу и ложное наложение системных insets на неполноэкранный плеер в карточке поста — ползунок воспроизведения, таймкоды и кнопка фуллскрина теперь аккуратно прилегают к нижнему краю видео без зависания в воздухе.',
'Компактные элементы управления: выровнены буферный трек и слайдер прокрутки, оптимизирован градиент затенения для максимальной видимости и удобства управления.',
],
),
LunarisChange(
version: '3.1.3',
title: 'iPhone Liquid Glass — Источники, Проверка сети и Навигация назад по вкладкам',
bullets: [
'Возврат назад по вкладкам (Tab Back Navigation): реализован стек истории переходов между разделами в AppShell — теперь при нажатии кнопки «Назад» или системного жеста происходит возврат к ранее открытым вкладкам и подразделам вместо случайного закрытия приложения.',
'Liquid Glass редизайн списка источников (Providers): стеклянные карточки провайдеров с красивыми сквиркл-иконками движков (Gelbooru, Rule34, Danbooru, e621, Yande.re, Paheal, Kemono), переключателями активности, инфо-бейджами приоритета и зеркальными кнопками управления.',
'Liquid Glass редизайн редактирования и создания источников (Edit / New Provider): секционные стеклянные карточки с градиентными бейджами, полоса быстрых пресетов для мгновенного заполнения URL и типа API, безопасный ввод API-ключей и наглядные подсказки.',
'Liquid Glass редизайн проверки состояния источников (Provider Check): карточка общих метрик сети (онлайн/офлайн, средний пинг), раскрывающиеся аккордеоны детальной диагностики, живые светодиодные LED-индикаторы статуса и кнопка одновременной проверки всех провайдеров.',
],
),
LunarisChange(
version: '3.1.2',
title: 'Оптимизация производительности: устранение лагов при скролле к тегам',
bullets: [
'Устранение лагов при прокрутке тегов: полностью ликвидирован тяжелый GPU-оверхед BackdropFilter на повторяющихся чипах тегов, вызывавший просадки FPS и микрофризы при скролле постов с десятками и сотнями тегов.',
'Высокопроизводительный стеклянный стиль чипов (TagChip): чипы переведены на эффективные аппаратные альфа-слои и зеркальные контуры без потери премиального неонового Liquid Glass вида и цветных индикаторов категорий.',
'Облегчение контейнеров блока тегов: на мобильных и десктоп экранах контейнеры тегов оптимизированы для мгновенного плавного 120 FPS скроллинга.',
'Интеллектуальный лимит начального отображения: оптимизировано первоначальное количество отображаемых тегов в огромных категориях с удобной кнопкой быстрого раскрытия.',
],
),
LunarisChange(
version: '3.1.1',
title: 'Деление тегов по стилю e621/Gelbooru/Rule34 и исправление поиска тегов со скобками',
bullets: [
'Цветное деление тегов по категориям (e621, Rule34, Gelbooru): теги авторов (Artist) подсвечиваются кораллово-красным, персонажи (Character) — мятно-зелёным, серии/копирайты (Copyright) — пурпурным, виды (Species) — янтарно-оранжевым, мета (Meta) — ледяным голубым, а общие теги (General) — нейтральным стилем.',
'Liquid Glass чипы тегов: компоненты TagChip получили полупрозрачный фон с BackdropFilter размытием, цветной светодиодный индикатор-точку со свечением и зеркальный контур.',
'Индикаторы в заголовках категорий: заголовки блоков тегов дополнены цветными точками категорий со свечением и стильными капсулами счётчиков.',
'Исправление поиска тегов со скобками: исправлена проблема, из-за которой теги с круглыми скобками (например, tyson_(password), touhou_(series)) очищались от скобок при поиске и не находили постов в ленте.',
'Поддержка скобок в подсказках и локальном кэше: автодополнение теперь корректно выдает теги со скобками, фильтруя только внешние скобки группировки and-веток.',
'Liquid Glass оформление блока тегов в детальном просмотре поста на мобильных и десктоп устройствах.',
],
),
LunarisChange(
version: '3.1.0',
title: 'iPhone Liquid Glass — Поиск, Избранное, История и исправление доступности',
bullets: [
'Liquid Glass редизайн разделов «Поиск», «Избранное» и «История»: матовые стеклянные карточки (BackdropFilter blur), полупрозрачные градиенты, зеркальные контуры и сквиркл-бейджи иконок в стиле iOS.',
'Исправление шпаргалки по поиску: увеличен нижний отступ прокрутки во всех списках и сетках до 140px + safe area, благодаря чему блок операторов и шпаргалка по поиску больше не перекрываются парящей навигационной панелью и легко нажимаются.',
'Исправление модального окна проверки обновлений: панель с выбором источников (GitHub и Gitea) открывается через корневой навигатор поверх всей навигации с безопасным отступом снизу, обеспечивая беспрепятственный доступ к обеим кнопкам.',
'Тактильный отклик и стеклянные пилюли: быстрые операторы, категории, недавние запросы, фильтры медиа и переключатели разделов получили матовое оформление и вибрационный отклик Haptic Feedback.',
],
),
LunarisChange(
version: '3.0.9',
title: 'Коррекция позиции кнопки настроек и отображения кнопок JSON и бэкапа',
bullets: [
'Оптимальная позиция кнопки настроек: парящая стеклянная кнопка опущена прямо к нижней навигационной панели, без избыточного завышения над карточками контента.',
'Полная видимость кнопок JSON и бэкапа: добавлен увеличенный нижний отступ прокрутки в настройках, чтобы панель навигации не перекрывала кнопки при скролле до конца.',
'Улучшенный дизайн и сетка кнопок экспорта/импорта: кнопки бэкапа и JSON организованы в симметричные аккуратные строки с яркими акцентными бейджами.',
],
),
LunarisChange(
version: '3.0.8',
title: 'iPhone Liquid Glass — раздел «Настройки» и парящая стеклянная кнопка',
bullets: [
'Парящая стеклянная кнопка настроек (Liquid Glass Floating Button): круглая сфера из матового стекла с эффектом BackdropFilter blur, зеркальным радиальным градиентом, подсветкой ободка, пружинящей анимацией масштабирования и вращения при нажатии.',
'Карточки настроек в стиле Liquid Glass (1:1 iOS): группы настроек переработаны в матовые стеклянные карточки с мягким градиентом, зеркальной рамкой и многослойными тенями глубины.',
'Иконки разделов и пунктов в стиле iOS: яркие сквиркл-бейджи с акцентными градиентами, мягким свечением и четкими белыми иконками, как в нативных настройках iPhone.',
'Стеклянная быстрая навигация по категориям: зафиксированная панель категорий с размытием фона и тактильным откликом при переключении разделов.',
],
),
LunarisChange(
version: '3.0.7',
title: 'Liquid Glass Navigation Bar — парящая стеклянная панель и анимированная пилюля',
bullets: [
'Парящая панель Liquid Glass: нижняя панель навигации преобразована в парящий стеклянный док со скруглением, полупрозрачным градиентом и размытием фона (BackdropFilter blur).',
'Плавающая пилюля-индикатор (Liquid Pill): плавный анимированный бегунок перетекает под активную вкладку со сглаженной пружинящей физикой (easeOutBack).',
'Микроанимации нажатия и тактильный отклик: иконки мягко сжимаются при тапе и отпружинивают назад с легким тактильным виброоткликом (Haptic Feedback).',
'Глубина контента: контент ленты, поиска и галереи плавно просвечивает и размывается под стеклянной панелью при прокрутке.',
],
),
LunarisChange(
version: '3.0.6',
title: 'Улучшение недавних запросов и отображения тегов',
bullets: [
'Полная видимость тегов и запросов: сняты тесные ограничения ширины (140px), теги и поисковые запросы теперь отображаются целиком без усечения.',
'Устранение дубликатов в истории: автоматическая дедупликация поисковых запросов в базе данных и интерфейсе. Устранены повторяющиеся пары запросов с пустыми счетчиками.',
'Исправление заголовка карточки поиска: заголовок «Недавние запросы» и счетчик больше не обрезаются на экранах смартфонов.',
'Удобное удаление: увеличенная область нажатия для кнопки удаления (крестика) предотвращает случайные нажатия на сам запрос.',
],
),
LunarisChange( LunarisChange(
version: '3.0.5', version: '3.0.5',
title: 'Интерактивные ссылки на соцсети и авторов в объявлениях и описаниях', title: 'Интерактивные ссылки на соцсети и авторов в объявлениях и описаниях',
+10 -1
View File
@@ -169,7 +169,16 @@ class ProviderManager {
for (final raw in rawTags) { for (final raw in rawTags) {
var token = raw.trim(); var token = raw.trim();
token = token.replaceAll(RegExp(r'^[\(\)]+|[\(\)]+$'), '').trim(); if (token.isEmpty) continue;
// Only strip parentheses if they are grouping delimiters (unbalanced in the token, e.g. '(cat' or 'dog)')
// but preserve tags that have internal paired parentheses like 'tyson_(password)'.
if (token.startsWith('(') && !token.contains(')')) {
token = token.substring(1).trim();
}
if (token.endsWith(')') && !token.contains('(')) {
token = token.substring(0, token.length - 1).trim();
}
if (token.isEmpty) continue; if (token.isEmpty) continue;
if (token.toLowerCase() == 'and') { if (token.toLowerCase() == 'and') {
@@ -12,6 +12,15 @@ class SearchRepository {
Future<Result<void>> save(SearchHistory history, {int maxItems = 500}) { Future<Result<void>> save(SearchHistory history, {int maxItems = 500}) {
return _databaseService.safeWrite((isar) async { return _databaseService.safeWrite((isar) async {
final norm = history.query.trim().toLowerCase();
// Remove any existing duplicate records with same query
final all = await isar.searchHistoryEntitys.where().findAll();
for (final item in all) {
if (item.query.trim().toLowerCase() == norm) {
await isar.searchHistoryEntitys.delete(item.isarId);
}
}
await isar.searchHistoryEntitys.put( await isar.searchHistoryEntitys.put(
SearchHistoryEntity() SearchHistoryEntity()
..historyId = history.id ..historyId = history.id
@@ -42,13 +51,40 @@ class SearchRepository {
return _databaseService.safeRead((isar) async { return _databaseService.safeRead((isar) async {
final items = await isar.searchHistoryEntitys.where().findAll(); final items = await isar.searchHistoryEntitys.where().findAll();
items.sort((a, b) => b.searchedAt.compareTo(a.searchedAt)); items.sort((a, b) => b.searchedAt.compareTo(a.searchedAt));
final limited = limit == null ? items : items.take(limit);
final seen = <String>{};
final deduplicated = <SearchHistoryEntity>[];
for (final item in items) {
final key = item.query.trim().toLowerCase();
if (key.isEmpty) continue;
if (seen.add(key)) {
deduplicated.add(item);
}
}
final limited = limit == null ? deduplicated : deduplicated.take(limit);
return limited.map((entity) => entity.toModel()).toList(); return limited.map((entity) => entity.toModel()).toList();
}); });
} }
Future<Result<bool>> delete(String historyId) { Future<Result<bool>> delete(String historyId) {
return _databaseService.safeWrite((isar) async { return _databaseService.safeWrite((isar) async {
final target = await isar.searchHistoryEntitys
.where()
.filter()
.historyIdEqualTo(historyId)
.findFirst();
if (target != null) {
final norm = target.query.trim().toLowerCase();
final all = await isar.searchHistoryEntitys.where().findAll();
for (final item in all) {
if (item.query.trim().toLowerCase() == norm ||
item.historyId == historyId) {
await isar.searchHistoryEntitys.delete(item.isarId);
}
}
return true;
}
return await isar.searchHistoryEntitys.deleteByHistoryId(historyId); return await isar.searchHistoryEntitys.deleteByHistoryId(historyId);
}); });
} }
+1 -4
View File
@@ -21,10 +21,7 @@ class SearchService {
TagCacheService? get tagCacheService => _tagCacheService; TagCacheService? get tagCacheService => _tagCacheService;
static String sanitizeToken(String raw) { static String sanitizeToken(String raw) {
return raw return raw.trim().toLowerCase();
.replaceAll(RegExp(r'^[\(\)]+|[\(\)]+$'), '')
.trim()
.toLowerCase();
} }
List<String> parseTags(String query) { List<String> parseTags(String query) {
@@ -39,6 +39,7 @@ class AppSettings {
required this.motionRefreshMode, required this.motionRefreshMode,
required this.autoBatterySaver60Hz, required this.autoBatterySaver60Hz,
required this.videoPlayerMuted, required this.videoPlayerMuted,
this.videoPlayerVolume = 100.0,
required this.videoPlayerHalfVolume, required this.videoPlayerHalfVolume,
required this.videoPlayerLoop, required this.videoPlayerLoop,
required this.videoPlayerCover, required this.videoPlayerCover,
@@ -94,6 +95,7 @@ class AppSettings {
final String motionRefreshMode; final String motionRefreshMode;
final bool autoBatterySaver60Hz; final bool autoBatterySaver60Hz;
final bool videoPlayerMuted; final bool videoPlayerMuted;
final double videoPlayerVolume;
final bool videoPlayerHalfVolume; final bool videoPlayerHalfVolume;
final bool videoPlayerLoop; final bool videoPlayerLoop;
final bool videoPlayerCover; final bool videoPlayerCover;
@@ -146,6 +148,7 @@ class AppSettings {
motionRefreshMode: 'auto', motionRefreshMode: 'auto',
autoBatterySaver60Hz: true, autoBatterySaver60Hz: true,
videoPlayerMuted: false, videoPlayerMuted: false,
videoPlayerVolume: 100.0,
videoPlayerHalfVolume: false, videoPlayerHalfVolume: false,
videoPlayerLoop: false, videoPlayerLoop: false,
videoPlayerCover: false, videoPlayerCover: false,
@@ -191,6 +194,7 @@ class AppSettings {
String? motionRefreshMode, String? motionRefreshMode,
bool? autoBatterySaver60Hz, bool? autoBatterySaver60Hz,
bool? videoPlayerMuted, bool? videoPlayerMuted,
double? videoPlayerVolume,
bool? videoPlayerHalfVolume, bool? videoPlayerHalfVolume,
bool? videoPlayerLoop, bool? videoPlayerLoop,
bool? videoPlayerCover, bool? videoPlayerCover,
@@ -252,6 +256,7 @@ class AppSettings {
motionRefreshMode: motionRefreshMode ?? this.motionRefreshMode, motionRefreshMode: motionRefreshMode ?? this.motionRefreshMode,
autoBatterySaver60Hz: autoBatterySaver60Hz ?? this.autoBatterySaver60Hz, autoBatterySaver60Hz: autoBatterySaver60Hz ?? this.autoBatterySaver60Hz,
videoPlayerMuted: videoPlayerMuted ?? this.videoPlayerMuted, videoPlayerMuted: videoPlayerMuted ?? this.videoPlayerMuted,
videoPlayerVolume: videoPlayerVolume ?? this.videoPlayerVolume,
videoPlayerHalfVolume: videoPlayerHalfVolume:
videoPlayerHalfVolume ?? this.videoPlayerHalfVolume, videoPlayerHalfVolume ?? this.videoPlayerHalfVolume,
videoPlayerLoop: videoPlayerLoop ?? this.videoPlayerLoop, videoPlayerLoop: videoPlayerLoop ?? this.videoPlayerLoop,
@@ -309,6 +314,7 @@ class AppSettings {
'motionRefreshMode': motionRefreshMode, 'motionRefreshMode': motionRefreshMode,
'autoBatterySaver60Hz': autoBatterySaver60Hz, 'autoBatterySaver60Hz': autoBatterySaver60Hz,
'videoPlayerMuted': videoPlayerMuted, 'videoPlayerMuted': videoPlayerMuted,
'videoPlayerVolume': videoPlayerVolume,
'videoPlayerHalfVolume': videoPlayerHalfVolume, 'videoPlayerHalfVolume': videoPlayerHalfVolume,
'videoPlayerLoop': videoPlayerLoop, 'videoPlayerLoop': videoPlayerLoop,
'videoPlayerCover': videoPlayerCover, 'videoPlayerCover': videoPlayerCover,
@@ -392,6 +398,8 @@ class AppSettings {
defaults.autoBatterySaver60Hz, defaults.autoBatterySaver60Hz,
videoPlayerMuted: videoPlayerMuted:
(json['videoPlayerMuted'] as bool?) ?? defaults.videoPlayerMuted, (json['videoPlayerMuted'] as bool?) ?? defaults.videoPlayerMuted,
videoPlayerVolume: (json['videoPlayerVolume'] as num?)?.toDouble() ??
defaults.videoPlayerVolume,
videoPlayerHalfVolume: (json['videoPlayerHalfVolume'] as bool?) ?? videoPlayerHalfVolume: (json['videoPlayerHalfVolume'] as bool?) ??
defaults.videoPlayerHalfVolume, defaults.videoPlayerHalfVolume,
videoPlayerLoop: videoPlayerLoop:
@@ -601,6 +609,17 @@ class SettingsService {
return updateSettings(settings.copyWith(videoPlaybackPositions: positions)); return updateSettings(settings.copyWith(videoPlaybackPositions: positions));
} }
Future<Result<void>> setVideoPlayerVolume(double volume) async {
final result = await getSettings();
if (result is Error<AppSettings>) return Error(result.failure);
final settings = (result as Success<AppSettings>).data;
final clamped = volume.clamp(0.0, 100.0);
if ((settings.videoPlayerVolume - clamped).abs() < 0.01) {
return const Success(null);
}
return updateSettings(settings.copyWith(videoPlayerVolume: clamped));
}
Future<Result<void>> appendDiagnosticLog(String message) async { Future<Result<void>> appendDiagnosticLog(String message) async {
final result = await getSettings(); final result = await getSettings();
if (result is Error<AppSettings>) return Error(result.failure); if (result is Error<AppSettings>) return Error(result.failure);
+5 -4
View File
@@ -66,10 +66,11 @@ class TagCacheService {
int limit = 16, int limit = 16,
Iterable<String>? priorityTags, Iterable<String>? priorityTags,
}) { }) {
final cleanPrefix = prefix var cleanPrefix = prefix.trim().toLowerCase();
.replaceAll(RegExp(r'^[\(\)]+|[\(\)]+$'), '') // If the prefix has an unbalanced opening parenthesis at the start (e.g. '(cat'), strip it
.trim() if (cleanPrefix.startsWith('(') && !cleanPrefix.contains(')')) {
.toLowerCase(); cleanPrefix = cleanPrefix.substring(1).trim();
}
if (cleanPrefix.isEmpty) return const []; if (cleanPrefix.isEmpty) return const [];
final prioritySet = priorityTags final prioritySet = priorityTags
@@ -1,5 +1,8 @@
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
@@ -176,82 +179,154 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
// Search input bar if active // Search input bar if active
if (_isSearching) if (_isSearching)
Padding( Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 4), padding: const EdgeInsets.fromLTRB(16, 6, 16, 6),
child: TextField( child: ClipRRect(
controller: _searchController, borderRadius: BorderRadius.circular(18),
autofocus: true, child: BackdropFilter(
decoration: InputDecoration( filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16),
hintText: isRu child: Container(
? 'Поиск по тегам и авторам...' decoration: BoxDecoration(
: 'Search by tags and artists...', color: Theme.of(context).brightness == Brightness.dark
prefixIcon: const Icon(Icons.search_rounded), ? Theme.of(context).colorScheme.surfaceContainerHigh
suffixIcon: _searchQuery.isNotEmpty .withValues(alpha: 0.55)
? IconButton( : Colors.white.withValues(alpha: 0.80),
icon: const Icon(Icons.clear_rounded), borderRadius: BorderRadius.circular(18),
onPressed: () { border: Border.all(
_searchController.clear(); color: Theme.of(context).brightness == Brightness.dark
setState(() => _searchQuery = ''); ? Colors.white.withValues(alpha: 0.14)
}, : Colors.white.withValues(alpha: 0.85),
) width: 1.1,
: null, ),
isDense: true, ),
filled: true, child: TextField(
contentPadding: const EdgeInsets.symmetric( controller: _searchController,
horizontal: 16, autofocus: true,
vertical: 10, decoration: InputDecoration(
), hintText: isRu
border: OutlineInputBorder( ? 'Поиск по тегам и авторам...'
borderRadius: BorderRadius.circular(16), : 'Search by tags and artists...',
borderSide: BorderSide.none, prefixIcon: const Icon(Icons.search_rounded),
suffixIcon: _searchQuery.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear_rounded),
onPressed: () {
HapticFeedback.lightImpact();
_searchController.clear();
setState(() => _searchQuery = '');
},
)
: null,
isDense: true,
filled: false,
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 10,
),
border: InputBorder.none,
),
onChanged: (val) =>
setState(() => _searchQuery = val.trim()),
),
), ),
), ),
onChanged: (val) => setState(() => _searchQuery = val.trim()),
), ),
), ),
// Navigation Tabs // Navigation Tabs with Liquid Glass container
Padding( Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 6), padding: const EdgeInsets.fromLTRB(16, 6, 16, 6),
child: SizedBox( child: Container(
width: double.infinity, decoration: BoxDecoration(
child: SegmentedButton<int>( borderRadius: BorderRadius.circular(22),
showSelectedIcon: false, boxShadow: [
segments: [ BoxShadow(
ButtonSegment( color: Colors.black.withValues(
value: 0, alpha: Theme.of(context).brightness == Brightness.dark
icon: const Icon(Icons.favorite_rounded, size: 18), ? 0.20
label: Text( : 0.04,
'${isRu ? 'Все' : 'All'} (${allPosts.length})',
style: const TextStyle(fontSize: 12),
overflow: TextOverflow.ellipsis,
),
),
ButtonSegment(
value: 1,
icon: const Icon(Icons.offline_pin_rounded, size: 18),
label: Text(
'${isRu ? 'Офлайн' : 'Offline'} (${offlinePosts.length})',
style: const TextStyle(fontSize: 12),
overflow: TextOverflow.ellipsis,
),
),
ButtonSegment(
value: 2,
icon: const Icon(Icons.groups_rounded, size: 18),
label: Text(
'${isRu ? 'Авторы' : 'Artists'} (${artistGroups.length})',
style: const TextStyle(fontSize: 12),
overflow: TextOverflow.ellipsis,
), ),
blurRadius: 10,
offset: const Offset(0, 2),
), ),
], ],
selected: {_tabIndex}, ),
onSelectionChanged: (value) { child: ClipRRect(
setState(() { borderRadius: BorderRadius.circular(22),
_tabIndex = value.first; child: BackdropFilter(
_selectedArtist = null; filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16),
}); child: Container(
}, decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
color: Theme.of(context).brightness == Brightness.dark
? Theme.of(context)
.colorScheme
.surfaceContainerHigh
.withValues(alpha: 0.50)
: Colors.white.withValues(alpha: 0.72),
border: Border.all(
color: Theme.of(context).brightness == Brightness.dark
? Colors.white.withValues(alpha: 0.12)
: Colors.white.withValues(alpha: 0.85),
width: 1.1,
),
),
child: SizedBox(
width: double.infinity,
child: SegmentedButton<int>(
showSelectedIcon: false,
style: ButtonStyle(
visualDensity: VisualDensity.compact,
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
),
segments: [
ButtonSegment(
value: 0,
icon: const Icon(Icons.favorite_rounded, size: 18),
label: Text(
'${isRu ? 'Все' : 'All'} (${allPosts.length})',
style: const TextStyle(
fontSize: 12, fontWeight: FontWeight.w600),
overflow: TextOverflow.ellipsis,
),
),
ButtonSegment(
value: 1,
icon: const Icon(Icons.offline_pin_rounded,
size: 18),
label: Text(
'${isRu ? 'Офлайн' : 'Offline'} (${offlinePosts.length})',
style: const TextStyle(
fontSize: 12, fontWeight: FontWeight.w600),
overflow: TextOverflow.ellipsis,
),
),
ButtonSegment(
value: 2,
icon: const Icon(Icons.groups_rounded, size: 18),
label: Text(
'${isRu ? 'Авторы' : 'Artists'} (${artistGroups.length})',
style: const TextStyle(
fontSize: 12, fontWeight: FontWeight.w600),
overflow: TextOverflow.ellipsis,
),
),
],
selected: {_tabIndex},
onSelectionChanged: (value) {
HapticFeedback.selectionClick();
setState(() {
_tabIndex = value.first;
_selectedArtist = null;
});
},
),
),
),
),
), ),
), ),
), ),
@@ -265,9 +340,12 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
FilterChip( FilterChip(
label: Text(isRu ? 'Все' : 'All'), label: Text(isRu ? 'Все' : 'All'),
selected: _mediaFilter == FavoriteMediaType.all, selected: _mediaFilter == FavoriteMediaType.all,
onSelected: (_) => setState( onSelected: (_) {
() => _mediaFilter = FavoriteMediaType.all, HapticFeedback.selectionClick();
), setState(
() => _mediaFilter = FavoriteMediaType.all,
);
},
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
@@ -275,9 +353,12 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
avatar: const Icon(Icons.videocam_rounded, size: 16), avatar: const Icon(Icons.videocam_rounded, size: 16),
label: Text(isRu ? 'Видео' : 'Videos'), label: Text(isRu ? 'Видео' : 'Videos'),
selected: _mediaFilter == FavoriteMediaType.video, selected: _mediaFilter == FavoriteMediaType.video,
onSelected: (_) => setState( onSelected: (_) {
() => _mediaFilter = FavoriteMediaType.video, HapticFeedback.selectionClick();
), setState(
() => _mediaFilter = FavoriteMediaType.video,
);
},
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
@@ -285,9 +366,12 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
avatar: const Icon(Icons.image_rounded, size: 16), avatar: const Icon(Icons.image_rounded, size: 16),
label: Text(isRu ? 'Фото' : 'Images'), label: Text(isRu ? 'Фото' : 'Images'),
selected: _mediaFilter == FavoriteMediaType.image, selected: _mediaFilter == FavoriteMediaType.image,
onSelected: (_) => setState( onSelected: (_) {
() => _mediaFilter = FavoriteMediaType.image, HapticFeedback.selectionClick();
), setState(
() => _mediaFilter = FavoriteMediaType.image,
);
},
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
), ),
], ],
@@ -490,31 +574,40 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
}) { }) {
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
return Container( return _FavoritesLiquidCard(
margin: const EdgeInsets.fromLTRB(16, 4, 16, 8), margin: const EdgeInsets.fromLTRB(16, 4, 16, 8),
padding: const EdgeInsets.all(14), padding: const EdgeInsets.all(14),
decoration: BoxDecoration( glowColor: scheme.primary,
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: scheme.outlineVariant.withValues(alpha: 0.35),
),
),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Row( Row(
children: [ children: [
Container( Container(
padding: const EdgeInsets.all(10), width: 40,
height: 40,
decoration: BoxDecoration( decoration: BoxDecoration(
color: scheme.primaryContainer.withValues(alpha: 0.7), gradient: LinearGradient(
colors: [
scheme.primary,
scheme.primary.withValues(alpha: 0.85),
],
),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: scheme.primary.withValues(alpha: 0.35),
blurRadius: 7,
offset: const Offset(0, 2.5),
),
],
), ),
child: Icon( child: const Center(
Icons.offline_pin_rounded, child: Icon(
color: scheme.onPrimaryContainer, Icons.offline_pin_rounded,
size: 22, color: Colors.white,
size: 22,
),
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
@@ -526,6 +619,7 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
'$downloadedCount ${isRu ? 'из' : 'of'} $totalCount ${isRu ? 'офлайн' : 'saved'}', '$downloadedCount ${isRu ? 'из' : 'of'} $totalCount ${isRu ? 'офлайн' : 'saved'}',
style: Theme.of(context).textTheme.titleSmall?.copyWith( style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
letterSpacing: -0.2,
), ),
), ),
const SizedBox(height: 2), const SizedBox(height: 2),
@@ -553,21 +647,22 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
if (pendingCount > 0) if (pendingCount > 0)
FilledButton.tonalIcon( FilledButton.tonalIcon(
onPressed: () async { onPressed: () async {
HapticFeedback.mediumImpact();
final dm = ref.read(downloadManagerServiceProvider); final dm = ref.read(downloadManagerServiceProvider);
for (final p in pendingPosts) { for (final p in pendingPosts) {
await dm.start(p); await dm.start(p);
} }
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text( content: Text(
isRu isRu
? 'В очередь загрузки добавлено: $pendingCount' ? 'В очередь загрузки добавлено: $pendingCount'
: 'Queued $pendingCount downloads', : 'Queued $pendingCount downloads',
),
behavior: SnackBarBehavior.floating,
), ),
); behavior: SnackBarBehavior.floating,
),
);
}, },
icon: const Icon(Icons.download_rounded, size: 16), icon: const Icon(Icons.download_rounded, size: 16),
label: Text( label: Text(
@@ -594,7 +689,7 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
vertical: 6, vertical: 6,
), ),
decoration: BoxDecoration( decoration: BoxDecoration(
color: scheme.secondaryContainer.withValues(alpha: 0.5), color: scheme.primary.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
child: Row( child: Row(
@@ -610,8 +705,8 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
isRu ? 'Всё готово' : 'Synced', isRu ? 'Всё готово' : 'Synced',
style: style:
Theme.of(context).textTheme.labelSmall?.copyWith( Theme.of(context).textTheme.labelSmall?.copyWith(
color: scheme.onSecondaryContainer, color: scheme.primary,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w700,
), ),
), ),
], ],
@@ -666,27 +761,36 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
ChoiceChip( ChoiceChip(
label: Text(isRu ? 'По дате' : 'Date'), label: Text(isRu ? 'По дате' : 'Date'),
selected: _offlineSort == OfflineSortOption.dateAddedDesc, selected: _offlineSort == OfflineSortOption.dateAddedDesc,
onSelected: (_) => setState( onSelected: (_) {
() => _offlineSort = OfflineSortOption.dateAddedDesc, HapticFeedback.selectionClick();
), setState(
() => _offlineSort = OfflineSortOption.dateAddedDesc,
);
},
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
), ),
const SizedBox(width: 6), const SizedBox(width: 6),
ChoiceChip( ChoiceChip(
label: Text(isRu ? 'По размеру' : 'Size'), label: Text(isRu ? 'По размеру' : 'Size'),
selected: _offlineSort == OfflineSortOption.sizeDesc, selected: _offlineSort == OfflineSortOption.sizeDesc,
onSelected: (_) => setState( onSelected: (_) {
() => _offlineSort = OfflineSortOption.sizeDesc, HapticFeedback.selectionClick();
), setState(
() => _offlineSort = OfflineSortOption.sizeDesc,
);
},
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
), ),
const SizedBox(width: 6), const SizedBox(width: 6),
ChoiceChip( ChoiceChip(
label: Text(isRu ? 'По автору' : 'Artist'), label: Text(isRu ? 'По автору' : 'Artist'),
selected: _offlineSort == OfflineSortOption.artist, selected: _offlineSort == OfflineSortOption.artist,
onSelected: (_) => setState( onSelected: (_) {
() => _offlineSort = OfflineSortOption.artist, HapticFeedback.selectionClick();
), setState(
() => _offlineSort = OfflineSortOption.artist,
);
},
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
), ),
], ],
@@ -712,38 +816,50 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
return Column( return Column(
children: [ children: [
// Artist Header Banner // Artist Header Banner (Liquid Glass)
Container( _FavoritesLiquidCard(
margin: const EdgeInsets.fromLTRB(16, 4, 16, 8), margin: const EdgeInsets.fromLTRB(16, 4, 16, 8),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.surfaceContainerLow,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: Theme.of(context)
.colorScheme
.outlineVariant
.withValues(alpha: 0.3),
),
),
child: Row( child: Row(
children: [ children: [
IconButton( IconButton(
onPressed: () => setState(() => _selectedArtist = null), onPressed: () {
HapticFeedback.selectionClick();
setState(() => _selectedArtist = null);
},
icon: const Icon(Icons.arrow_back_rounded), icon: const Icon(Icons.arrow_back_rounded),
tooltip: isRu ? 'Все авторы' : 'All artists', tooltip: isRu ? 'Все авторы' : 'All artists',
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
CircleAvatar( Container(
radius: 18, width: 38,
backgroundColor: Theme.of(context).colorScheme.primaryContainer, height: 38,
child: Text( decoration: BoxDecoration(
selected.isNotEmpty ? selected[0].toUpperCase() : '?', gradient: LinearGradient(
style: TextStyle( colors: [
fontWeight: FontWeight.bold, Theme.of(context).colorScheme.primary,
color: Theme.of(context).colorScheme.onPrimaryContainer, Theme.of(context).colorScheme.tertiary,
],
),
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Theme.of(context)
.colorScheme
.primary
.withValues(alpha: 0.35),
blurRadius: 6,
offset: const Offset(0, 2),
),
],
),
child: Center(
child: Text(
selected.isNotEmpty ? selected[0].toUpperCase() : '?',
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
),
), ),
), ),
), ),
@@ -756,6 +872,7 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
selected, selected,
style: Theme.of(context).textTheme.titleMedium?.copyWith( style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
letterSpacing: -0.2,
), ),
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
@@ -776,6 +893,7 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
), ),
onPressed: () { onPressed: () {
HapticFeedback.selectionClick();
context.push('/search?q=${Uri.encodeComponent('artist:$selected')}'); context.push('/search?q=${Uri.encodeComponent('artist:$selected')}');
}, },
icon: const Icon(Icons.search_rounded, size: 16), icon: const Icon(Icons.search_rounded, size: 16),
@@ -808,7 +926,9 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
} }
return ListView.separated( return ListView.separated(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), // Extended bottom padding so the last artist cards scroll comfortably above the floating dock
padding: EdgeInsets.fromLTRB(
16, 8, 16, 140 + MediaQuery.paddingOf(context).bottom),
itemCount: entries.length, itemCount: entries.length,
separatorBuilder: (_, __) => const SizedBox(height: 10), separatorBuilder: (_, __) => const SizedBox(height: 10),
itemBuilder: (context, index) { itemBuilder: (context, index) {
@@ -863,6 +983,83 @@ class _FavoritesScreenState extends ConsumerState<FavoritesScreen> {
} }
} }
class _FavoritesLiquidCard extends StatelessWidget {
const _FavoritesLiquidCard({
required this.child,
this.padding,
this.glowColor,
this.margin,
});
final Widget child;
final EdgeInsetsGeometry? padding;
final EdgeInsetsGeometry? margin;
final Color? glowColor;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final accent = glowColor ?? theme.colorScheme.primary;
return Container(
margin: margin,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
boxShadow: [
BoxShadow(
color: isDark
? Colors.black.withValues(alpha: 0.30)
: accent.withValues(alpha: 0.07),
blurRadius: 16,
offset: const Offset(0, 5),
spreadRadius: -2,
),
BoxShadow(
color: accent.withValues(alpha: isDark ? 0.05 : 0.02),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(22),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 18, sigmaY: 18),
child: Container(
padding: padding ?? const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: isDark
? [
theme.colorScheme.surfaceContainerHigh
.withValues(alpha: 0.60),
theme.colorScheme.surfaceContainerLow
.withValues(alpha: 0.38),
]
: [
Colors.white.withValues(alpha: 0.88),
Colors.white.withValues(alpha: 0.72),
],
),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.14)
: Colors.white.withValues(alpha: 0.85),
width: 1.2,
),
),
child: child,
),
),
),
);
}
}
class _ArtistCard extends StatelessWidget { class _ArtistCard extends StatelessWidget {
const _ArtistCard({ const _ArtistCard({
required this.artistName, required this.artistName,
@@ -881,123 +1078,182 @@ class _ArtistCard extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
final isDark = Theme.of(context).brightness == Brightness.dark;
return Card( return Container(
elevation: 0, decoration: BoxDecoration(
color: scheme.surfaceContainerLow, borderRadius: BorderRadius.circular(22),
shape: RoundedRectangleBorder( boxShadow: [
borderRadius: BorderRadius.circular(16), BoxShadow(
side: BorderSide( color: isDark
color: scheme.outlineVariant.withValues(alpha: 0.3), ? Colors.black.withValues(alpha: 0.28)
), : scheme.primary.withValues(alpha: 0.06),
blurRadius: 14,
offset: const Offset(0, 4),
spreadRadius: -2,
),
],
), ),
clipBehavior: Clip.antiAlias, child: ClipRRect(
child: InkWell( borderRadius: BorderRadius.circular(22),
onTap: onTap, child: BackdropFilter(
child: Padding( filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16),
padding: const EdgeInsets.all(12), child: Material(
child: Row( color: Colors.transparent,
children: [ child: InkWell(
// Artist Avatar borderRadius: BorderRadius.circular(22),
Container( onTap: () {
width: 48, HapticFeedback.selectionClick();
height: 48, onTap();
},
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
gradient: LinearGradient( gradient: LinearGradient(
colors: [
scheme.primaryContainer,
scheme.tertiaryContainer,
],
begin: Alignment.topLeft, begin: Alignment.topLeft,
end: Alignment.bottomRight, end: Alignment.bottomRight,
colors: isDark
? [
scheme.surfaceContainerHigh
.withValues(alpha: 0.58),
scheme.surfaceContainerLow
.withValues(alpha: 0.36),
]
: [
Colors.white.withValues(alpha: 0.88),
Colors.white.withValues(alpha: 0.72),
],
), ),
borderRadius: BorderRadius.circular(14), border: Border.all(
), color: isDark
child: Center( ? Colors.white.withValues(alpha: 0.13)
child: Text( : Colors.white.withValues(alpha: 0.85),
artistName.isNotEmpty ? artistName[0].toUpperCase() : '?', width: 1.1,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: scheme.onPrimaryContainer,
),
), ),
), ),
), child: Row(
const SizedBox(width: 12),
// Artist Name & Count
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( // Artist Squircle Avatar
artistName,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 2),
Container( Container(
padding: const EdgeInsets.symmetric( width: 48,
horizontal: 8, height: 48,
vertical: 2,
),
decoration: BoxDecoration( decoration: BoxDecoration(
color: scheme.secondaryContainer.withValues(alpha: 0.5), gradient: LinearGradient(
borderRadius: BorderRadius.circular(8), colors: [
scheme.primary,
scheme.tertiary,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(15),
boxShadow: [
BoxShadow(
color: scheme.primary.withValues(alpha: 0.35),
blurRadius: 8,
offset: const Offset(0, 2.5),
),
],
), ),
child: Text( child: Center(
'$postsCount ${isRu ? 'работ' : 'posts'}', child: Text(
style: Theme.of(context).textTheme.labelSmall?.copyWith( artistName.isNotEmpty ? artistName[0].toUpperCase() : '?',
color: scheme.onSecondaryContainer, style: const TextStyle(
fontWeight: FontWeight.w600, fontSize: 20,
), fontWeight: FontWeight.bold,
), color: Colors.white,
),
],
),
),
// Thumbnails preview
if (previewUrls.isNotEmpty) ...[
const SizedBox(width: 8),
Row(
children: [
for (final url in previewUrls)
Padding(
padding: const EdgeInsets.only(left: 4),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: 44,
height: 44,
child: CachedNetworkImage(
imageUrl: url,
fit: BoxFit.cover,
placeholder: (_, __) => Container(
color: scheme.surfaceContainerHighest,
),
errorWidget: (_, __, ___) => Container(
color: scheme.surfaceContainerHighest,
child: const Icon(
Icons.image_not_supported_rounded,
size: 16,
),
),
),
), ),
), ),
), ),
),
const SizedBox(width: 12),
// Artist Name & Count
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
artistName,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
letterSpacing: -0.2,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 3),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 2,
),
decoration: BoxDecoration(
color: scheme.primary.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'$postsCount ${isRu ? 'работ' : 'posts'}',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: scheme.primary,
fontWeight: FontWeight.w700,
),
),
),
],
),
),
// Thumbnails preview
if (previewUrls.isNotEmpty) ...[
const SizedBox(width: 8),
Row(
children: [
for (final url in previewUrls)
Padding(
padding: const EdgeInsets.only(left: 5),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
width: 44,
height: 44,
decoration: BoxDecoration(
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.10)
: scheme.outlineVariant.withValues(alpha: 0.25),
),
borderRadius: BorderRadius.circular(10),
),
child: CachedNetworkImage(
imageUrl: url,
fit: BoxFit.cover,
placeholder: (_, __) => Container(
color: scheme.surfaceContainerHighest,
),
errorWidget: (_, __, ___) => Container(
color: scheme.surfaceContainerHighest,
child: const Icon(
Icons.image_not_supported_rounded,
size: 16,
),
),
),
),
),
),
],
),
],
const SizedBox(width: 4),
Icon(
Icons.chevron_right_rounded,
size: 20,
color: scheme.onSurfaceVariant.withValues(alpha: 0.5),
),
], ],
), ),
],
const SizedBox(width: 6),
Icon(
Icons.chevron_right_rounded,
color: scheme.onSurfaceVariant.withValues(alpha: 0.6),
), ),
], ),
), ),
), ),
), ),
@@ -123,14 +123,18 @@ class FeedController extends AsyncNotifier<FeedState> {
final settingsRes = await ref.read(settingsServiceProvider).getSettings(); final settingsRes = await ref.read(settingsServiceProvider).getSettings();
final settings = final settings =
settingsRes is Success<AppSettings> ? settingsRes.data : AppSettings.defaults; settingsRes is Success<AppSettings> ? settingsRes.data : AppSettings.defaults;
await ref try {
.read(searchServiceProvider) await refresh();
.saveSearch(query, 0, maxHistory: settings.searchHistoryLimit); final count = state.value?.posts.length ?? 0;
await refresh(); await ref
final count = state.value?.posts.length ?? 0; .read(searchServiceProvider)
await ref .saveSearch(query, count, maxHistory: settings.searchHistoryLimit);
.read(searchServiceProvider) } catch (_) {
.saveSearch(query, count, maxHistory: settings.searchHistoryLimit); await ref
.read(searchServiceProvider)
.saveSearch(query, 0, maxHistory: settings.searchHistoryLimit);
rethrow;
}
} }
Future<void> updateTagSuggestions(String query) async { Future<void> updateTagSuggestions(String query) async {
@@ -374,7 +374,11 @@ class _FeedScreenState extends ConsumerState<FeedScreen>
void _submitSearch(String query) { void _submitSearch(String query) {
final trimmed = query.trim(); final trimmed = query.trim();
if (trimmed.isEmpty) { if (trimmed.isEmpty) {
_clearFilters(); if (widget.initialQuery != null) {
context.go('/');
} else {
_applySearchQuery('');
}
return; return;
} }
final location = '/?q=${Uri.encodeQueryComponent(trimmed)}'; final location = '/?q=${Uri.encodeQueryComponent(trimmed)}';
@@ -104,7 +104,7 @@ class _FeedToolbarState extends State<FeedToolbar> {
}, },
onCleared: () { onCleared: () {
_query = ''; _query = '';
widget.onClearFilters(); widget.onSearch('');
}, },
), ),
), ),
@@ -235,7 +235,7 @@ class _FeedToolbarState extends State<FeedToolbar> {
}, },
onCleared: () { onCleared: () {
_query = ''; _query = '';
widget.onClearFilters(); widget.onSearch('');
}, },
), ),
), ),
@@ -21,6 +21,7 @@ import '../../../shared/widgets/rating_badge.dart';
import '../../collections/presentation/collection_form_dialog.dart'; import '../../collections/presentation/collection_form_dialog.dart';
import '../../favorites/presentation/favorites_controller.dart'; import '../../favorites/presentation/favorites_controller.dart';
import '../../feed/presentation/feed_controller.dart'; import '../../feed/presentation/feed_controller.dart';
import '../../settings/presentation/settings_controller.dart';
import '../../viewed/presentation/viewed_controller.dart'; import '../../viewed/presentation/viewed_controller.dart';
import 'post_details_controller.dart'; import 'post_details_controller.dart';
import 'widgets/cloud_mirrors_card.dart'; import 'widgets/cloud_mirrors_card.dart';
@@ -219,34 +220,79 @@ class PostDetailsScreen extends ConsumerWidget {
), ),
Expanded( Expanded(
child: Center( child: Center(
child: SizedBox( child: MediaUrlSelector.isVideo(post)
width: double.infinity, ? ConstrainedBox(
height: 760, constraints: const BoxConstraints(
child: PostMediaViewer( maxHeight: 760,
key: ValueKey(post.cacheKey), ),
post: post, child: AspectRatio(
localFilePath: localMedia?.savedPath, aspectRatio:
qualityMode: qualityMode, (post.width > 0 && post.height > 0)
mediaHeaders: ref ? (post.width / post.height)
.watch(postMediaHeadersProvider(post)) .clamp(0.45, 2.4)
.value ?? : (16 / 9),
const {}, child: PostMediaViewer(
initialPosition: Duration( key: ValueKey(post.cacheKey),
milliseconds: settings.videoPlaybackPositions[ post: post,
post.cacheKey] ?? localFilePath: localMedia?.savedPath,
0, qualityMode: qualityMode,
), mediaHeaders: ref
initialLoop: settings.videoPlayerLoop, .watch(postMediaHeadersProvider(post))
initialMuted: settings.videoPlayerMuted, .value ??
initialCoverVideo: settings.videoPlayerCover, const {},
initialHalfVolume: initialPosition: Duration(
settings.videoPlayerHalfVolume, milliseconds: settings.videoPlaybackPositions[
onPlaybackSnapshot: (snapshot) => post.cacheKey] ??
_saveVideoSnapshot(ref, post, snapshot), 0,
onPlaybackPreferencesChanged: (snapshot) => ),
_saveVideoPreferences(ref, snapshot), initialLoop: settings.videoPlayerLoop,
), initialMuted: settings.videoPlayerMuted,
), initialCoverVideo: settings.videoPlayerCover,
initialHalfVolume:
settings.videoPlayerHalfVolume,
initialVolume: settings.videoPlayerVolume,
onVolumeChanged: (vol) => ref
.read(settingsControllerProvider.notifier)
.setVideoPlayerVolume(vol),
onPlaybackSnapshot: (snapshot) =>
_saveVideoSnapshot(ref, post, snapshot),
onPlaybackPreferencesChanged: (snapshot) =>
_saveVideoPreferences(ref, snapshot),
),
),
)
: SizedBox(
width: double.infinity,
height: 760,
child: PostMediaViewer(
key: ValueKey(post.cacheKey),
post: post,
localFilePath: localMedia?.savedPath,
qualityMode: qualityMode,
mediaHeaders: ref
.watch(postMediaHeadersProvider(post))
.value ??
const {},
initialPosition: Duration(
milliseconds: settings.videoPlaybackPositions[
post.cacheKey] ??
0,
),
initialLoop: settings.videoPlayerLoop,
initialMuted: settings.videoPlayerMuted,
initialCoverVideo: settings.videoPlayerCover,
initialHalfVolume:
settings.videoPlayerHalfVolume,
initialVolume: settings.videoPlayerVolume,
onVolumeChanged: (vol) => ref
.read(settingsControllerProvider.notifier)
.setVideoPlayerVolume(vol),
onPlaybackSnapshot: (snapshot) =>
_saveVideoSnapshot(ref, post, snapshot),
onPlaybackPreferencesChanged: (snapshot) =>
_saveVideoPreferences(ref, snapshot),
),
),
), ),
), ),
IconButton.filledTonal( IconButton.filledTonal(
@@ -316,14 +362,15 @@ class PostDetailsScreen extends ConsumerWidget {
const SizedBox(height: 16), const SizedBox(height: 16),
Container( Container(
decoration: BoxDecoration( decoration: BoxDecoration(
color: color: Theme.of(context).brightness == Brightness.dark
Theme.of(context).colorScheme.surfaceContainerLow, ? Theme.of(context).colorScheme.surfaceContainerHigh.withValues(alpha: 0.70)
borderRadius: BorderRadius.circular(18), : Theme.of(context).colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(20),
border: Border.all( border: Border.all(
color: Theme.of(context) color: Theme.of(context).brightness == Brightness.dark
.colorScheme ? Colors.white.withValues(alpha: 0.12)
.outlineVariant : Theme.of(context).colorScheme.outlineVariant.withValues(alpha: 0.40),
.withValues(alpha: 0.35), width: 1.1,
), ),
), ),
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
@@ -354,6 +401,7 @@ class PostDetailsScreen extends ConsumerWidget {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
_CommentsSection(post: post), _CommentsSection(post: post),
const SizedBox(height: 80),
], ],
), ),
), ),
@@ -398,7 +446,12 @@ class PostDetailsScreen extends ConsumerWidget {
if ((details.primaryVelocity ?? 0) > 900) _close(context); if ((details.primaryVelocity ?? 0) > 900) _close(context);
}, },
child: ListView( child: ListView(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 16), padding: EdgeInsets.fromLTRB(
8,
8,
8,
120 + MediaQuery.paddingOf(context).bottom,
),
children: [ children: [
GestureDetector( GestureDetector(
behavior: HitTestBehavior.deferToChild, behavior: HitTestBehavior.deferToChild,
@@ -408,33 +461,80 @@ class PostDetailsScreen extends ConsumerWidget {
? null ? null
: () => : () =>
_showMobileQuickActions(context, ref, post, favoriteKeys), _showMobileQuickActions(context, ref, post, favoriteKeys),
child: SizedBox( child: isVideo
width: double.infinity, ? Center(
height: MediaQuery.sizeOf(context).height * 0.62, child: ConstrainedBox(
child: PostMediaViewer( constraints: BoxConstraints(
key: ValueKey(post.cacheKey), maxHeight: MediaQuery.sizeOf(context).height * 0.70,
post: post, ),
localFilePath: localMedia?.savedPath, child: AspectRatio(
qualityMode: qualityMode, aspectRatio: (post.width > 0 && post.height > 0)
mediaHeaders: ? (post.width / post.height).clamp(0.45, 2.4)
ref.watch(postMediaHeadersProvider(post)).value ?? const {}, : (16 / 9),
initialPosition: Duration( child: PostMediaViewer(
milliseconds: key: ValueKey(post.cacheKey),
settings.videoPlaybackPositions[post.cacheKey] ?? 0, post: post,
), localFilePath: localMedia?.savedPath,
initialLoop: settings.videoPlayerLoop, qualityMode: qualityMode,
initialMuted: settings.videoPlayerMuted, mediaHeaders:
initialCoverVideo: settings.videoPlayerCover, ref.watch(postMediaHeadersProvider(post)).value ??
initialHalfVolume: settings.videoPlayerHalfVolume, const {},
onPlaybackSnapshot: (snapshot) => initialPosition: Duration(
_saveVideoSnapshot(ref, post, snapshot), milliseconds:
onPlaybackPreferencesChanged: (snapshot) => settings.videoPlaybackPositions[post.cacheKey] ??
_saveVideoPreferences(ref, snapshot), 0,
onMediaGestureLockChanged: (locked) { ),
onMediaGestureLockChanged?.call(locked); initialLoop: settings.videoPlayerLoop,
}, initialMuted: settings.videoPlayerMuted,
), initialCoverVideo: settings.videoPlayerCover,
), initialHalfVolume: settings.videoPlayerHalfVolume,
initialVolume: settings.videoPlayerVolume,
onVolumeChanged: (vol) => ref
.read(settingsControllerProvider.notifier)
.setVideoPlayerVolume(vol),
onPlaybackSnapshot: (snapshot) =>
_saveVideoSnapshot(ref, post, snapshot),
onPlaybackPreferencesChanged: (snapshot) =>
_saveVideoPreferences(ref, snapshot),
onMediaGestureLockChanged: (locked) {
onMediaGestureLockChanged?.call(locked);
},
),
),
),
)
: SizedBox(
width: double.infinity,
height: MediaQuery.sizeOf(context).height * 0.62,
child: PostMediaViewer(
key: ValueKey(post.cacheKey),
post: post,
localFilePath: localMedia?.savedPath,
qualityMode: qualityMode,
mediaHeaders:
ref.watch(postMediaHeadersProvider(post)).value ??
const {},
initialPosition: Duration(
milliseconds:
settings.videoPlaybackPositions[post.cacheKey] ?? 0,
),
initialLoop: settings.videoPlayerLoop,
initialMuted: settings.videoPlayerMuted,
initialCoverVideo: settings.videoPlayerCover,
initialHalfVolume: settings.videoPlayerHalfVolume,
initialVolume: settings.videoPlayerVolume,
onVolumeChanged: (vol) => ref
.read(settingsControllerProvider.notifier)
.setVideoPlayerVolume(vol),
onPlaybackSnapshot: (snapshot) =>
_saveVideoSnapshot(ref, post, snapshot),
onPlaybackPreferencesChanged: (snapshot) =>
_saveVideoPreferences(ref, snapshot),
onMediaGestureLockChanged: (locked) {
onMediaGestureLockChanged?.call(locked);
},
),
),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
PostActionBar( PostActionBar(
@@ -493,13 +593,15 @@ class PostDetailsScreen extends ConsumerWidget {
const SizedBox(height: 12), const SizedBox(height: 12),
Container( Container(
decoration: BoxDecoration( decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerLow, color: Theme.of(context).brightness == Brightness.dark
borderRadius: BorderRadius.circular(18), ? Theme.of(context).colorScheme.surfaceContainerHigh.withValues(alpha: 0.70)
: Theme.of(context).colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(20),
border: Border.all( border: Border.all(
color: Theme.of(context) color: Theme.of(context).brightness == Brightness.dark
.colorScheme ? Colors.white.withValues(alpha: 0.12)
.outlineVariant : Theme.of(context).colorScheme.outlineVariant.withValues(alpha: 0.40),
.withValues(alpha: 0.35), width: 1.1,
), ),
), ),
clipBehavior: Clip.antiAlias, clipBehavior: Clip.antiAlias,
@@ -530,6 +632,7 @@ class PostDetailsScreen extends ConsumerWidget {
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
_CommentsSection(post: post), _CommentsSection(post: post),
const SizedBox(height: 24),
], ],
), ),
); );
@@ -776,7 +879,8 @@ class PostDetailsScreen extends ConsumerWidget {
if (settings.videoPlayerMuted == snapshot.muted && if (settings.videoPlayerMuted == snapshot.muted &&
settings.videoPlayerHalfVolume == snapshot.halfVolume && settings.videoPlayerHalfVolume == snapshot.halfVolume &&
settings.videoPlayerLoop == snapshot.loopVideo && settings.videoPlayerLoop == snapshot.loopVideo &&
settings.videoPlayerCover == snapshot.coverVideo) { settings.videoPlayerCover == snapshot.coverVideo &&
(settings.videoPlayerVolume - snapshot.volume).abs() < 0.01) {
return; return;
} }
await ref.read(settingsServiceProvider).updateSettings( await ref.read(settingsServiceProvider).updateSettings(
@@ -785,6 +889,7 @@ class PostDetailsScreen extends ConsumerWidget {
videoPlayerHalfVolume: snapshot.halfVolume, videoPlayerHalfVolume: snapshot.halfVolume,
videoPlayerLoop: snapshot.loopVideo, videoPlayerLoop: snapshot.loopVideo,
videoPlayerCover: snapshot.coverVideo, videoPlayerCover: snapshot.coverVideo,
videoPlayerVolume: snapshot.volume,
), ),
); );
ref.invalidate(appSettingsProvider); ref.invalidate(appSettingsProvider);
@@ -1081,7 +1186,7 @@ class _CommentsSectionState extends ConsumerState<_CommentsSection> {
), ),
clipBehavior: Clip.antiAlias, clipBehavior: Clip.antiAlias,
child: ExpansionTile( child: ExpansionTile(
tilePadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 2), tilePadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
childrenPadding: const EdgeInsets.fromLTRB(14, 0, 14, 14), childrenPadding: const EdgeInsets.fromLTRB(14, 0, 14, 14),
initiallyExpanded: false, initiallyExpanded: false,
shape: const Border(), shape: const Border(),
@@ -27,10 +27,12 @@ class PostMediaViewer extends StatefulWidget {
this.initialMuted = false, this.initialMuted = false,
this.initialCoverVideo = false, this.initialCoverVideo = false,
this.initialHalfVolume = false, this.initialHalfVolume = false,
this.initialVolume = 100.0,
this.qualityMode = MediaQualityMode.auto, this.qualityMode = MediaQualityMode.auto,
this.mediaHeaders = const {}, this.mediaHeaders = const {},
this.onPlaybackSnapshot, this.onPlaybackSnapshot,
this.onPlaybackPreferencesChanged, this.onPlaybackPreferencesChanged,
this.onVolumeChanged,
this.onMediaGestureLockChanged, this.onMediaGestureLockChanged,
super.key, super.key,
}); });
@@ -44,10 +46,12 @@ class PostMediaViewer extends StatefulWidget {
final bool initialMuted; final bool initialMuted;
final bool initialCoverVideo; final bool initialCoverVideo;
final bool initialHalfVolume; final bool initialHalfVolume;
final double initialVolume;
final MediaQualityMode qualityMode; final MediaQualityMode qualityMode;
final Map<String, String> mediaHeaders; final Map<String, String> mediaHeaders;
final ValueChanged<VideoPlaybackSnapshot>? onPlaybackSnapshot; final ValueChanged<VideoPlaybackSnapshot>? onPlaybackSnapshot;
final ValueChanged<VideoPlaybackSnapshot>? onPlaybackPreferencesChanged; final ValueChanged<VideoPlaybackSnapshot>? onPlaybackPreferencesChanged;
final ValueChanged<double>? onVolumeChanged;
final ValueChanged<bool>? onMediaGestureLockChanged; final ValueChanged<bool>? onMediaGestureLockChanged;
@override @override
@@ -68,8 +72,10 @@ class _PostMediaViewerState extends State<PostMediaViewer>
late bool _muted; late bool _muted;
late bool _loopVideo; late bool _loopVideo;
late bool _halfVolume; late bool _halfVolume;
late double _currentVolume;
String? _videoError; String? _videoError;
bool _retriedFormatError = false; bool _retriedFormatError = false;
bool _softwareDecodingFallback = false;
Timer? _hideTimer; Timer? _hideTimer;
StreamSubscription<String>? _errorSubscription; StreamSubscription<String>? _errorSubscription;
StreamSubscription<Duration>? _positionSubscription; StreamSubscription<Duration>? _positionSubscription;
@@ -83,6 +89,7 @@ class _PostMediaViewerState extends State<PostMediaViewer>
_muted = widget.initialMuted; _muted = widget.initialMuted;
_loopVideo = widget.initialLoop; _loopVideo = widget.initialLoop;
_halfVolume = widget.initialHalfVolume; _halfVolume = widget.initialHalfVolume;
_currentVolume = widget.initialVolume;
_imageUrls = _buildImageUrls(widget.post); _imageUrls = _buildImageUrls(widget.post);
_videoUrls = _buildVideoUrls(widget.post); _videoUrls = _buildVideoUrls(widget.post);
if (_isVideo(widget.post) && _videoUrls.isNotEmpty) { if (_isVideo(widget.post) && _videoUrls.isNotEmpty) {
@@ -99,6 +106,7 @@ class _PostMediaViewerState extends State<PostMediaViewer>
_videoIndex = 0; _videoIndex = 0;
_videoError = null; _videoError = null;
_retriedFormatError = false; _retriedFormatError = false;
_softwareDecodingFallback = false;
_imageUrls = _buildImageUrls(widget.post); _imageUrls = _buildImageUrls(widget.post);
_videoUrls = _buildVideoUrls(widget.post); _videoUrls = _buildVideoUrls(widget.post);
if (_isVideo(widget.post) && _videoUrls.isNotEmpty) { if (_isVideo(widget.post) && _videoUrls.isNotEmpty) {
@@ -109,6 +117,27 @@ class _PostMediaViewerState extends State<PostMediaViewer>
unawaited(_retryVideo()); unawaited(_retryVideo());
} }
} }
if (oldWidget.initialVolume != widget.initialVolume) {
_currentVolume = widget.initialVolume;
unawaited(_applyVolume());
}
if (oldWidget.initialMuted != widget.initialMuted) {
_muted = widget.initialMuted;
unawaited(_applyVolume());
}
if (oldWidget.initialHalfVolume != widget.initialHalfVolume) {
_halfVolume = widget.initialHalfVolume;
unawaited(_applyVolume());
}
if (oldWidget.initialLoop != widget.initialLoop) {
_loopVideo = widget.initialLoop;
unawaited(_player?.setPlaylistMode(
_loopVideo ? PlaylistMode.single : PlaylistMode.none,
));
}
if (oldWidget.initialCoverVideo != widget.initialCoverVideo) {
_coverVideo = widget.initialCoverVideo;
}
} }
@override @override
@@ -167,6 +196,12 @@ class _PostMediaViewerState extends State<PostMediaViewer>
muted: _muted, muted: _muted,
loopVideo: _loopVideo, loopVideo: _loopVideo,
halfVolume: _halfVolume, halfVolume: _halfVolume,
initialVolume: _currentVolume,
onVolumeChanged: (vol) {
_currentVolume = vol;
widget.onVolumeChanged?.call(vol);
_emitPlaybackPreferences();
},
fullscreen: widget.fullscreen, fullscreen: widget.fullscreen,
errorMessage: _videoError, errorMessage: _videoError,
onInteract: _showControls, onInteract: _showControls,
@@ -326,7 +361,13 @@ class _PostMediaViewerState extends State<PostMediaViewer>
void _initializeVideo() { void _initializeVideo() {
MediaKit.ensureInitialized(); MediaKit.ensureInitialized();
_player = Player(); _player = Player();
_controller = VideoController(_player!); _controller = VideoController(
_player!,
configuration: VideoControllerConfiguration(
enableHardwareAcceleration: !_softwareDecodingFallback,
hwdec: _softwareDecodingFallback ? 'no' : 'auto-safe',
),
);
_applyVolume(); _applyVolume();
_player!.setPlaylistMode( _player!.setPlaylistMode(
_loopVideo ? PlaylistMode.single : PlaylistMode.none, _loopVideo ? PlaylistMode.single : PlaylistMode.none,
@@ -370,6 +411,7 @@ class _PostMediaViewerState extends State<PostMediaViewer>
), ),
play: false, play: false,
); );
await _applyVolume();
if (initialPosition > Duration.zero) { if (initialPosition > Duration.zero) {
await player.seek(initialPosition); await player.seek(initialPosition);
} }
@@ -385,18 +427,24 @@ class _PostMediaViewerState extends State<PostMediaViewer>
await _openVideo(play: play); await _openVideo(play: play);
return; return;
} }
// If format error occurred on initial load (often due to async referer headers), retry once automatically final lower = message.toLowerCase();
// If format or codec error occurred (e.g. unsupported hwdec profile), fallback to software decoding and retry once
if (!_retriedFormatError && if (!_retriedFormatError &&
(message.contains('Failed to recognize file format') || (lower.contains('codec') ||
message.contains('Demuxer error') || lower.contains('could not open') ||
message.contains('Could not open') || lower.contains('couldnt open') ||
message.contains('Stream format not recognized') || lower.contains('could not initialize codec') ||
message.contains('format unrecognized'))) { lower.contains('demuxer error') ||
lower.contains('format unrecognized') ||
lower.contains('stream format not recognized') ||
lower.contains('failed to recognize file format'))) {
_retriedFormatError = true; _retriedFormatError = true;
await Future<void>.delayed(const Duration(milliseconds: 300)); _softwareDecodingFallback = true;
if (mounted && _player != null) { _disposeVideo();
await Future<void>.delayed(const Duration(milliseconds: 250));
if (mounted) {
_videoIndex = 0; _videoIndex = 0;
await _openVideo(play: play); _initializeVideo();
return; return;
} }
} }
@@ -408,7 +456,12 @@ class _PostMediaViewerState extends State<PostMediaViewer>
Future<void> _retryVideo() async { Future<void> _retryVideo() async {
_videoIndex = 0; _videoIndex = 0;
_retriedFormatError = false; _retriedFormatError = false;
await _openVideo(play: true); _softwareDecodingFallback = true;
_disposeVideo();
await Future<void>.delayed(const Duration(milliseconds: 150));
if (mounted) {
_initializeVideo();
}
} }
void _disposeVideo() { void _disposeVideo() {
@@ -518,6 +571,7 @@ class _PostMediaViewerState extends State<PostMediaViewer>
final player = _player; final player = _player;
final controller = _controller; final controller = _controller;
if (player == null || controller == null) return; if (player == null || controller == null) return;
final wasPlaying = player.state.playing;
setState(() => _inFullscreen = true); setState(() => _inFullscreen = true);
if (!context.mounted) return; if (!context.mounted) return;
final result = await Navigator.of(context, rootNavigator: true) final result = await Navigator.of(context, rootNavigator: true)
@@ -527,6 +581,7 @@ class _PostMediaViewerState extends State<PostMediaViewer>
pageBuilder: (_, __, ___) => _FullscreenVideoPage( pageBuilder: (_, __, ___) => _FullscreenVideoPage(
player: player, player: player,
controller: controller, controller: controller,
wasPlaying: wasPlaying,
aspectRatio: widget.post.width > 0 && widget.post.height > 0 aspectRatio: widget.post.width > 0 && widget.post.height > 0
? widget.post.width / widget.post.height ? widget.post.width / widget.post.height
: 16 / 9, : 16 / 9,
@@ -534,6 +589,7 @@ class _PostMediaViewerState extends State<PostMediaViewer>
muted: _muted, muted: _muted,
halfVolume: _halfVolume, halfVolume: _halfVolume,
coverVideo: _coverVideo, coverVideo: _coverVideo,
initialVolume: _currentVolume,
errorMessage: _videoError, errorMessage: _videoError,
onRetry: _retryVideo, onRetry: _retryVideo,
onChanged: (snapshot) { onChanged: (snapshot) {
@@ -549,6 +605,11 @@ class _PostMediaViewerState extends State<PostMediaViewer>
if (mounted) setState(() => _inFullscreen = false); if (mounted) setState(() => _inFullscreen = false);
if (result != null) { if (result != null) {
await _applyPlaybackSnapshot(result); await _applyPlaybackSnapshot(result);
if (result.playing && !player.state.playing) {
await player.play();
} else if (!result.playing && player.state.playing) {
await player.pause();
}
return; return;
} }
} }
@@ -560,12 +621,14 @@ class _PostMediaViewerState extends State<PostMediaViewer>
_loopVideo = snapshot.loopVideo; _loopVideo = snapshot.loopVideo;
_coverVideo = snapshot.coverVideo; _coverVideo = snapshot.coverVideo;
_halfVolume = snapshot.halfVolume; _halfVolume = snapshot.halfVolume;
_currentVolume = snapshot.volume;
}); });
await _applyVolume(); await _applyVolume();
await _player?.setPlaylistMode( await _player?.setPlaylistMode(
_loopVideo ? PlaylistMode.single : PlaylistMode.none, _loopVideo ? PlaylistMode.single : PlaylistMode.none,
); );
_emitPlaybackPreferences(); _emitPlaybackPreferences();
widget.onVolumeChanged?.call(_currentVolume);
} }
VideoPlaybackSnapshot _snapshot() { VideoPlaybackSnapshot _snapshot() {
@@ -577,15 +640,16 @@ class _PostMediaViewerState extends State<PostMediaViewer>
halfVolume: _halfVolume, halfVolume: _halfVolume,
loopVideo: _loopVideo, loopVideo: _loopVideo,
coverVideo: _coverVideo, coverVideo: _coverVideo,
volume: _currentVolume,
); );
} }
Future<void> _applyVolume() async { Future<void> _applyVolume() async {
await _player?.setVolume(_muted await _player?.setVolume(_muted
? 0 ? 0.0
: _halfVolume : _halfVolume
? 50 ? 50.0
: 100); : _currentVolume);
} }
void _emitPlaybackPreferences() { void _emitPlaybackPreferences() {
@@ -656,6 +720,7 @@ class VideoPlaybackSnapshot {
required this.halfVolume, required this.halfVolume,
required this.loopVideo, required this.loopVideo,
required this.coverVideo, required this.coverVideo,
this.volume = 100.0,
}); });
final Duration position; final Duration position;
@@ -664,17 +729,20 @@ class VideoPlaybackSnapshot {
final bool halfVolume; final bool halfVolume;
final bool loopVideo; final bool loopVideo;
final bool coverVideo; final bool coverVideo;
final double volume;
} }
class _FullscreenVideoPage extends StatefulWidget { class _FullscreenVideoPage extends StatefulWidget {
const _FullscreenVideoPage({ const _FullscreenVideoPage({
required this.player, required this.player,
required this.controller, required this.controller,
required this.wasPlaying,
required this.aspectRatio, required this.aspectRatio,
required this.loopVideo, required this.loopVideo,
required this.muted, required this.muted,
required this.halfVolume, required this.halfVolume,
required this.coverVideo, required this.coverVideo,
this.initialVolume = 100.0,
required this.errorMessage, required this.errorMessage,
required this.onRetry, required this.onRetry,
required this.onChanged, required this.onChanged,
@@ -682,11 +750,13 @@ class _FullscreenVideoPage extends StatefulWidget {
final Player player; final Player player;
final VideoController controller; final VideoController controller;
final bool wasPlaying;
final double aspectRatio; final double aspectRatio;
final bool loopVideo; final bool loopVideo;
final bool muted; final bool muted;
final bool halfVolume; final bool halfVolume;
final bool coverVideo; final bool coverVideo;
final double initialVolume;
final String? errorMessage; final String? errorMessage;
final VoidCallback onRetry; final VoidCallback onRetry;
final ValueChanged<VideoPlaybackSnapshot> onChanged; final ValueChanged<VideoPlaybackSnapshot> onChanged;
@@ -701,6 +771,7 @@ class _FullscreenVideoPageState extends State<_FullscreenVideoPage> {
late bool _muted; late bool _muted;
late bool _loopVideo; late bool _loopVideo;
late bool _halfVolume; late bool _halfVolume;
late double _currentVolume;
late bool _isLandscape; late bool _isLandscape;
Timer? _hideTimer; Timer? _hideTimer;
@@ -711,10 +782,19 @@ class _FullscreenVideoPageState extends State<_FullscreenVideoPage> {
_muted = widget.muted; _muted = widget.muted;
_loopVideo = widget.loopVideo; _loopVideo = widget.loopVideo;
_halfVolume = widget.halfVolume; _halfVolume = widget.halfVolume;
_currentVolume = widget.initialVolume;
_applyVolume();
_isLandscape = widget.aspectRatio > 1.05; _isLandscape = widget.aspectRatio > 1.05;
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky); SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
_applyOrientation(); _applyOrientation();
_scheduleControlsHide(); _scheduleControlsHide();
if (widget.wasPlaying) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && !widget.player.state.playing) {
widget.player.play();
}
});
}
} }
void _applyOrientation() { void _applyOrientation() {
@@ -790,6 +870,11 @@ class _FullscreenVideoPageState extends State<_FullscreenVideoPage> {
muted: _muted, muted: _muted,
loopVideo: _loopVideo, loopVideo: _loopVideo,
halfVolume: _halfVolume, halfVolume: _halfVolume,
initialVolume: _currentVolume,
onVolumeChanged: (vol) {
_currentVolume = vol;
widget.onChanged(_snapshot());
},
fullscreen: true, fullscreen: true,
errorMessage: widget.errorMessage, errorMessage: widget.errorMessage,
onInteract: _showControls, onInteract: _showControls,
@@ -883,10 +968,10 @@ class _FullscreenVideoPageState extends State<_FullscreenVideoPage> {
Future<void> _applyVolume() async { Future<void> _applyVolume() async {
await widget.player.setVolume(_muted await widget.player.setVolume(_muted
? 0 ? 0.0
: _halfVolume : _halfVolume
? 50 ? 50.0
: 100); : _currentVolume);
} }
VideoPlaybackSnapshot _snapshot() { VideoPlaybackSnapshot _snapshot() {
@@ -897,6 +982,7 @@ class _FullscreenVideoPageState extends State<_FullscreenVideoPage> {
halfVolume: _halfVolume, halfVolume: _halfVolume,
loopVideo: _loopVideo, loopVideo: _loopVideo,
coverVideo: _coverVideo, coverVideo: _coverVideo,
volume: _currentVolume,
); );
} }
} }
@@ -915,6 +1001,8 @@ class _VideoSurface extends StatefulWidget {
required this.muted, required this.muted,
required this.halfVolume, required this.halfVolume,
required this.loopVideo, required this.loopVideo,
this.initialVolume = 100.0,
this.onVolumeChanged,
required this.fullscreen, required this.fullscreen,
required this.errorMessage, required this.errorMessage,
required this.onInteract, required this.onInteract,
@@ -934,6 +1022,8 @@ class _VideoSurface extends StatefulWidget {
final bool muted; final bool muted;
final bool halfVolume; final bool halfVolume;
final bool loopVideo; final bool loopVideo;
final double initialVolume;
final ValueChanged<double>? onVolumeChanged;
final bool fullscreen; final bool fullscreen;
final String? errorMessage; final String? errorMessage;
final VoidCallback onInteract; final VoidCallback onInteract;
@@ -965,7 +1055,17 @@ class _VideoSurfaceState extends State<_VideoSurface> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_currentVolume = widget.player.state.volume; _currentVolume = widget.initialVolume;
widget.player.setVolume(_currentVolume);
}
@override
void didUpdateWidget(covariant _VideoSurface oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.initialVolume != widget.initialVolume) {
_currentVolume = widget.initialVolume;
widget.player.setVolume(_currentVolume);
}
} }
@override @override
@@ -983,26 +1083,37 @@ class _VideoSurfaceState extends State<_VideoSurface> {
if (target < Duration.zero) target = Duration.zero; if (target < Duration.zero) target = Duration.zero;
if (dur > Duration.zero && target > dur) target = dur; if (dur > Duration.zero && target > dur) target = dur;
widget.player.seek(target); widget.player.seek(target);
widget.onInteract();
if (delta.inSeconds < 0) {
setState(() => _showLeftSeek = true);
_seekLeftTimer?.cancel();
_seekLeftTimer = Timer(const Duration(milliseconds: 650), () {
if (mounted) setState(() => _showLeftSeek = false);
});
} else if (delta.inSeconds > 0) {
setState(() => _showRightSeek = true);
_seekRightTimer?.cancel();
_seekRightTimer = Timer(const Duration(milliseconds: 650), () {
if (mounted) setState(() => _showRightSeek = false);
});
}
} }
void _onDoubleTapAt(Offset localPosition, double width) { void _onDoubleTapAt(Offset localPosition, double width) {
if (_isLocked) return; if (_isLocked) return;
if (localPosition.dx < width * 0.4) { if (localPosition.dx < width * 0.4) {
_seekBy(const Duration(seconds: -10)); _seekBy(const Duration(seconds: -10));
setState(() => _showLeftSeek = true);
_seekLeftTimer?.cancel();
_seekLeftTimer = Timer(const Duration(milliseconds: 650), () {
if (mounted) setState(() => _showLeftSeek = false);
});
} else if (localPosition.dx > width * 0.6) { } else if (localPosition.dx > width * 0.6) {
_seekBy(const Duration(seconds: 10)); _seekBy(const Duration(seconds: 10));
setState(() => _showRightSeek = true);
_seekRightTimer?.cancel();
_seekRightTimer = Timer(const Duration(milliseconds: 650), () {
if (mounted) setState(() => _showRightSeek = false);
});
} else { } else {
widget.player.playOrPause(); if (widget.player.state.playing) {
widget.player.pause();
} else {
if (widget.player.state.completed) {
widget.player.seek(Duration.zero);
}
widget.player.play();
}
widget.onInteract(); widget.onInteract();
} }
} }
@@ -1025,6 +1136,7 @@ class _VideoSurfaceState extends State<_VideoSurface> {
final newVol = (_currentVolume - deltaY * 0.5).clamp(0.0, 100.0); final newVol = (_currentVolume - deltaY * 0.5).clamp(0.0, 100.0);
_currentVolume = newVol; _currentVolume = newVol;
widget.player.setVolume(newVol); widget.player.setVolume(newVol);
widget.onVolumeChanged?.call(newVol);
setState(() => _showVolumeIndicator = true); setState(() => _showVolumeIndicator = true);
_volumeTimer?.cancel(); _volumeTimer?.cancel();
_volumeTimer = Timer(const Duration(milliseconds: 1100), () { _volumeTimer = Timer(const Duration(milliseconds: 1100), () {
@@ -1035,6 +1147,7 @@ class _VideoSurfaceState extends State<_VideoSurface> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final player = widget.player; final player = widget.player;
Offset? lastTapDown;
final child = LayoutBuilder( final child = LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
@@ -1047,6 +1160,32 @@ class _VideoSurfaceState extends State<_VideoSurface> {
controller: widget.controller, controller: widget.controller,
fit: widget.coverVideo ? BoxFit.cover : BoxFit.contain, fit: widget.coverVideo ? BoxFit.cover : BoxFit.contain,
controls: null, controls: null,
pauseUponEnteringBackgroundMode: false,
resumeUponEnteringForegroundMode: false,
),
),
Positioned.fill(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (details) => lastTapDown = details.localPosition,
onTap: widget.onInteract,
onDoubleTap: () {
if (lastTapDown != null) {
_onDoubleTapAt(
lastTapDown!,
MediaQuery.sizeOf(context).width,
);
}
},
onLongPressStart: (_) => _startSpeedBoost(),
onLongPressEnd: (_) => _stopSpeedBoost(),
onVerticalDragUpdate: (details) {
final x = details.localPosition.dx;
final width = MediaQuery.sizeOf(context).width;
if (x > width * 0.4) {
_adjustVolume(details.primaryDelta ?? 0.0);
}
},
), ),
), ),
StreamBuilder<bool>( StreamBuilder<bool>(
@@ -1094,6 +1233,7 @@ class _VideoSurfaceState extends State<_VideoSurface> {
onToggleLoop: widget.onToggleLoop, onToggleLoop: widget.onToggleLoop,
onFullscreen: widget.onFullscreen, onFullscreen: widget.onFullscreen,
onSeekBy: _seekBy, onSeekBy: _seekBy,
onInteract: widget.onInteract,
), ),
), ),
), ),
@@ -1102,36 +1242,16 @@ class _VideoSurfaceState extends State<_VideoSurface> {
}, },
); );
Offset? lastTapDown;
return MouseRegion( return MouseRegion(
onHover: (_) => widget.onInteract(), onHover: (_) => widget.onInteract(),
child: GestureDetector( child: ClipRRect(
onTapDown: (details) => lastTapDown = details.localPosition, borderRadius: BorderRadius.circular(widget.fullscreen ? 0 : 10),
onTap: widget.onInteract, child: widget.fullscreen
onDoubleTap: () { ? SizedBox.expand(child: child)
if (lastTapDown != null) { : AspectRatio(
_onDoubleTapAt(lastTapDown!, MediaQuery.sizeOf(context).width); aspectRatio: widget.aspectRatio.clamp(0.35, 2.4),
} child: child,
}, ),
onLongPressStart: (_) => _startSpeedBoost(),
onLongPressEnd: (_) => _stopSpeedBoost(),
onVerticalDragUpdate: (details) {
final x = details.localPosition.dx;
final width = MediaQuery.sizeOf(context).width;
if (x > width * 0.4) {
_adjustVolume(details.primaryDelta ?? 0.0);
}
},
child: ClipRRect(
borderRadius: BorderRadius.circular(widget.fullscreen ? 0 : 10),
child: widget.fullscreen
? SizedBox.expand(child: child)
: AspectRatio(
aspectRatio: widget.aspectRatio.clamp(0.35, 2.4),
child: child,
),
),
), ),
); );
} }
@@ -1449,30 +1569,38 @@ class _RoundControlButton extends StatelessWidget {
: Colors.white; : Colors.white;
return Tooltip( return Tooltip(
message: tooltip, message: tooltip,
child: InkResponse( child: Material(
onTap: onPressed, color: Colors.transparent,
radius: size / 2 + 4, shape: const CircleBorder(),
child: AnimatedContainer( child: InkResponse(
duration: AppMotion.duration(context, 140), containedInkWell: true,
width: size, highlightShape: BoxShape.circle,
height: size, onTap: onPressed,
decoration: BoxDecoration( child: AnimatedContainer(
color: background, duration: AppMotion.duration(context, 140),
shape: BoxShape.circle, width: size,
border: Border.all( height: size,
color: selected decoration: BoxDecoration(
? scheme.primary.withValues(alpha: 0.4) color: background,
: Colors.white.withValues(alpha: 0.14), shape: BoxShape.circle,
border: Border.all(
color: selected
? scheme.primary.withValues(alpha: 0.4)
: Colors.white.withValues(alpha: 0.14),
),
boxShadow: [
if (emphasized)
BoxShadow(
color: scheme.primary.withValues(alpha: 0.45),
blurRadius: 28,
spreadRadius: 2,
),
],
),
child: Center(
child: Icon(icon, color: foreground, size: iconSize),
), ),
boxShadow: [
if (emphasized)
BoxShadow(
color: scheme.primary.withValues(alpha: 0.35),
blurRadius: 14,
),
],
), ),
child: Icon(icon, color: foreground, size: iconSize),
), ),
), ),
); );
@@ -1728,6 +1856,7 @@ class _VideoControls extends StatelessWidget {
required this.onToggleLoop, required this.onToggleLoop,
required this.onFullscreen, required this.onFullscreen,
required this.onSeekBy, required this.onSeekBy,
this.onInteract,
}); });
final Player player; final Player player;
@@ -1744,6 +1873,7 @@ class _VideoControls extends StatelessWidget {
final VoidCallback onToggleLoop; final VoidCallback onToggleLoop;
final VoidCallback onFullscreen; final VoidCallback onFullscreen;
final void Function(Duration) onSeekBy; final void Function(Duration) onSeekBy;
final VoidCallback? onInteract;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -1792,7 +1922,10 @@ class _VideoControls extends StatelessWidget {
), ),
), ),
child: SafeArea( child: SafeArea(
top: fullscreen,
bottom: false, bottom: false,
left: fullscreen,
right: fullscreen,
child: Row( child: Row(
children: [ children: [
if (fullscreen) ...[ if (fullscreen) ...[
@@ -1861,34 +1994,39 @@ class _VideoControls extends StatelessWidget {
icon: Icons.replay_10_rounded, icon: Icons.replay_10_rounded,
size: 46, size: 46,
iconSize: 26, iconSize: 26,
onPressed: () => onSeekBy(const Duration(seconds: -10)), onPressed: () {
onSeekBy(const Duration(seconds: -10));
onInteract?.call();
},
), ),
const SizedBox(width: 32), const SizedBox(width: 32),
Container( _RoundControlButton(
width: 68, tooltip: playing ? 'Пауза' : 'Воспроизведение',
height: 68, icon: playing
decoration: BoxDecoration( ? Icons.pause_rounded
shape: BoxShape.circle, : Icons.play_arrow_rounded,
color: scheme.primary.withValues(alpha: 0.94), size: 68,
boxShadow: [ iconSize: 42,
BoxShadow( emphasized: true,
color: scheme.primary.withValues(alpha: 0.45), onPressed: () async {
blurRadius: 28, try {
spreadRadius: 2, if (player.state.playing) {
), await player.pause();
], } else {
), if (player.state.completed) {
child: IconButton( await player.seek(Duration.zero);
tooltip: playing ? 'Пауза' : 'Воспроизведение', }
iconSize: 42, await player.play();
color: scheme.onPrimary, }
onPressed: player.playOrPause, } catch (_) {
icon: Icon( if (player.state.playing) {
playing await player.pause();
? Icons.pause_rounded } else {
: Icons.play_arrow_rounded, await player.play();
), }
), }
onInteract?.call();
},
), ),
const SizedBox(width: 32), const SizedBox(width: 32),
_RoundControlButton( _RoundControlButton(
@@ -1896,7 +2034,10 @@ class _VideoControls extends StatelessWidget {
icon: Icons.forward_10_rounded, icon: Icons.forward_10_rounded,
size: 46, size: 46,
iconSize: 26, iconSize: 26,
onPressed: () => onSeekBy(const Duration(seconds: 10)), onPressed: () {
onSeekBy(const Duration(seconds: 10));
onInteract?.call();
},
), ),
], ],
); );
@@ -1910,7 +2051,12 @@ class _VideoControls extends StatelessWidget {
left: 0, left: 0,
right: 0, right: 0,
child: Container( child: Container(
padding: const EdgeInsets.fromLTRB(14, 12, 14, 10), padding: EdgeInsets.fromLTRB(
14,
8,
14,
fullscreen ? 10 : 4,
),
decoration: const BoxDecoration( decoration: const BoxDecoration(
gradient: LinearGradient( gradient: LinearGradient(
begin: Alignment.bottomCenter, begin: Alignment.bottomCenter,
@@ -1920,6 +2066,9 @@ class _VideoControls extends StatelessWidget {
), ),
child: SafeArea( child: SafeArea(
top: false, top: false,
bottom: fullscreen,
left: fullscreen,
right: fullscreen,
child: StreamBuilder<Duration>( child: StreamBuilder<Duration>(
stream: player.stream.duration, stream: player.stream.duration,
initialData: player.state.duration, initialData: player.state.duration,
@@ -1967,8 +2116,8 @@ class _VideoControls extends StatelessWidget {
// Buffer progress track // Buffer progress track
if (maxMs > 0 && bufferMs > 0) if (maxMs > 0 && bufferMs > 0)
Positioned( Positioned(
left: 20, left: 14,
right: 20, right: 14,
child: ClipRRect( child: ClipRRect(
borderRadius: borderRadius:
BorderRadius.circular(2), BorderRadius.circular(2),
@@ -1976,10 +2125,12 @@ class _VideoControls extends StatelessWidget {
value: (bufferMs / maxMs) value: (bufferMs / maxMs)
.clamp(0.0, 1.0), .clamp(0.0, 1.0),
minHeight: 3.5, minHeight: 3.5,
backgroundColor: Colors.transparent, backgroundColor:
Colors.transparent,
valueColor: valueColor:
AlwaysStoppedAnimation( AlwaysStoppedAnimation(
Colors.white.withValues(alpha: 0.28), Colors.white
.withValues(alpha: 0.28),
), ),
), ),
), ),
@@ -1997,6 +2148,10 @@ class _VideoControls extends StatelessWidget {
const RoundSliderThumbShape( const RoundSliderThumbShape(
enabledThumbRadius: 6, enabledThumbRadius: 6,
), ),
overlayShape:
const RoundSliderOverlayShape(
overlayRadius: 14,
),
), ),
child: Slider( child: Slider(
value: valueMs, value: valueMs,
@@ -298,7 +298,7 @@ class _TagGroupBlock extends StatelessWidget {
required this.onLongPress, required this.onLongPress,
}); });
static const _collapsedLimit = 36; static const _collapsedLimit = 28;
final String label; final String label;
final String group; final String group;
@@ -320,13 +320,51 @@ class _TagGroupBlock extends StatelessWidget {
children: [ children: [
Row( Row(
children: [ children: [
Text(label, style: Theme.of(context).textTheme.labelLarge), Container(
const SizedBox(width: 8), width: 8,
Text( height: 8,
'${tags.length}', margin: const EdgeInsets.only(right: 8),
style: Theme.of(context).textTheme.labelMedium?.copyWith( decoration: BoxDecoration(
color: Theme.of(context).colorScheme.onSurfaceVariant, color: _headerDotColor(group, Theme.of(context)),
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: _headerDotColor(group, Theme.of(context))
.withValues(alpha: 0.55),
blurRadius: 5,
spreadRadius: 1,
), ),
],
),
),
Text(
label,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
letterSpacing: -0.1,
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 1.5),
decoration: BoxDecoration(
color: Theme.of(context).brightness == Brightness.dark
? Colors.white.withValues(alpha: 0.08)
: Colors.black.withValues(alpha: 0.05),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: Theme.of(context).brightness == Brightness.dark
? Colors.white.withValues(alpha: 0.12)
: Colors.black.withValues(alpha: 0.08),
),
),
child: Text(
'${tags.length}',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
), ),
], ],
), ),
@@ -338,6 +376,7 @@ class _TagGroupBlock extends StatelessWidget {
for (final tag in visibleTags) for (final tag in visibleTags)
TagChip( TagChip(
tag: tag, tag: tag,
group: group,
onTap: () => onTap(tag), onTap: () => onTap(tag),
onLongPress: () => onLongPress(tag), onLongPress: () => onLongPress(tag),
), ),
@@ -360,4 +399,17 @@ class _TagGroupBlock extends StatelessWidget {
), ),
); );
} }
static Color _headerDotColor(String group, ThemeData theme) {
return switch (group.toLowerCase()) {
'artist' => const Color(0xFFFF4757),
'character' => const Color(0xFF2ED573),
'copyright' => const Color(0xFFA55EEA),
'species' => const Color(0xFFFFA502),
'meta' => const Color(0xFF1E90FF),
_ => theme.colorScheme.primary,
};
}
} }
@@ -1,56 +1,334 @@
import 'dart:ui';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../backend/backend.dart'; import '../../../backend/backend.dart';
import '../../../core/utils/result.dart'; import '../../../core/utils/result.dart';
import '../../../shared/widgets/adaptive_scaffold.dart';
import '../../../shared/widgets/error_view.dart'; import '../../../shared/widgets/error_view.dart';
import 'providers_controller.dart'; import 'providers_controller.dart';
import 'widgets/provider_health_tile.dart'; import 'widgets/provider_health_tile.dart';
class ProviderCheckScreen extends ConsumerWidget { class ProviderCheckScreen extends ConsumerStatefulWidget {
const ProviderCheckScreen({super.key}); const ProviderCheckScreen({super.key});
@override @override
Widget build(BuildContext context, WidgetRef ref) { ConsumerState<ProviderCheckScreen> createState() =>
_ProviderCheckScreenState();
}
class _ProviderCheckScreenState extends ConsumerState<ProviderCheckScreen> {
bool _isCheckingAll = false;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final isRu = Localizations.maybeLocaleOf(context)?.languageCode == 'ru';
final providers = ref.watch(providersControllerProvider); final providers = ref.watch(providersControllerProvider);
final health = ref.watch(providerHealthProvider); final health = ref.watch(providerHealthProvider);
final diagnostics = ref.watch(providerDiagnosticsProvider).value ?? {}; final diagnostics = ref.watch(providerDiagnosticsProvider).value ?? {};
return AdaptiveScaffold( final bottomInset = MediaQuery.paddingOf(context).bottom;
title: 'Provider Check',
actions: [ return Scaffold(
IconButton( extendBodyBehindAppBar: true,
tooltip: 'Check all', appBar: PreferredSize(
onPressed: () => _checkAll(ref), preferredSize: const Size.fromHeight(60),
icon: const Icon(Icons.playlist_add_check_rounded), child: ClipRRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 18, sigmaY: 18),
child: AppBar(
backgroundColor: isDark
? theme.colorScheme.surface.withValues(alpha: 0.75)
: Colors.white.withValues(alpha: 0.85),
surfaceTintColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios_new_rounded, size: 20),
onPressed: () {
if (Navigator.of(context).canPop()) {
Navigator.of(context).pop();
} else {
context.go('/providers');
}
},
tooltip: isRu ? 'Назад' : 'Back',
),
title: Text(
isRu ? 'Проверка источников' : 'Provider Check',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
),
actions: [
Padding(
padding: const EdgeInsets.only(right: 12),
child: Material(
color: Colors.transparent,
borderRadius: BorderRadius.circular(14),
child: InkWell(
borderRadius: BorderRadius.circular(14),
onTap: _isCheckingAll ? null : () => _checkAll(ref),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF6366F1), Color(0xFF8B5CF6)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(14),
boxShadow: [
BoxShadow(
color: const Color(0xFF6366F1)
.withValues(alpha: 0.35),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (_isCheckingAll)
const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
else
const Icon(
Icons.playlist_add_check_rounded,
size: 16,
color: Colors.white,
),
const SizedBox(width: 5),
Text(
isRu ? 'Проверить все' : 'Check All',
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Colors.white,
),
),
],
),
),
),
),
),
],
),
),
), ),
], ),
body: providers.when( body: providers.when(
loading: () => const Center(child: CircularProgressIndicator()), loading: () => const Center(child: CircularProgressIndicator()),
error: (error, _) => ErrorView(message: error.toString()), error: (error, _) => ErrorView(message: error.toString()),
data: (items) => ListView.builder( data: (items) {
padding: const EdgeInsets.all(16), int onlineCount = 0;
itemCount: items.length, int offlineCount = 0;
itemBuilder: (context, index) { int pingSum = 0;
final item = items[index]; int pingCount = 0;
return ProviderHealthTile(
config: item, for (final item in items) {
health: health[item.id], final h = health[item.id];
diagnostics: diagnostics[item.id], if (h != null) {
onCheck: () => _checkOne(ref, item.id), if (h.status == ProviderStatus.online) {
); onlineCount++;
}, pingSum += h.pingMs;
), pingCount++;
} else if (h.status == ProviderStatus.offline) {
offlineCount++;
}
}
}
final avgPing =
pingCount > 0 ? (pingSum / pingCount).round() : null;
return Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 860),
child: ListView(
padding: EdgeInsets.fromLTRB(
16,
MediaQuery.paddingOf(context).top + 68,
16,
140 + bottomInset,
),
children: [
// Status Overview Card
Container(
margin: const EdgeInsets.only(bottom: 16),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: isDark
? [
theme.colorScheme.surfaceContainerHigh
.withValues(alpha: 0.65),
theme.colorScheme.surfaceContainerLow
.withValues(alpha: 0.40),
]
: [
Colors.white.withValues(alpha: 0.90),
Colors.white.withValues(alpha: 0.75),
],
),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.14)
: Colors.white.withValues(alpha: 0.85),
width: 1.1,
),
boxShadow: [
BoxShadow(
color: isDark
? Colors.black.withValues(alpha: 0.25)
: const Color(0xFF6366F1).withValues(alpha: 0.08),
blurRadius: 16,
offset: const Offset(0, 4),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 6,
children: [
Text(
isRu ? 'Состояние сети' : 'Network Health',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
),
if (avgPing != null)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: const Color(0xFF10B981).withValues(
alpha: isDark ? 0.16 : 0.10),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: const Color(0xFF10B981).withValues(
alpha: isDark ? 0.38 : 0.25),
),
),
child: Text(
'${isRu ? 'Средний пинг' : 'Avg ping'}: $avgPing ms',
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: Color(0xFF10B981),
fontFamily: 'monospace',
),
),
),
],
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: _MetricPill(
label: isRu ? 'Всего' : 'Total',
value: '${items.length}',
color: theme.colorScheme.primary,
isDark: isDark,
),
),
const SizedBox(width: 8),
Expanded(
child: _MetricPill(
label: isRu ? 'Онлайн' : 'Online',
value: '$onlineCount',
color: const Color(0xFF10B981),
isDark: isDark,
),
),
const SizedBox(width: 8),
Expanded(
child: _MetricPill(
label: isRu ? 'Офлайн' : 'Offline',
value: '$offlineCount',
color: const Color(0xFFEF4444),
isDark: isDark,
),
),
],
),
],
),
),
// Health Tiles List
if (items.isEmpty)
Container(
padding: const EdgeInsets.all(32),
decoration: BoxDecoration(
color: isDark
? theme.colorScheme.surfaceContainerHigh
.withValues(alpha: 0.40)
: Colors.white.withValues(alpha: 0.80),
borderRadius: BorderRadius.circular(24),
),
child: Center(
child: Text(
isRu ? 'Нет источников для проверки' : 'No providers to check',
style: theme.textTheme.bodyMedium,
),
),
)
else
...items.map((item) {
return ProviderHealthTile(
key: ValueKey(item.id),
config: item,
health: health[item.id],
diagnostics: diagnostics[item.id],
onCheck: () => _checkOne(ref, item.id),
);
}),
],
),
),
);
},
), ),
); );
} }
Future<void> _checkAll(WidgetRef ref) async { Future<void> _checkAll(WidgetRef ref) async {
final result = await ref.read(providerCheckServiceProvider).checkAll(); setState(() => _isCheckingAll = true);
if (result is Success<List<ProviderHealth>>) { HapticFeedback.mediumImpact();
ref.read(providerHealthProvider.notifier).state = { try {
for (final item in result.data) item.providerId: item, final result =
}; await ref.read(providerCheckServiceProvider).checkAll();
if (result is Success<List<ProviderHealth>>) {
ref.read(providerHealthProvider.notifier).state = {
for (final item in result.data) item.providerId: item,
};
}
} finally {
if (mounted) setState(() => _isCheckingAll = false);
} }
} }
@@ -65,3 +343,53 @@ class ProviderCheckScreen extends ConsumerWidget {
} }
} }
} }
class _MetricPill extends StatelessWidget {
const _MetricPill({
required this.label,
required this.value,
required this.color,
required this.isDark,
});
final String label;
final String value;
final Color color;
final bool isDark;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
decoration: BoxDecoration(
color: color.withValues(alpha: isDark ? 0.12 : 0.08),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: color.withValues(alpha: isDark ? 0.30 : 0.20),
width: 1,
),
),
child: Column(
children: [
Text(
value,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w800,
color: color,
),
),
const SizedBox(height: 1),
Text(
label,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: color.withValues(alpha: 0.85),
),
),
],
),
);
}
}
File diff suppressed because it is too large Load Diff
@@ -1,8 +1,9 @@
import 'dart:ui';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import '../../../shared/widgets/adaptive_scaffold.dart';
import '../../../shared/widgets/confirm_dialog.dart'; import '../../../shared/widgets/confirm_dialog.dart';
import '../../../shared/widgets/error_view.dart'; import '../../../shared/widgets/error_view.dart';
import 'providers_controller.dart'; import 'providers_controller.dart';
@@ -13,50 +14,371 @@ class ProvidersScreen extends ConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final isRu = Localizations.maybeLocaleOf(context)?.languageCode == 'ru';
final providers = ref.watch(providersControllerProvider); final providers = ref.watch(providersControllerProvider);
return AdaptiveScaffold( final bottomInset = MediaQuery.paddingOf(context).bottom;
title: 'Providers',
actions: [ return Scaffold(
IconButton( extendBodyBehindAppBar: true,
tooltip: 'Check providers', appBar: PreferredSize(
onPressed: () => context.go('/providers/check'), preferredSize: const Size.fromHeight(60),
icon: const Icon(Icons.network_check_rounded), child: ClipRRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 18, sigmaY: 18),
child: AppBar(
backgroundColor: isDark
? theme.colorScheme.surface.withValues(alpha: 0.72)
: Colors.white.withValues(alpha: 0.82),
surfaceTintColor: Colors.transparent,
elevation: 0,
centerTitle: false,
leading: Navigator.of(context).canPop()
? IconButton(
icon: const Icon(Icons.arrow_back_ios_new_rounded, size: 20),
onPressed: () => context.pop(),
tooltip: isRu ? 'Назад' : 'Back',
)
: null,
title: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 30,
height: 30,
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF6366F1), Color(0xFF8B5CF6)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(9),
boxShadow: [
BoxShadow(
color:
const Color(0xFF6366F1).withValues(alpha: 0.35),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: const Center(
child:
Icon(Icons.hub_rounded, size: 16, color: Colors.white),
),
),
const SizedBox(width: 8),
Flexible(
child: Text(
isRu ? 'Провайдеры' : 'Providers',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
overflow: TextOverflow.ellipsis,
),
),
],
),
actions: [
// Provider Check Glass Button
Padding(
padding: const EdgeInsets.only(right: 6),
child: Material(
color: Colors.transparent,
borderRadius: BorderRadius.circular(14),
child: InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () {
HapticFeedback.lightImpact();
context.push('/providers/check');
},
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: theme.colorScheme.primary
.withValues(alpha: isDark ? 0.16 : 0.10),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: theme.colorScheme.primary
.withValues(alpha: isDark ? 0.35 : 0.22),
width: 1,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.network_check_rounded,
size: 16,
color: theme.colorScheme.primary,
),
const SizedBox(width: 5),
Text(
isRu ? 'Проверка' : 'Check',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: theme.colorScheme.primary,
),
),
],
),
),
),
),
),
// Add Provider Accent Button
Padding(
padding: const EdgeInsets.only(right: 12),
child: Material(
color: Colors.transparent,
borderRadius: BorderRadius.circular(14),
child: InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () {
HapticFeedback.lightImpact();
context.push('/providers/new');
},
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF6366F1), Color(0xFF8B5CF6)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(14),
boxShadow: [
BoxShadow(
color: const Color(0xFF6366F1)
.withValues(alpha: 0.35),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.add_rounded,
size: 16,
color: Colors.white,
),
const SizedBox(width: 4),
Text(
isRu ? 'Создать' : 'Add',
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Colors.white,
),
),
],
),
),
),
),
),
],
),
),
), ),
IconButton( ),
tooltip: 'Add provider',
onPressed: () => context.go('/providers/new'),
icon: const Icon(Icons.add_rounded),
),
],
body: providers.when( body: providers.when(
loading: () => const Center(child: CircularProgressIndicator()), loading: () => const Center(child: CircularProgressIndicator()),
error: (error, _) => ErrorView(message: error.toString()), error: (error, _) => ErrorView(message: error.toString()),
data: (items) => ListView.builder( data: (items) {
padding: const EdgeInsets.all(16), final activeCount = items.where((p) => p.enabled).length;
itemCount: items.length,
itemBuilder: (context, index) { return Align(
final item = items[index]; alignment: Alignment.topCenter,
return ProviderCard( child: ConstrainedBox(
config: item, constraints: const BoxConstraints(maxWidth: 860),
onToggle: (enabled) => ref child: ListView(
.read(providersControllerProvider.notifier) padding: EdgeInsets.fromLTRB(
.toggle(item.id, enabled), 16,
onEdit: () => context.go('/providers/new', extra: item), MediaQuery.paddingOf(context).top + 68,
onDelete: () async { 16,
final ok = await showConfirmDialog( 140 + bottomInset,
context, ),
title: 'Delete provider', children: [
message: 'Remove ${item.name}?', // Overview Glass Card
); Container(
if (ok) { margin: const EdgeInsets.only(bottom: 16),
await ref padding: const EdgeInsets.all(16),
.read(providersControllerProvider.notifier) decoration: BoxDecoration(
.delete(item.id); borderRadius: BorderRadius.circular(22),
} gradient: LinearGradient(
}, begin: Alignment.topLeft,
); end: Alignment.bottomRight,
}, colors: isDark
), ? [
theme.colorScheme.surfaceContainerHigh
.withValues(alpha: 0.65),
theme.colorScheme.surfaceContainerLow
.withValues(alpha: 0.40),
]
: [
Colors.white.withValues(alpha: 0.90),
Colors.white.withValues(alpha: 0.75),
],
),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.14)
: Colors.white.withValues(alpha: 0.85),
width: 1.1,
),
boxShadow: [
BoxShadow(
color: isDark
? Colors.black.withValues(alpha: 0.25)
: const Color(0xFF6366F1).withValues(alpha: 0.08),
blurRadius: 16,
offset: const Offset(0, 4),
),
],
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isRu
? 'Управление источниками'
: 'Provider Management',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
),
const SizedBox(height: 4),
Text(
isRu
? 'Настройте подключение, API ключи и приоритеты booru-сервисов'
: 'Configure connections, API keys and search priorities',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
const SizedBox(width: 12),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFF10B981)
.withValues(alpha: isDark ? 0.16 : 0.10),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: const Color(0xFF10B981)
.withValues(alpha: isDark ? 0.40 : 0.28),
),
),
child: Text(
'$activeCount / ${items.length} ${isRu ? 'вкл' : 'on'}',
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Color(0xFF10B981),
),
),
),
],
),
),
// Empty State
if (items.isEmpty)
Container(
padding: const EdgeInsets.all(32),
decoration: BoxDecoration(
color: isDark
? theme.colorScheme.surfaceContainerHigh
.withValues(alpha: 0.40)
: Colors.white.withValues(alpha: 0.80),
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.10)
: Colors.white,
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.cloud_off_rounded,
size: 48,
color: theme.colorScheme.onSurfaceVariant
.withValues(alpha: 0.5),
),
const SizedBox(height: 12),
Text(
isRu
? 'Нет настроенных источников'
: 'No providers configured',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 6),
Text(
isRu
? 'Нажмите «Создать», чтобы добавить новый booru-провайдер'
: 'Tap "Add" to set up a new booru provider',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
],
),
)
else
// List of Provider Cards
...items.map((item) {
return ProviderCard(
key: ValueKey(item.id),
config: item,
onToggle: (enabled) => ref
.read(providersControllerProvider.notifier)
.toggle(item.id, enabled),
onEdit: () => context.push(
'/providers/new',
extra: item,
),
onDelete: () async {
final ok = await showConfirmDialog(
context,
title: isRu ? 'Удалить источник' : 'Delete provider',
message: isRu
? 'Вы действительно хотите удалить ${item.name}?'
: 'Remove ${item.name}?',
);
if (ok) {
await ref
.read(providersControllerProvider.notifier)
.delete(item.id);
}
},
);
}),
],
),
),
);
},
), ),
); );
} }
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../../backend/backend.dart'; import '../../../../backend/backend.dart';
@@ -18,27 +19,396 @@ class ProviderCard extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Card( final theme = Theme.of(context);
child: ListTile( final isDark = theme.brightness == Brightness.dark;
leading: Switch(value: config.enabled, onChanged: onToggle), final isRu = Localizations.maybeLocaleOf(context)?.languageCode == 'ru';
title: Text(config.name), final (engineColor, engineIcon, engineTitle) = _engineInfo(config.apiType);
subtitle: Text(
'${config.apiType} · ${config.baseUrl}\nPriority ${config.priority}'), return Container(
isThreeLine: true, margin: const EdgeInsets.only(bottom: 14),
trailing: Wrap( decoration: BoxDecoration(
spacing: 4, borderRadius: BorderRadius.circular(24),
children: [ boxShadow: [
IconButton( BoxShadow(
tooltip: 'Edit', color: isDark
onPressed: onEdit, ? Colors.black.withValues(alpha: 0.30)
icon: const Icon(Icons.edit_rounded), : engineColor.withValues(alpha: 0.08),
blurRadius: 18,
offset: const Offset(0, 6),
spreadRadius: -2,
),
BoxShadow(
color: engineColor.withValues(alpha: isDark ? 0.05 : 0.03),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(24),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: isDark
? [
theme.colorScheme.surfaceContainerHigh
.withValues(alpha: config.enabled ? 0.65 : 0.35),
theme.colorScheme.surfaceContainerLow
.withValues(alpha: config.enabled ? 0.45 : 0.20),
]
: [
Colors.white
.withValues(alpha: config.enabled ? 0.90 : 0.60),
Colors.white
.withValues(alpha: config.enabled ? 0.75 : 0.45),
],
), ),
IconButton( border: Border.all(
tooltip: 'Delete', color: isDark
onPressed: onDelete, ? (config.enabled
icon: const Icon(Icons.delete_rounded), ? engineColor.withValues(alpha: 0.28)
: Colors.white.withValues(alpha: 0.08))
: (config.enabled
? Colors.white.withValues(alpha: 0.90)
: Colors.white.withValues(alpha: 0.50)),
width: 1.2,
), ),
], ),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Row 1: Icon squircle + Name & details + Switch
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Engine Icon Squircle Badge
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: config.enabled
? [
engineColor,
engineColor.withValues(alpha: 0.80),
]
: [
Colors.grey.shade600,
Colors.grey.shade700,
],
),
borderRadius: BorderRadius.circular(14),
boxShadow: [
if (config.enabled)
BoxShadow(
color: engineColor.withValues(alpha: 0.38),
blurRadius: 10,
offset: const Offset(0, 3),
),
],
),
child: Center(
child: Icon(
engineIcon,
size: 22,
color: Colors.white,
),
),
),
const SizedBox(width: 14),
// Name & Sub-details
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Flexible(
child: Text(
config.name,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
color: config.enabled
? theme.colorScheme.onSurface
: theme.colorScheme.onSurface
.withValues(alpha: 0.6),
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 5),
Wrap(
spacing: 6,
runSpacing: 4,
children: [
// Engine badge
_GlassPill(
label: engineTitle,
color: engineColor,
isDark: isDark,
),
// Priority badge
_GlassPill(
label: '${isRu ? 'Приоритет' : 'Priority'} ${config.priority}',
color: theme.colorScheme.primary,
isDark: isDark,
),
],
),
],
),
),
// Switch
Transform.scale(
scale: 0.9,
child: Switch.adaptive(
value: config.enabled,
onChanged: (val) {
HapticFeedback.selectionClick();
onToggle(val);
},
activeThumbColor: engineColor,
activeTrackColor: engineColor.withValues(alpha: 0.45),
),
),
],
),
const SizedBox(height: 12),
// Row 2: Base URL glass chip
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: isDark
? Colors.black.withValues(alpha: 0.20)
: theme.colorScheme.surfaceContainerHighest
.withValues(alpha: 0.40),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.06)
: Colors.black.withValues(alpha: 0.05),
),
),
child: Row(
children: [
Icon(
Icons.link_rounded,
size: 14,
color: theme.colorScheme.onSurfaceVariant
.withValues(alpha: 0.8),
),
const SizedBox(width: 6),
Expanded(
child: Text(
config.baseUrl,
style: TextStyle(
fontSize: 12,
fontFamily: 'monospace',
color: theme.colorScheme.onSurfaceVariant,
letterSpacing: -0.1,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
const SizedBox(height: 12),
// Row 3: Action Buttons (Edit & Delete)
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
// Edit Action Button
_GlassActionButton(
icon: Icons.edit_rounded,
label: isRu ? 'Изменить' : 'Edit',
color: theme.colorScheme.primary,
isDark: isDark,
onTap: () {
HapticFeedback.lightImpact();
onEdit();
},
),
const SizedBox(width: 8),
// Delete Action Button
_GlassActionButton(
icon: Icons.delete_outline_rounded,
label: isRu ? 'Удалить' : 'Delete',
color: const Color(0xFFEF4444),
isDark: isDark,
onTap: () {
HapticFeedback.lightImpact();
onDelete();
},
),
],
),
],
),
),
),
);
}
static (Color, IconData, String) _engineInfo(String apiType) {
return switch (apiType.toLowerCase()) {
'gelbooru' => (
const Color(0xFF10B981),
Icons.image_search_rounded,
'Gelbooru',
),
'rule34' => (
const Color(0xFF84CC16),
Icons.photo_library_rounded,
'Rule34',
),
'paheal' => (
const Color(0xFFF97316),
Icons.filter_hdr_rounded,
'Paheal HTML',
),
'realbooru_html' => (
const Color(0xFFEAB308),
Icons.camera_alt_rounded,
'Realbooru HTML',
),
'danbooru' => (
const Color(0xFF3B82F6),
Icons.auto_awesome_rounded,
'Danbooru',
),
'moebooru' => (
const Color(0xFF8B5CF6),
Icons.face_retouching_natural_rounded,
'Moebooru',
),
'e621' => (
const Color(0xFFF59E0B),
Icons.pets_rounded,
'e621 / e926',
),
'kemono' => (
const Color(0xFFEC4899),
Icons.palette_rounded,
'Kemono',
),
'coomer' => (
const Color(0xFF06B6D4),
Icons.collections_rounded,
'Coomer',
),
_ => (
const Color(0xFF6366F1),
Icons.hub_rounded,
apiType.isEmpty ? 'Custom' : apiType,
),
};
}
}
class _GlassPill extends StatelessWidget {
const _GlassPill({
required this.label,
required this.color,
required this.isDark,
});
final String label;
final Color color;
final bool isDark;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: color.withValues(alpha: isDark ? 0.16 : 0.10),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: color.withValues(alpha: isDark ? 0.35 : 0.25),
width: 1,
),
),
child: Text(
label,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: color,
letterSpacing: -0.2,
),
),
);
}
}
class _GlassActionButton extends StatelessWidget {
const _GlassActionButton({
required this.icon,
required this.label,
required this.color,
required this.isDark,
required this.onTap,
});
final IconData icon;
final String label;
final Color color;
final bool isDark;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
borderRadius: BorderRadius.circular(12),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: color.withValues(alpha: isDark ? 0.14 : 0.08),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: color.withValues(alpha: isDark ? 0.32 : 0.22),
width: 1,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: color),
const SizedBox(width: 5),
Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: color,
letterSpacing: -0.1,
),
),
],
),
), ),
), ),
); );
@@ -1,9 +1,10 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../../backend/backend.dart'; import '../../../../backend/backend.dart';
import '../../../../shared/widgets/provider_status_badge.dart'; import '../../../../shared/widgets/provider_status_badge.dart';
class ProviderHealthTile extends StatelessWidget { class ProviderHealthTile extends StatefulWidget {
const ProviderHealthTile({ const ProviderHealthTile({
required this.config, required this.config,
required this.health, required this.health,
@@ -17,59 +18,408 @@ class ProviderHealthTile extends StatelessWidget {
final ProviderDiagnostics? diagnostics; final ProviderDiagnostics? diagnostics;
final VoidCallback onCheck; final VoidCallback onCheck;
@override
State<ProviderHealthTile> createState() => _ProviderHealthTileState();
}
class _ProviderHealthTileState extends State<ProviderHealthTile> {
bool _expanded = false;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final isRu = Localizations.maybeLocaleOf(context)?.languageCode == 'ru';
final config = widget.config;
final health = widget.health;
final diagnostics = widget.diagnostics;
final hint = ProviderQualityHint.from( final hint = ProviderQualityHint.from(
config: config, config: config,
health: health, health: health,
diagnostics: diagnostics, diagnostics: diagnostics,
isRu: isRu,
); );
return Card(
child: ExpansionTile( final status = health?.status ?? ProviderStatus.unknown;
leading: ProviderStatusBadge(health: health), final statusColor = switch (status) {
title: Text(config.name), ProviderStatus.online => (health != null && health.pingMs > 2500)
subtitle: Wrap( ? const Color(0xFFF59E0B)
spacing: 8, : const Color(0xFF10B981),
runSpacing: 6, ProviderStatus.offline => const Color(0xFFEF4444),
crossAxisAlignment: WrapCrossAlignment.center, ProviderStatus.unknown => const Color(0xFF94A3B8),
children: [ };
Chip(
avatar: Icon(hint.icon, size: 16), final hasError = diagnostics?.lastErrorMessage != null ||
label: Text(hint.label), health?.errorMessage != null;
visualDensity: VisualDensity.compact, final errorMessage = diagnostics?.lastErrorMessage ?? health?.errorMessage;
backgroundColor: hint.color(context).withValues(alpha: 0.16),
side: return Container(
BorderSide(color: hint.color(context).withValues(alpha: 0.4)), margin: const EdgeInsets.only(bottom: 14),
), decoration: BoxDecoration(
Text('${config.apiType} | priority ${config.priority}'), borderRadius: BorderRadius.circular(22),
], boxShadow: [
), BoxShadow(
trailing: IconButton( color: isDark
tooltip: 'Check', ? Colors.black.withValues(alpha: 0.30)
onPressed: onCheck, : statusColor.withValues(alpha: 0.08),
icon: const Icon(Icons.network_check_rounded), blurRadius: 18,
), offset: const Offset(0, 6),
childrenPadding: const EdgeInsets.fromLTRB(16, 0, 16, 14), spreadRadius: -2,
children: [ ),
Align( BoxShadow(
alignment: Alignment.centerLeft, color: statusColor.withValues(alpha: isDark ? 0.06 : 0.03),
child: Text( blurRadius: 10,
[ offset: const Offset(0, 2),
'${config.enabled ? 'Enabled' : 'Disabled'} | ${config.baseUrl}',
if (health != null) 'Ping ${health!.pingMs} ms',
if (health?.apiVersion != null) 'API ${health!.apiVersion}',
if (health?.lastCheckedAt != null)
'Checked ${health!.lastCheckedAt}',
if (diagnostics != null)
'Last search: ${diagnostics!.lastResultCount} posts at ${diagnostics!.lastSearchAt}',
if (diagnostics?.lastErrorMessage != null)
diagnostics!.lastErrorMessage!,
if (health?.errorMessage != null) health!.errorMessage!,
].join('\n'),
),
), ),
], ],
), ),
child: ClipRRect(
borderRadius: BorderRadius.circular(22),
child: AnimatedContainer(
duration: const Duration(milliseconds: 250),
curve: Curves.easeOutCubic,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: isDark
? [
theme.colorScheme.surfaceContainerHigh
.withValues(alpha: 0.65),
theme.colorScheme.surfaceContainerLow
.withValues(alpha: 0.40),
]
: [
Colors.white.withValues(alpha: 0.92),
Colors.white.withValues(alpha: 0.78),
],
),
border: Border.all(
color: isDark
? statusColor.withValues(alpha: 0.30)
: Colors.white.withValues(alpha: 0.90),
width: 1.2,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header Tile
InkWell(
onTap: () {
HapticFeedback.selectionClick();
setState(() => _expanded = !_expanded);
},
borderRadius: BorderRadius.circular(22),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
// Status Badge with glowing LED
ProviderStatusBadge(health: health),
const SizedBox(width: 12),
// Name & Badges
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
config.name,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 5),
Wrap(
spacing: 6,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
// Ping chip if available
if (health != null)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7, vertical: 2.5),
decoration: BoxDecoration(
color: statusColor.withValues(
alpha: isDark ? 0.16 : 0.10),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: statusColor.withValues(
alpha: isDark ? 0.38 : 0.25),
width: 1,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.bolt_rounded,
size: 12,
color: statusColor,
),
const SizedBox(width: 3),
Text(
'${health.pingMs} ms',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: statusColor,
fontFamily: 'monospace',
),
),
],
),
),
// Quality Hint Chip
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7, vertical: 2.5),
decoration: BoxDecoration(
color: hint.color(context).withValues(
alpha: isDark ? 0.14 : 0.08),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: hint.color(context).withValues(
alpha: isDark ? 0.32 : 0.20),
width: 1,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
hint.icon,
size: 12,
color: hint.color(context),
),
const SizedBox(width: 4),
Text(
hint.label,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: hint.color(context),
letterSpacing: -0.1,
),
),
],
),
),
],
),
],
),
),
// Check Button
IconButton(
tooltip: isRu ? 'Проверить' : 'Check',
onPressed: () {
HapticFeedback.lightImpact();
widget.onCheck();
},
icon: Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: theme.colorScheme.primary
.withValues(alpha: isDark ? 0.18 : 0.10),
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.primary
.withValues(alpha: isDark ? 0.40 : 0.25),
),
),
child: Center(
child: Icon(
Icons.refresh_rounded,
size: 18,
color: theme.colorScheme.primary,
),
),
),
),
// Expand Chevron
Icon(
_expanded
? Icons.keyboard_arrow_up_rounded
: Icons.keyboard_arrow_down_rounded,
size: 20,
color: theme.colorScheme.onSurfaceVariant,
),
],
),
),
),
// Expanded Diagnostics Section
if (_expanded) ...[
Divider(
height: 1,
thickness: 1,
color: isDark
? Colors.white.withValues(alpha: 0.08)
: Colors.black.withValues(alpha: 0.05),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Diagnostic row 1: URL & Enabled
_DiagItem(
icon: Icons.link_rounded,
label: isRu ? 'Сервер' : 'Endpoint',
value: '${config.baseUrl} (${config.enabled ? (isRu ? 'Активен' : 'Enabled') : (isRu ? 'Выключен' : 'Disabled')})',
isMonospace: true,
),
const SizedBox(height: 8),
// Diagnostic row 2: API Type & Priority
_DiagItem(
icon: Icons.hub_outlined,
label: isRu ? 'Движок и приоритет' : 'Engine & Priority',
value: '${config.apiType} · ${isRu ? 'приоритет' : 'priority'} ${config.priority}',
),
const SizedBox(height: 8),
// Diagnostic row 3: API Version
if (health?.apiVersion != null) ...[
_DiagItem(
icon: Icons.info_outline_rounded,
label: isRu ? 'Версия API' : 'API Version',
value: health!.apiVersion!,
),
const SizedBox(height: 8),
],
// Diagnostic row 4: Last Checked Time
if (health?.lastCheckedAt != null) ...[
_DiagItem(
icon: Icons.schedule_rounded,
label: isRu ? 'Проверено' : 'Last Checked',
value: health!.lastCheckedAt.toString().split('.').first,
isMonospace: true,
),
const SizedBox(height: 8),
],
// Diagnostic row 5: Last Search
if (diagnostics != null) ...[
_DiagItem(
icon: Icons.search_rounded,
label: isRu ? 'Последний поиск' : 'Last Search',
value: isRu
? '${diagnostics.lastResultCount} постов получено в ${diagnostics.lastSearchAt.toString().split('.').first}'
: '${diagnostics.lastResultCount} posts retrieved at ${diagnostics.lastSearchAt.toString().split('.').first}',
),
const SizedBox(height: 8),
],
// Error Box (if any)
if (hasError && errorMessage != null) ...[
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFFEF4444)
.withValues(alpha: isDark ? 0.16 : 0.08),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: const Color(0xFFEF4444)
.withValues(alpha: isDark ? 0.38 : 0.25),
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.error_outline_rounded,
size: 16,
color: Color(0xFFEF4444),
),
const SizedBox(width: 8),
Expanded(
child: Text(
errorMessage,
style: const TextStyle(
fontSize: 12,
fontFamily: 'monospace',
color: Color(0xFFEF4444),
height: 1.35,
),
),
),
],
),
),
],
],
),
),
],
],
),
),
),
);
}
}
class _DiagItem extends StatelessWidget {
const _DiagItem({
required this.icon,
required this.label,
required this.value,
this.isMonospace = false,
});
final IconData icon;
final String label;
final String value;
final bool isMonospace;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
icon,
size: 15,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7),
),
const SizedBox(width: 8),
Text(
'$label: ',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSurfaceVariant,
),
),
Expanded(
child: Text(
value,
style: TextStyle(
fontSize: 12,
fontFamily: isMonospace ? 'monospace' : null,
color: theme.colorScheme.onSurface,
),
),
),
],
); );
} }
} }
@@ -87,10 +437,11 @@ class ProviderQualityHint {
required ContentProviderConfig config, required ContentProviderConfig config,
required ProviderHealth? health, required ProviderHealth? health,
required ProviderDiagnostics? diagnostics, required ProviderDiagnostics? diagnostics,
required bool isRu,
}) { }) {
if (!config.enabled) { if (!config.enabled) {
return ProviderQualityHint._( return ProviderQualityHint._(
'Disabled', isRu ? 'Выключен' : 'Disabled',
Icons.pause_circle_outline_rounded, Icons.pause_circle_outline_rounded,
(scheme) => scheme.outline, (scheme) => scheme.outline,
); );
@@ -98,34 +449,34 @@ class ProviderQualityHint {
if (diagnostics?.lastErrorMessage != null || if (diagnostics?.lastErrorMessage != null ||
health?.status == ProviderStatus.offline) { health?.status == ProviderStatus.offline) {
return ProviderQualityHint._( return ProviderQualityHint._(
'Search failing', isRu ? 'Ошибка поиска' : 'Search failing',
Icons.error_outline_rounded, Icons.error_outline_rounded,
(scheme) => scheme.error, (scheme) => scheme.error,
); );
} }
if (diagnostics != null && diagnostics.lastResultCount == 0) { if (diagnostics != null && diagnostics.lastResultCount == 0) {
return ProviderQualityHint._( return ProviderQualityHint._(
'No recent results', isRu ? 'Нет результатов' : 'No recent results',
Icons.search_off_rounded, Icons.search_off_rounded,
(scheme) => scheme.tertiary, (scheme) => scheme.tertiary,
); );
} }
if (health != null && health.pingMs > 2500) { if (health != null && health.pingMs > 2500) {
return ProviderQualityHint._( return ProviderQualityHint._(
'Slow', isRu ? 'Медленно' : 'Slow',
Icons.speed_rounded, Icons.speed_rounded,
(scheme) => scheme.secondary, (scheme) => scheme.secondary,
); );
} }
if (health != null || diagnostics != null) { if (health != null || diagnostics != null) {
return ProviderQualityHint._( return ProviderQualityHint._(
'Healthy', isRu ? 'Стабилен' : 'Healthy',
Icons.check_circle_outline_rounded, Icons.check_circle_outline_rounded,
(scheme) => scheme.primary, (scheme) => scheme.primary,
); );
} }
return ProviderQualityHint._( return ProviderQualityHint._(
'Not checked', isRu ? 'Не проверен' : 'Not checked',
Icons.help_outline_rounded, Icons.help_outline_rounded,
(scheme) => scheme.outline, (scheme) => scheme.outline,
); );
@@ -1,4 +1,7 @@
import 'dart:ui';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
@@ -47,6 +50,7 @@ class _SearchScreenState extends ConsumerState<SearchScreen> {
final strings = AppStrings(settings.languageCode); final strings = AppStrings(settings.languageCode);
final isRu = strings.ru; final isRu = strings.ru;
final theme = Theme.of(context); final theme = Theme.of(context);
final bottomInset = MediaQuery.paddingOf(context).bottom;
return AdaptiveScaffold( return AdaptiveScaffold(
title: strings.search, title: strings.search,
@@ -78,19 +82,12 @@ class _SearchScreenState extends ConsumerState<SearchScreen> {
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 860), constraints: const BoxConstraints(maxWidth: 860),
child: ListView( child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), // Extended bottom padding so the cheat sheet card is never obscured by the floating dock
padding: EdgeInsets.fromLTRB(16, 14, 16, 140 + bottomInset),
children: [ children: [
// 1. Search Bar with Quick Operators // 1. Search Bar with Quick Operators
Container( _SearchLiquidCard(
padding: const EdgeInsets.all(16), glowColor: theme.colorScheme.primary,
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: theme.colorScheme.outlineVariant
.withValues(alpha: 0.3),
),
),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
@@ -171,45 +168,124 @@ class _SearchScreenState extends ConsumerState<SearchScreen> {
const SizedBox(height: 16), const SizedBox(height: 16),
// 2. Recent Searches Card // 2. Recent Searches Card
_SearchSectionCard( _SearchLiquidCard(
icon: Icons.history_rounded, glowColor: const Color(0xFF6366F1),
accentColor: const Color(0xFF6366F1), child: Column(
title: isRu ? 'Недавние запросы' : 'Recent searches', crossAxisAlignment: CrossAxisAlignment.start,
badgeCount: data.recent.length, children: [
trailing: data.recent.isEmpty Row(
? null children: [
: TextButton( const _SearchIconBadge(
onPressed: () => ref icon: Icons.history_rounded,
.read(searchControllerProvider.notifier) color: Color(0xFF6366F1),
.clearHistory(), ),
child: Text( const SizedBox(width: 12),
isRu ? 'Очистить' : 'Clear', Expanded(
style: TextStyle( child: Row(
color: theme.colorScheme.primary, mainAxisSize: MainAxisSize.min,
fontSize: 13, children: [
fontWeight: FontWeight.w600, Flexible(
child: Text(
isRu ? 'Недавние запросы' : 'Recent searches',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
fontSize: 15,
letterSpacing: -0.2,
),
),
),
if (data.recent.isNotEmpty) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7, vertical: 2),
decoration: BoxDecoration(
color: const Color(0xFF6366F1)
.withValues(alpha: 0.16),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'${data.recent.map((e) => e.query.trim().toLowerCase()).where((q) => q.isNotEmpty).toSet().length}',
style: theme.textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.bold,
color: const Color(0xFF6366F1),
),
),
),
],
],
), ),
), ),
), if (data.recent.isNotEmpty)
child: RecentSearches( TextButton(
items: data.recent, style: TextButton.styleFrom(
onTap: (query) => visualDensity: VisualDensity.compact,
context.go('/?q=${Uri.encodeQueryComponent(query)}'), padding: const EdgeInsets.symmetric(
onDelete: (id) => ref horizontal: 10, vertical: 4),
.read(searchControllerProvider.notifier) minimumSize: Size.zero,
.deleteHistory(id), tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
onPressed: () {
HapticFeedback.selectionClick();
ref
.read(searchControllerProvider.notifier)
.clearHistory();
},
child: Text(
isRu ? 'Очистить' : 'Clear',
style: TextStyle(
color: theme.colorScheme.primary,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
],
),
const SizedBox(height: 14),
RecentSearches(
items: data.recent,
onTap: (query) =>
context.go('/?q=${Uri.encodeQueryComponent(query)}'),
onDelete: (id) => ref
.read(searchControllerProvider.notifier)
.deleteHistory(id),
),
],
), ),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
// 3. Explore Popular Categories & Tags // 3. Explore Popular Categories & Tags
_SearchSectionCard( _SearchLiquidCard(
icon: Icons.explore_rounded, glowColor: const Color(0xFF10B981),
accentColor: const Color(0xFF10B981),
title: isRu ? 'Популярные категории' : 'Explore categories',
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Row(
children: [
const _SearchIconBadge(
icon: Icons.explore_rounded,
color: Color(0xFF10B981),
),
const SizedBox(width: 12),
Expanded(
child: Text(
isRu ? 'Популярные категории' : 'Explore categories',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
fontSize: 15,
letterSpacing: -0.2,
),
),
),
],
),
const SizedBox(height: 16),
_CategoryTagRow( _CategoryTagRow(
categoryName: isRu ? 'Тематика' : 'Theme & Ambience', categoryName: isRu ? 'Тематика' : 'Theme & Ambience',
color: const Color(0xFF0EA5E9), color: const Color(0xFF0EA5E9),
@@ -223,7 +299,7 @@ class _SearchScreenState extends ConsumerState<SearchScreen> {
], ],
onTap: (tag) => _onTagTap(tag, data.query), onTap: (tag) => _onTagTap(tag, data.query),
), ),
const SizedBox(height: 14), const SizedBox(height: 16),
_CategoryTagRow( _CategoryTagRow(
categoryName: categoryName:
isRu ? 'Персонажи и детали' : 'Characters & Attire', isRu ? 'Персонажи и детали' : 'Characters & Attire',
@@ -239,7 +315,7 @@ class _SearchScreenState extends ConsumerState<SearchScreen> {
], ],
onTap: (tag) => _onTagTap(tag, data.query), onTap: (tag) => _onTagTap(tag, data.query),
), ),
const SizedBox(height: 14), const SizedBox(height: 16),
_CategoryTagRow( _CategoryTagRow(
categoryName: isRu ? 'Провайдеры' : 'Providers', categoryName: isRu ? 'Провайдеры' : 'Providers',
color: const Color(0xFF8B5CF6), color: const Color(0xFF8B5CF6),
@@ -257,84 +333,78 @@ class _SearchScreenState extends ConsumerState<SearchScreen> {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
// 4. Search Tips / Cheat Sheet Card // 4. Search Tips / Cheat Sheet Card (Full Liquid Glass Container)
Container( _SearchLiquidCard(
decoration: BoxDecoration( padding: EdgeInsets.zero,
color: theme.colorScheme.surfaceContainerLow, glowColor: const Color(0xFFF59E0B),
borderRadius: BorderRadius.circular(20), child: Theme(
border: Border.all( data: theme.copyWith(dividerColor: Colors.transparent),
color: theme.colorScheme.outlineVariant child: ExpansionTile(
.withValues(alpha: 0.3), shape: const Border(),
), collapsedShape: const Border(),
), tilePadding: const EdgeInsets.symmetric(
child: ExpansionTile( horizontal: 16, vertical: 4),
shape: const Border(), leading: const _SearchIconBadge(
collapsedShape: const Border(), icon: Icons.lightbulb_rounded,
leading: Container(
width: 32,
height: 32,
decoration: BoxDecoration(
color: const Color(0xFFF59E0B).withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(10),
),
child: const Icon(
Icons.lightbulb_outline_rounded,
size: 18,
color: Color(0xFFF59E0B), color: Color(0xFFF59E0B),
), ),
), title: Text(
title: Text( isRu ? 'Шпаргалка по поиску' : 'Search tips & operators',
isRu ? 'Шпаргалка по поиску' : 'Search tips & operators', style: theme.textTheme.titleSmall?.copyWith(
style: theme.textTheme.titleSmall?.copyWith( fontWeight: FontWeight.w700,
fontWeight: FontWeight.w700, letterSpacing: -0.2,
),
),
initiallyExpanded: _showTips,
onExpansionChanged: (exp) => setState(() => _showTips = exp),
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_TipRow(
code: 'tag_a and tag_b',
description: isRu
? 'Независимый опрос обоих тегов с чередованием постов в ленте.'
: 'Interleaves results from both queries independently.',
),
const SizedBox(height: 8),
_TipRow(
code: 'type:video / type:gif',
description: isRu
? 'Показывает только видео или анимированные GIF.'
: 'Filters results to only videos or animated GIFs.',
),
const SizedBox(height: 8),
_TipRow(
code: 'rating:safe / rating:explicit',
description: isRu
? 'Фильтр по возрастному рейтингу медиа.'
: 'Filter by age rating classification.',
),
const SizedBox(height: 8),
_TipRow(
code: 'score:>50 / score:>100',
description: isRu
? 'Посты с оценкой пользователей выше указанной.'
: 'Posts with community score greater than threshold.',
),
const SizedBox(height: 8),
_TipRow(
code: 'provider:gelbooru',
description: isRu
? 'Поиск исключительно в указанном источнике.'
: 'Search specifically on the given booru provider.',
),
],
), ),
), ),
], initiallyExpanded: _showTips,
onExpansionChanged: (exp) {
HapticFeedback.selectionClick();
setState(() => _showTips = exp);
},
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_TipRow(
code: 'tag_a and tag_b',
description: isRu
? 'Независимый опрос обоих тегов с чередованием постов в ленте.'
: 'Interleaves results from both queries independently.',
),
const SizedBox(height: 8),
_TipRow(
code: 'type:video / type:gif',
description: isRu
? 'Показывает только видео или анимированные GIF.'
: 'Filters results to only videos or animated GIFs.',
),
const SizedBox(height: 8),
_TipRow(
code: 'rating:safe / rating:explicit',
description: isRu
? 'Фильтр по возрастному рейтингу медиа.'
: 'Filter by age rating classification.',
),
const SizedBox(height: 8),
_TipRow(
code: 'score:>50 / score:>100',
description: isRu
? 'Посты с оценкой пользователей выше указанной.'
: 'Posts with community score greater than threshold.',
),
const SizedBox(height: 8),
_TipRow(
code: 'provider:gelbooru',
description: isRu
? 'Поиск исключительно в указанном источнике.'
: 'Search specifically on the given booru provider.',
),
],
),
),
],
),
), ),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
@@ -347,91 +417,117 @@ class _SearchScreenState extends ConsumerState<SearchScreen> {
} }
} }
class _SearchSectionCard extends StatelessWidget { class _SearchLiquidCard extends StatelessWidget {
const _SearchSectionCard({ const _SearchLiquidCard({
required this.icon,
required this.accentColor,
required this.title,
required this.child, required this.child,
this.badgeCount, this.padding,
this.trailing, this.glowColor,
}); });
final IconData icon;
final Color accentColor;
final String title;
final Widget child; final Widget child;
final int? badgeCount; final EdgeInsetsGeometry? padding;
final Widget? trailing; final Color? glowColor;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final accent = glowColor ?? theme.colorScheme.primary;
return Container( return Container(
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerLow, borderRadius: BorderRadius.circular(24),
borderRadius: BorderRadius.circular(20), boxShadow: [
border: Border.all( BoxShadow(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.3), color: isDark
? Colors.black.withValues(alpha: 0.35)
: accent.withValues(alpha: 0.08),
blurRadius: 18,
offset: const Offset(0, 6),
spreadRadius: -2,
),
BoxShadow(
color: accent.withValues(alpha: isDark ? 0.06 : 0.03),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(24),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 18, sigmaY: 18),
child: Container(
padding: padding ?? const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: isDark
? [
theme.colorScheme.surfaceContainerHigh
.withValues(alpha: 0.60),
theme.colorScheme.surfaceContainerLow
.withValues(alpha: 0.38),
]
: [
Colors.white.withValues(alpha: 0.88),
Colors.white.withValues(alpha: 0.72),
],
),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.14)
: Colors.white.withValues(alpha: 0.85),
width: 1.2,
),
),
child: child,
),
), ),
), ),
padding: const EdgeInsets.all(16), );
child: Column( }
crossAxisAlignment: CrossAxisAlignment.start, }
children: [
Row( class _SearchIconBadge extends StatelessWidget {
children: [ const _SearchIconBadge({
Container( required this.icon,
width: 32, required this.color,
height: 32, });
decoration: BoxDecoration(
color: accentColor.withValues(alpha: 0.14), final IconData icon;
borderRadius: BorderRadius.circular(10), final Color color;
),
child: Icon(icon, size: 18, color: accentColor), @override
), Widget build(BuildContext context) {
const SizedBox(width: 12), const size = 34.0;
Expanded( const iconSize = 18.0;
child: Row( return Container(
children: [ width: size,
Flexible( height: size,
child: Text( decoration: BoxDecoration(
title, gradient: LinearGradient(
maxLines: 1, begin: Alignment.topLeft,
overflow: TextOverflow.ellipsis, end: Alignment.bottomRight,
style: theme.textTheme.titleMedium?.copyWith( colors: [
fontWeight: FontWeight.w700, color,
), color.withValues(alpha: 0.86),
), ],
), ),
if (badgeCount != null && badgeCount! > 0) ...[ borderRadius: BorderRadius.circular(size * 0.28),
const SizedBox(width: 8), boxShadow: [
Container( BoxShadow(
padding: const EdgeInsets.symmetric( color: color.withValues(alpha: 0.35),
horizontal: 8, vertical: 2), blurRadius: 7,
decoration: BoxDecoration( offset: const Offset(0, 2.5),
color: accentColor.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(10),
),
child: Text(
'$badgeCount',
style: theme.textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.bold,
color: accentColor,
),
),
),
],
],
),
),
if (trailing != null) trailing!,
],
), ),
const SizedBox(height: 14),
child,
], ],
), ),
child: Center(
child: Icon(icon, size: iconSize, color: Colors.white),
),
); );
} }
} }
@@ -452,19 +548,33 @@ class _QuickOperatorChip extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
return Material( return Material(
color: color.withValues(alpha: 0.12), color: Colors.transparent,
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(14),
child: InkWell( child: InkWell(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(14),
onTap: onTap, onTap: () {
HapticFeedback.selectionClick();
onTap();
},
child: Container( child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12), color: color.withValues(alpha: isDark ? 0.16 : 0.10),
borderRadius: BorderRadius.circular(14),
border: Border.all( border: Border.all(
color: color.withValues(alpha: 0.35), color: color.withValues(alpha: isDark ? 0.40 : 0.32),
width: 1.1,
), ),
boxShadow: [
BoxShadow(
color: color.withValues(alpha: isDark ? 0.14 : 0.06),
blurRadius: 6,
offset: const Offset(0, 1.5),
),
],
), ),
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -477,6 +587,7 @@ class _QuickOperatorChip extends StatelessWidget {
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
color: color, color: color,
fontFamily: 'monospace', fontFamily: 'monospace',
letterSpacing: -0.2,
), ),
), ),
], ],
@@ -503,44 +614,76 @@ class _CategoryTagRow extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Row(
categoryName, children: [
style: theme.textTheme.labelLarge?.copyWith( Container(
fontWeight: FontWeight.w600, width: 7,
color: theme.colorScheme.onSurfaceVariant, height: 7,
), decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: color.withValues(alpha: 0.6),
blurRadius: 4,
),
],
),
),
const SizedBox(width: 8),
Text(
categoryName,
style: theme.textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.w700,
color: theme.colorScheme.onSurface,
letterSpacing: -0.2,
),
),
],
), ),
const SizedBox(height: 8), const SizedBox(height: 10),
Wrap( Wrap(
spacing: 8, spacing: 8,
runSpacing: 8, runSpacing: 8,
children: [ children: [
for (final tag in tags) for (final tag in tags)
Material( Material(
color: theme.colorScheme.surfaceContainer, color: Colors.transparent,
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(14),
child: InkWell( child: InkWell(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(14),
onTap: () => onTap(tag), onTap: () {
HapticFeedback.selectionClick();
onTap(tag);
},
child: Container( child: Container(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 5), horizontal: 11, vertical: 6),
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12), color: isDark
? theme.colorScheme.surfaceContainerHighest
.withValues(alpha: 0.45)
: Colors.white.withValues(alpha: 0.60),
borderRadius: BorderRadius.circular(14),
border: Border.all( border: Border.all(
color: theme.colorScheme.outlineVariant color: isDark
.withValues(alpha: 0.3), ? Colors.white.withValues(alpha: 0.10)
: theme.colorScheme.outlineVariant
.withValues(alpha: 0.35),
width: 1.0,
), ),
), ),
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Container( Container(
width: 6, width: 5,
height: 6, height: 5,
decoration: BoxDecoration( decoration: BoxDecoration(
color: color, color: color,
shape: BoxShape.circle, shape: BoxShape.circle,
@@ -550,7 +693,8 @@ class _CategoryTagRow extends StatelessWidget {
Text( Text(
tag, tag,
style: theme.textTheme.bodySmall?.copyWith( style: theme.textTheme.bodySmall?.copyWith(
fontWeight: FontWeight.w500, fontWeight: FontWeight.w600,
letterSpacing: -0.1,
), ),
), ),
], ],
@@ -574,14 +718,23 @@ class _TipRow extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
return Row( return Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Container( Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest, color: isDark
borderRadius: BorderRadius.circular(6), ? theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.6)
: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.8),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.08)
: theme.colorScheme.outlineVariant.withValues(alpha: 0.25),
),
), ),
child: Text( child: Text(
code, code,
@@ -595,10 +748,14 @@ class _TipRow extends StatelessWidget {
), ),
const SizedBox(width: 10), const SizedBox(width: 10),
Expanded( Expanded(
child: Text( child: Padding(
description, padding: const EdgeInsets.only(top: 2),
style: theme.textTheme.bodySmall?.copyWith( child: Text(
color: theme.colorScheme.onSurfaceVariant, description,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
height: 1.35,
),
), ),
), ),
), ),
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../../backend/backend.dart'; import '../../../../backend/backend.dart';
@@ -47,8 +48,44 @@ class _RecentSearchesState extends State<RecentSearches> {
); );
} }
// Deduplicate items by normalized query
final seen = <String>{};
final uniqueItems = <SearchHistory>[];
for (final item in widget.items) {
final key = item.query.trim().toLowerCase();
if (key.isEmpty) continue;
if (seen.add(key)) {
uniqueItems.add(item);
}
}
if (uniqueItems.isEmpty) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 24, horizontal: 16),
alignment: Alignment.center,
child: Column(
children: [
Icon(
Icons.history_toggle_off_rounded,
size: 40,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
),
const SizedBox(height: 10),
Text(
'История поиска пуста',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
);
}
final visibleItems = final visibleItems =
_expanded ? widget.items : widget.items.take(20).toList(); _expanded ? uniqueItems : uniqueItems.take(20).toList();
final screenW = MediaQuery.sizeOf(context).width;
final maxQueryWidth = (screenW - 200).clamp(180.0, 480.0);
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -59,38 +96,62 @@ class _RecentSearchesState extends State<RecentSearches> {
children: [ children: [
for (final item in visibleItems) for (final item in visibleItems)
Material( Material(
color: theme.colorScheme.surfaceContainer, color: Colors.transparent,
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
child: InkWell( child: InkWell(
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
onTap: () => widget.onTap(item.query), onTap: () {
HapticFeedback.selectionClick();
widget.onTap(item.query);
},
child: Container( child: Container(
padding: padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 6), const EdgeInsets.only(left: 10, right: 6, top: 6, bottom: 6),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Theme.of(context).brightness == Brightness.dark
? theme.colorScheme.surfaceContainerHighest
.withValues(alpha: 0.45)
: Colors.white.withValues(alpha: 0.65),
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
border: Border.all( border: Border.all(
color: theme.colorScheme.outlineVariant color: Theme.of(context).brightness == Brightness.dark
.withValues(alpha: 0.35), ? Colors.white.withValues(alpha: 0.12)
: theme.colorScheme.outlineVariant
.withValues(alpha: 0.35),
width: 1.0,
), ),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(
alpha: Theme.of(context).brightness == Brightness.dark
? 0.15
: 0.04),
blurRadius: 6,
offset: const Offset(0, 1.5),
),
],
), ),
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon( Icon(
Icons.history_rounded, Icons.history_rounded,
size: 14, size: 15,
color: theme.colorScheme.primary, color: theme.colorScheme.primary,
), ),
const SizedBox(width: 6), const SizedBox(width: 6),
ConstrainedBox( ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 140), constraints: BoxConstraints(maxWidth: maxQueryWidth),
child: Text( child: Tooltip(
item.query, message: item.query,
maxLines: 1, waitDuration: const Duration(milliseconds: 600),
overflow: TextOverflow.ellipsis, child: Text(
style: theme.textTheme.bodyMedium?.copyWith( item.query,
fontWeight: FontWeight.w500, maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
), ),
), ),
), ),
@@ -100,14 +161,14 @@ class _RecentSearchesState extends State<RecentSearches> {
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2), horizontal: 6, vertical: 2),
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.secondaryContainer, color: theme.colorScheme.primary.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
), ),
child: Text( child: Text(
'${item.resultCount}', '${item.resultCount}',
style: theme.textTheme.labelSmall?.copyWith( style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSecondaryContainer, color: theme.colorScheme.primary,
fontSize: 10, fontSize: 11,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
@@ -115,14 +176,24 @@ class _RecentSearchesState extends State<RecentSearches> {
], ],
if (widget.onDelete != null) ...[ if (widget.onDelete != null) ...[
const SizedBox(width: 4), const SizedBox(width: 4),
GestureDetector( Material(
onTap: () => widget.onDelete!(item.id), color: Colors.transparent,
child: Padding( shape: const CircleBorder(),
padding: const EdgeInsets.all(2), clipBehavior: Clip.antiAlias,
child: Icon( child: InkWell(
Icons.close_rounded, customBorder: const CircleBorder(),
size: 14, onTap: () {
color: theme.colorScheme.onSurfaceVariant, HapticFeedback.lightImpact();
widget.onDelete!(item.id);
},
child: Padding(
padding: const EdgeInsets.all(4),
child: Icon(
Icons.close_rounded,
size: 15,
color: theme.colorScheme.onSurfaceVariant
.withValues(alpha: 0.75),
),
), ),
), ),
), ),
@@ -134,7 +205,7 @@ class _RecentSearchesState extends State<RecentSearches> {
), ),
], ],
), ),
if (widget.items.length > 20) ...[ if (uniqueItems.length > 20) ...[
const SizedBox(height: 10), const SizedBox(height: 10),
Center( Center(
child: TextButton.icon( child: TextButton.icon(
@@ -148,7 +219,7 @@ class _RecentSearchesState extends State<RecentSearches> {
label: Text( label: Text(
_expanded _expanded
? 'Свернуть' ? 'Свернуть'
: 'Показать все (${widget.items.length})', : 'Показать все (${uniqueItems.length})',
), ),
), ),
), ),
@@ -23,6 +23,16 @@ class SettingsController extends AsyncNotifier<AppSettings> {
ref.invalidate(appSettingsProvider); ref.invalidate(appSettingsProvider);
} }
Future<void> setVideoPlayerVolume(double volume) async {
final current = state.value ?? AppSettings.defaults;
final clamped = volume.clamp(0.0, 100.0);
if ((current.videoPlayerVolume - clamped).abs() < 0.01) return;
final updated = current.copyWith(videoPlayerVolume: clamped);
state = AsyncData(updated);
await ref.read(settingsServiceProvider).setVideoPlayerVolume(clamped);
ref.invalidate(appSettingsProvider);
}
Future<void> clearCache() async { Future<void> clearCache() async {
await ref.read(cacheServiceProvider).clear(); await ref.read(cacheServiceProvider).clear();
} }
@@ -1,4 +1,5 @@
import 'dart:io'; import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart' hide appBuildNumber; import 'package:flutter/services.dart' hide appBuildNumber;
@@ -150,24 +151,33 @@ class _SettingsContentState extends ConsumerState<_SettingsContent> {
return Column( return Column(
children: [ children: [
// Pinned Top Category Quick Navigation // Pinned Top Category Quick Navigation (Frosted Glass)
Container( ClipRect(
padding: const EdgeInsets.symmetric(vertical: 8), child: BackdropFilter(
decoration: BoxDecoration( filter: ImageFilter.blur(sigmaX: 18, sigmaY: 18),
color: theme.scaffoldBackgroundColor, child: Container(
border: Border( padding: const EdgeInsets.symmetric(vertical: 8),
bottom: BorderSide( decoration: BoxDecoration(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.25), color: theme.scaffoldBackgroundColor.withValues(
alpha: theme.brightness == Brightness.dark ? 0.76 : 0.82,
),
border: Border(
bottom: BorderSide(
color: theme.brightness == Brightness.dark
? Colors.white.withValues(alpha: 0.08)
: Colors.black.withValues(alpha: 0.06),
),
),
), ),
), child: Align(
), alignment: Alignment.center,
child: Align( child: ConstrainedBox(
alignment: Alignment.center, constraints: const BoxConstraints(maxWidth: 860),
child: ConstrainedBox( child: _CategoryQuickNav(
constraints: const BoxConstraints(maxWidth: 860), categories: navCategories,
child: _CategoryQuickNav( onSelect: _scrollTo,
categories: navCategories, ),
onSelect: _scrollTo, ),
), ),
), ),
), ),
@@ -177,7 +187,12 @@ class _SettingsContentState extends ConsumerState<_SettingsContent> {
Expanded( Expanded(
child: SingleChildScrollView( child: SingleChildScrollView(
controller: _scrollController, controller: _scrollController,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), padding: EdgeInsets.fromLTRB(
16,
12,
16,
120 + MediaQuery.paddingOf(context).bottom,
),
child: Align( child: Align(
alignment: Alignment.topCenter, alignment: Alignment.topCenter,
child: ConstrainedBox( child: ConstrainedBox(
@@ -961,191 +976,275 @@ class _SettingsContentState extends ConsumerState<_SettingsContent> {
final isRu = settings.languageCode == 'ru'; final isRu = settings.languageCode == 'ru';
final theme = Theme.of(context); final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final selectedSource = await showModalBottomSheet<UpdateSource>( final selectedSource = await showModalBottomSheet<UpdateSource>(
context: context, context: context,
useRootNavigator: true,
isScrollControlled: true,
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
builder: (sheetContext) { builder: (sheetContext) {
return Container( return ClipRRect(
decoration: BoxDecoration( borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
color: theme.colorScheme.surface, child: BackdropFilter(
borderRadius: const BorderRadius.vertical(top: Radius.circular(28)), filter: ImageFilter.blur(sigmaX: 24, sigmaY: 24),
), child: Container(
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28), decoration: BoxDecoration(
child: Column( color: isDark
mainAxisSize: MainAxisSize.min, ? theme.colorScheme.surface.withValues(alpha: 0.88)
crossAxisAlignment: CrossAxisAlignment.stretch, : Colors.white.withValues(alpha: 0.94),
children: [ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
Center( border: Border(
child: Container( top: BorderSide(
width: 36, color: isDark
height: 4, ? Colors.white.withValues(alpha: 0.18)
margin: const EdgeInsets.only(bottom: 16), : Colors.white.withValues(alpha: 0.85),
decoration: BoxDecoration( width: 1.2,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(2),
), ),
), ),
), ),
Text( child: SafeArea(
isRu ? 'Источник обновлений' : 'Update Source', top: false,
style: theme.textTheme.titleMedium?.copyWith( child: Padding(
fontWeight: FontWeight.bold, padding: EdgeInsets.fromLTRB(
), 20,
textAlign: TextAlign.center, 14,
), 20,
const SizedBox(height: 6), 24 + MediaQuery.paddingOf(sheetContext).bottom,
Text( ),
isRu child: Column(
? 'Выберите сервер для загрузки обновлений' mainAxisSize: MainAxisSize.min,
: 'Choose a server to download updates from', crossAxisAlignment: CrossAxisAlignment.stretch,
style: theme.textTheme.bodySmall?.copyWith( children: [
color: theme.colorScheme.onSurfaceVariant, Center(
), child: Container(
textAlign: TextAlign.center, width: 38,
), height: 4.5,
const SizedBox(height: 20), margin: const EdgeInsets.only(bottom: 16),
// Option 1: GitHub (Recommended for speed)
Material(
color: theme.colorScheme.primaryContainer.withValues(alpha: 0.35),
borderRadius: BorderRadius.circular(16),
child: InkWell(
borderRadius: BorderRadius.circular(16),
onTap: () => Navigator.pop(sheetContext, UpdateSource.github),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.primary.withValues(alpha: 0.15), color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.35),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(3),
),
child: Icon(
Icons.bolt_rounded,
color: theme.colorScheme.primary,
size: 24,
), ),
), ),
const SizedBox(width: 14), ),
Expanded( Text(
child: Column( isRu ? 'Источник обновлений' : 'Update Source',
crossAxisAlignment: CrossAxisAlignment.start, style: theme.textTheme.titleMedium?.copyWith(
children: [ fontWeight: FontWeight.w800,
Row( letterSpacing: -0.3,
children: [
Text(
'GitHub',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
decoration: BoxDecoration(
color: Colors.green.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(6),
),
child: Text(
isRu ? 'Рекомендуется для скорости' : 'Recommended for speed',
style: const TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: Colors.green,
),
),
),
],
),
const SizedBox(height: 3),
Text(
isRu
? 'Прямая быстрая загрузка без ограничений'
: 'Direct fast download without limits',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
), ),
Icon( textAlign: TextAlign.center,
Icons.arrow_forward_ios_rounded, ),
size: 14, const SizedBox(height: 6),
Text(
isRu
? 'Выберите сервер для быстрой загрузки новой версии'
: 'Choose a server to download updates from',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant, color: theme.colorScheme.onSurfaceVariant,
), ),
], textAlign: TextAlign.center,
), ),
), const SizedBox(height: 20),
),
),
const SizedBox(height: 12),
// Option 2: Gitea (Muted / neutral grey) // Option 1: GitHub (Recommended for speed)
Material( Material(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.25), color: isDark
borderRadius: BorderRadius.circular(16), ? theme.colorScheme.primaryContainer.withValues(alpha: 0.35)
child: InkWell( : theme.colorScheme.primary.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(18),
onTap: () => Navigator.pop(sheetContext, UpdateSource.gitea), child: InkWell(
child: Padding( borderRadius: BorderRadius.circular(18),
padding: const EdgeInsets.all(16), onTap: () {
child: Row( HapticFeedback.selectionClick();
children: [ Navigator.pop(sheetContext, UpdateSource.github);
Container( },
width: 44, child: Container(
height: 44, padding: const EdgeInsets.all(16),
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onSurface.withValues(alpha: 0.08), borderRadius: BorderRadius.circular(18),
borderRadius: BorderRadius.circular(12), border: Border.all(
), color: isDark
child: Icon( ? Colors.white.withValues(alpha: 0.15)
Icons.dns_rounded, : theme.colorScheme.primary.withValues(alpha: 0.35),
color: theme.colorScheme.onSurfaceVariant, width: 1.2,
size: 22, ),
), ),
), child: Row(
const SizedBox(width: 14), children: [
Expanded( Container(
child: Column( width: 44,
crossAxisAlignment: CrossAxisAlignment.start, height: 44,
children: [ decoration: BoxDecoration(
Text( gradient: const LinearGradient(
'Gitea', colors: [Color(0xFF6366F1), Color(0xFF4F46E5)],
style: theme.textTheme.titleSmall?.copyWith( begin: Alignment.topLeft,
fontWeight: FontWeight.w600, end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(13),
boxShadow: [
BoxShadow(
color: const Color(0xFF6366F1).withValues(alpha: 0.40),
blurRadius: 10,
offset: const Offset(0, 3),
),
],
),
child: const Center(
child: Icon(
Icons.bolt_rounded,
color: Colors.white,
size: 24,
),
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'GitHub',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 7,
vertical: 2.5,
),
decoration: BoxDecoration(
color: Colors.green.withValues(alpha: 0.20),
borderRadius: BorderRadius.circular(6),
),
child: Text(
isRu ? 'Рекомендуется' : 'Recommended',
style: const TextStyle(
fontSize: 10.5,
fontWeight: FontWeight.w700,
color: Colors.green,
),
),
),
],
),
const SizedBox(height: 3),
Text(
isRu
? 'Прямая быстрая загрузка релизов без задержек'
: 'Direct fast download without limits',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
Icon(
Icons.arrow_forward_ios_rounded,
size: 15,
color: theme.colorScheme.onSurfaceVariant, color: theme.colorScheme.onSurfaceVariant,
), ),
), ],
const SizedBox(height: 3), ),
Text(
isRu
? 'Сервер релизов'
: 'Release server',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7),
),
),
],
), ),
), ),
Icon( ),
Icons.arrow_forward_ios_rounded, const SizedBox(height: 12),
size: 14,
color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5), // Option 2: Gitea
Material(
color: isDark
? theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.35)
: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.40),
borderRadius: BorderRadius.circular(18),
child: InkWell(
borderRadius: BorderRadius.circular(18),
onTap: () {
HapticFeedback.selectionClick();
Navigator.pop(sheetContext, UpdateSource.gitea);
},
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.12)
: theme.colorScheme.outlineVariant.withValues(alpha: 0.35),
width: 1.2,
),
),
child: Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF0EA5E9), Color(0xFF0284C7)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(13),
boxShadow: [
BoxShadow(
color: const Color(0xFF0EA5E9).withValues(alpha: 0.35),
blurRadius: 10,
offset: const Offset(0, 3),
),
],
),
child: const Center(
child: Icon(
Icons.dns_rounded,
color: Colors.white,
size: 22,
),
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Gitea (Synapse)',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 3),
Text(
isRu
? 'Альтернативный независимый сервер релизов'
: 'Alternative independent release mirror',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
Icon(
Icons.arrow_forward_ios_rounded,
size: 15,
color: theme.colorScheme.onSurfaceVariant,
),
],
),
),
), ),
], ),
), ],
), ),
), ),
), ),
], ),
), ),
); );
}, },
@@ -1297,6 +1396,49 @@ class _SettingsContentState extends ConsumerState<_SettingsContent> {
// Settings 2.0 Modern Components // Settings 2.0 Modern Components
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
class _SettingsIconBadge extends StatelessWidget {
const _SettingsIconBadge({
required this.icon,
required this.color,
this.size = 34,
this.iconSize = 18,
});
final IconData icon;
final Color color;
final double size;
final double iconSize;
@override
Widget build(BuildContext context) {
return Container(
width: size,
height: size,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
color,
color.withValues(alpha: 0.86),
],
),
borderRadius: BorderRadius.circular(size * 0.28),
boxShadow: [
BoxShadow(
color: color.withValues(alpha: 0.35),
blurRadius: 7,
offset: const Offset(0, 2.5),
),
],
),
child: Center(
child: Icon(icon, size: iconSize, color: Colors.white),
),
);
}
}
class _CategoryQuickNav extends StatelessWidget { class _CategoryQuickNav extends StatelessWidget {
const _CategoryQuickNav({ const _CategoryQuickNav({
required this.categories, required this.categories,
@@ -1310,8 +1452,10 @@ class _CategoryQuickNav extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
return SizedBox( return SizedBox(
height: 40, height: 44,
child: ListView.separated( child: ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: 16), padding: const EdgeInsets.symmetric(horizontal: 16),
scrollDirection: Axis.horizontal, scrollDirection: Axis.horizontal,
@@ -1319,32 +1463,84 @@ class _CategoryQuickNav extends StatelessWidget {
separatorBuilder: (_, __) => const SizedBox(width: 8), separatorBuilder: (_, __) => const SizedBox(width: 8),
itemBuilder: (context, index) { itemBuilder: (context, index) {
final cat = categories[index]; final cat = categories[index];
return Material( return Container(
color: theme.colorScheme.surfaceContainer, decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(22),
child: InkWell( boxShadow: [
borderRadius: BorderRadius.circular(20), BoxShadow(
onTap: () => onSelect(cat.key), color: isDark
child: Container( ? Colors.black.withValues(alpha: 0.25)
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), : cat.color.withValues(alpha: 0.12),
decoration: BoxDecoration( blurRadius: 8,
borderRadius: BorderRadius.circular(20), offset: const Offset(0, 2.5),
border: Border.all(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.35),
),
), ),
child: Row( ],
mainAxisSize: MainAxisSize.min, ),
children: [ child: ClipRRect(
Icon(cat.icon, size: 16, color: cat.color), borderRadius: BorderRadius.circular(22),
const SizedBox(width: 8), child: BackdropFilter(
Text( filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16),
cat.label, child: Material(
style: theme.textTheme.labelLarge?.copyWith( color: isDark
fontWeight: FontWeight.w600, ? theme.colorScheme.surfaceContainerHigh.withValues(alpha: 0.60)
: Colors.white.withValues(alpha: 0.82),
child: InkWell(
borderRadius: BorderRadius.circular(22),
onTap: () {
HapticFeedback.selectionClick();
onSelect(cat.key);
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(22),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.18)
: Colors.white.withValues(alpha: 0.85),
width: 1.1,
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 24,
height: 24,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
cat.color,
cat.color.withValues(alpha: 0.82),
],
),
borderRadius: BorderRadius.circular(7),
boxShadow: [
BoxShadow(
color: cat.color.withValues(alpha: 0.35),
blurRadius: 5,
offset: const Offset(0, 1.5),
),
],
),
child: Center(
child: Icon(cat.icon, size: 14, color: Colors.white),
),
),
const SizedBox(width: 8),
Text(
cat.label,
style: theme.textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.w600,
letterSpacing: -0.2,
),
),
],
), ),
), ),
], ),
), ),
), ),
), ),
@@ -1373,50 +1569,95 @@ class _SettingsCardGroup extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
return Container( return Container(
key: sectionKey, key: sectionKey,
margin: const EdgeInsets.only(bottom: 16), margin: const EdgeInsets.only(bottom: 18),
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerLow, borderRadius: BorderRadius.circular(24),
borderRadius: BorderRadius.circular(20), boxShadow: [
border: Border.all( BoxShadow(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.3), color: isDark
), ? Colors.black.withValues(alpha: 0.40)
: accentColor.withValues(alpha: 0.08),
blurRadius: 20,
offset: const Offset(0, 6),
spreadRadius: -2,
),
BoxShadow(
color: accentColor.withValues(alpha: isDark ? 0.08 : 0.04),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
), ),
clipBehavior: Clip.antiAlias, child: ClipRRect(
child: Column( borderRadius: BorderRadius.circular(24),
crossAxisAlignment: CrossAxisAlignment.stretch, child: BackdropFilter(
children: [ filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
// Header child: Container(
Padding( decoration: BoxDecoration(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 10), borderRadius: BorderRadius.circular(24),
child: Row( gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: isDark
? [
theme.colorScheme.surfaceContainerHigh.withValues(alpha: 0.60),
theme.colorScheme.surfaceContainerLow.withValues(alpha: 0.40),
]
: [
Colors.white.withValues(alpha: 0.88),
Colors.white.withValues(alpha: 0.72),
],
),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.15)
: Colors.white.withValues(alpha: 0.85),
width: 1.2,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
// iOS Liquid Glass Card Header
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
child: Row(
children: [
_SettingsIconBadge(
icon: icon,
color: accentColor,
size: 34,
iconSize: 19,
),
const SizedBox(width: 14),
Expanded(
child: Text(
title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
letterSpacing: -0.3,
),
),
),
],
),
),
Container( Container(
width: 32, height: 1,
height: 32, margin: const EdgeInsets.symmetric(horizontal: 16),
decoration: BoxDecoration( color: isDark
color: accentColor.withValues(alpha: 0.14), ? Colors.white.withValues(alpha: 0.08)
borderRadius: BorderRadius.circular(10), : theme.colorScheme.outlineVariant.withValues(alpha: 0.25),
),
child: Icon(icon, size: 18, color: accentColor),
),
const SizedBox(width: 12),
Expanded(
child: Text(
title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
),
), ),
...children,
], ],
), ),
), ),
const Divider(height: 1, thickness: 1, indent: 0, endIndent: 0), ),
...children,
],
), ),
); );
} }
@@ -1427,12 +1668,15 @@ class _SettingsDivider extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return Divider( return Divider(
height: 1, height: 1,
thickness: 0.7, thickness: 0.7,
indent: 68, indent: 64,
endIndent: 16, endIndent: 16,
color: Theme.of(context).colorScheme.outlineVariant.withValues(alpha: 0.25), color: isDark
? Colors.white.withValues(alpha: 0.07)
: Theme.of(context).colorScheme.outlineVariant.withValues(alpha: 0.25),
); );
} }
} }
@@ -1463,14 +1707,11 @@ class _SettingsTile extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row( child: Row(
children: [ children: [
Container( _SettingsIconBadge(
width: 38, icon: icon,
height: 38, color: iconColor,
decoration: BoxDecoration( size: 34,
color: iconColor.withValues(alpha: 0.12), iconSize: 18,
borderRadius: BorderRadius.circular(12),
),
child: Icon(icon, size: 20, color: iconColor),
), ),
const SizedBox(width: 14), const SizedBox(width: 14),
Expanded( Expanded(
@@ -1536,14 +1777,11 @@ class _SettingsSegmentedTile<T> extends StatelessWidget {
children: [ children: [
Row( Row(
children: [ children: [
Container( _SettingsIconBadge(
width: 38, icon: icon,
height: 38, color: iconColor,
decoration: BoxDecoration( size: 34,
color: iconColor.withValues(alpha: 0.12), iconSize: 18,
borderRadius: BorderRadius.circular(12),
),
child: Icon(icon, size: 20, color: iconColor),
), ),
const SizedBox(width: 14), const SizedBox(width: 14),
Expanded( Expanded(
@@ -1653,14 +1891,11 @@ class _SettingsStepperTile extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Row( child: Row(
children: [ children: [
Container( _SettingsIconBadge(
width: 38, icon: icon,
height: 38, color: iconColor,
decoration: BoxDecoration( size: 34,
color: iconColor.withValues(alpha: 0.12), iconSize: 18,
borderRadius: BorderRadius.circular(12),
),
child: Icon(icon, size: 20, color: iconColor),
), ),
const SizedBox(width: 14), const SizedBox(width: 14),
Expanded( Expanded(
@@ -1753,18 +1988,11 @@ class _SettingsFolderStructureTile extends StatelessWidget {
children: [ children: [
Row( Row(
children: [ children: [
Container( const _SettingsIconBadge(
width: 38, icon: Icons.folder_copy_rounded,
height: 38, color: Color(0xFF0EA5E9),
decoration: BoxDecoration( size: 34,
color: const Color(0xFF0EA5E9).withValues(alpha: 0.12), iconSize: 18,
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.folder_copy_rounded,
size: 20,
color: Color(0xFF0EA5E9),
),
), ),
const SizedBox(width: 14), const SizedBox(width: 14),
Expanded( Expanded(
@@ -2408,35 +2636,64 @@ class _HeroBrandBanner extends StatelessWidget {
Text( Text(
isRu ? 'Резервное копирование и экспорт' : 'Backup & JSON Export', isRu ? 'Резервное копирование и экспорт' : 'Backup & JSON Export',
style: theme.textTheme.titleSmall?.copyWith( style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w700,
color: theme.colorScheme.onSurfaceVariant, letterSpacing: -0.2,
), ),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
Wrap( Column(
spacing: 10, crossAxisAlignment: CrossAxisAlignment.stretch,
runSpacing: 10,
alignment: WrapAlignment.center,
children: [ children: [
OutlinedButton.icon( Row(
onPressed: onExportBackup, children: [
icon: const Icon(Icons.file_upload_rounded, size: 18), Expanded(
label: Text(isRu ? 'Экспорт бэкапа' : 'Export backup'), child: OutlinedButton.icon(
onPressed: onExportBackup,
icon: const Icon(Icons.file_upload_rounded, size: 18),
label: Text(
isRu ? 'Экспорт бэкапа' : 'Export backup',
overflow: TextOverflow.ellipsis,
),
),
),
const SizedBox(width: 10),
Expanded(
child: OutlinedButton.icon(
onPressed: onImportBackup,
icon: const Icon(Icons.file_download_rounded, size: 18),
label: Text(
isRu ? 'Импорт бэкапа' : 'Import backup',
overflow: TextOverflow.ellipsis,
),
),
),
],
), ),
OutlinedButton.icon( const SizedBox(height: 10),
onPressed: onImportBackup, Row(
icon: const Icon(Icons.file_download_rounded, size: 18), children: [
label: Text(isRu ? 'Импорт бэкапа' : 'Import backup'), Expanded(
), child: FilledButton.tonalIcon(
OutlinedButton.icon( onPressed: onExportJson,
onPressed: onExportJson, icon: const Icon(Icons.data_object_rounded, size: 18),
icon: const Icon(Icons.upload_file_rounded, size: 18), label: Text(
label: const Text('JSON Export'), isRu ? 'JSON Экспорт' : 'JSON Export',
), overflow: TextOverflow.ellipsis,
OutlinedButton.icon( ),
onPressed: onImportJson, ),
icon: const Icon(Icons.download_for_offline_rounded, size: 18), ),
label: const Text('JSON Import'), const SizedBox(width: 10),
Expanded(
child: FilledButton.tonalIcon(
onPressed: onImportJson,
icon: const Icon(Icons.download_for_offline_rounded, size: 18),
label: Text(
isRu ? 'JSON Импорт' : 'JSON Import',
overflow: TextOverflow.ellipsis,
),
),
),
],
), ),
], ],
), ),
@@ -1,5 +1,8 @@
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
@@ -156,28 +159,56 @@ class _ViewedScreenState extends ConsumerState<ViewedScreen> {
); );
} }
final bottomInset = MediaQuery.paddingOf(context).bottom;
return RefreshIndicator( return RefreshIndicator(
onRefresh: () => onRefresh: () =>
ref.read(viewedControllerProvider.notifier).refresh(), ref.read(viewedControllerProvider.notifier).refresh(),
child: ListView( child: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), padding: EdgeInsets.fromLTRB(16, 8, 16, 140 + bottomInset),
children: [ children: [
for (final group in groups) ...[ for (final group in groups) ...[
Padding( Padding(
padding: const EdgeInsets.fromLTRB(4, 16, 4, 10), padding: const EdgeInsets.fromLTRB(2, 16, 2, 10),
child: Row( child: Row(
children: [ children: [
Icon( Container(
Icons.calendar_today_rounded, width: 28,
size: 16, height: 28,
color: Theme.of(context).colorScheme.primary, decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Theme.of(context).colorScheme.primary,
Theme.of(context).colorScheme.primary.withValues(alpha: 0.82),
],
),
borderRadius: BorderRadius.circular(9),
boxShadow: [
BoxShadow(
color: Theme.of(context)
.colorScheme
.primary
.withValues(alpha: 0.32),
blurRadius: 6,
offset: const Offset(0, 2),
),
],
),
child: const Center(
child: Icon(
Icons.calendar_today_rounded,
size: 14,
color: Colors.white,
),
),
), ),
const SizedBox(width: 8), const SizedBox(width: 10),
Text( Text(
_localizedGroupLabel(group.label, isRu), _localizedGroupLabel(group.label, isRu),
style: style:
Theme.of(context).textTheme.titleSmall?.copyWith( Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
letterSpacing: -0.2,
), ),
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
@@ -187,10 +218,24 @@ class _ViewedScreenState extends ConsumerState<ViewedScreen> {
vertical: 2, vertical: 2,
), ),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Theme.of(context) color: Theme.of(context).brightness == Brightness.dark
.colorScheme ? Theme.of(context)
.surfaceContainerHighest, .colorScheme
.surfaceContainerHighest
.withValues(alpha: 0.5)
: Theme.of(context)
.colorScheme
.primary
.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
border: Border.all(
color: Theme.of(context).brightness == Brightness.dark
? Colors.white.withValues(alpha: 0.08)
: Theme.of(context)
.colorScheme
.primary
.withValues(alpha: 0.20),
),
), ),
child: Text( child: Text(
'${group.items.length}', '${group.items.length}',
@@ -198,7 +243,10 @@ class _ViewedScreenState extends ConsumerState<ViewedScreen> {
.textTheme .textTheme
.labelSmall .labelSmall
?.copyWith( ?.copyWith(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w700,
color: Theme.of(context).brightness == Brightness.dark
? Theme.of(context).colorScheme.onSurfaceVariant
: Theme.of(context).colorScheme.primary,
), ),
), ),
), ),
@@ -299,184 +347,251 @@ class _ViewedPostTile extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
final isDark = Theme.of(context).brightness == Brightness.dark;
final image = MediaUrlSelector.preview(post).firstOrNull; final image = MediaUrlSelector.preview(post).firstOrNull;
final timeStr = final timeStr =
'${viewedAt.hour.toString().padLeft(2, '0')}:${viewedAt.minute.toString().padLeft(2, '0')}'; '${viewedAt.hour.toString().padLeft(2, '0')}:${viewedAt.minute.toString().padLeft(2, '0')}';
return Card( return Container(
elevation: 0, margin: const EdgeInsets.only(bottom: 10),
color: scheme.surfaceContainerLow, decoration: BoxDecoration(
margin: const EdgeInsets.only(bottom: 8), borderRadius: BorderRadius.circular(20),
shape: RoundedRectangleBorder( boxShadow: [
borderRadius: BorderRadius.circular(16), BoxShadow(
side: BorderSide( color: Colors.black.withValues(alpha: isDark ? 0.28 : 0.05),
color: scheme.outlineVariant.withValues(alpha: 0.3), blurRadius: 14,
), offset: const Offset(0, 4),
spreadRadius: -2,
),
],
), ),
clipBehavior: Clip.antiAlias, child: ClipRRect(
child: InkWell( borderRadius: BorderRadius.circular(20),
onTap: onOpen, child: BackdropFilter(
child: Padding( filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16),
padding: const EdgeInsets.all(10), child: Material(
child: Row( color: Colors.transparent,
children: [ child: InkWell(
// Squircle Thumbnail borderRadius: BorderRadius.circular(20),
ClipRRect( onTap: () {
borderRadius: BorderRadius.circular(12), HapticFeedback.selectionClick();
child: SizedBox( onOpen();
width: 68, },
height: 68, child: Container(
child: Stack( padding: const EdgeInsets.all(10),
fit: StackFit.expand, decoration: BoxDecoration(
children: [ borderRadius: BorderRadius.circular(20),
image == null gradient: LinearGradient(
? Container( begin: Alignment.topLeft,
color: scheme.surfaceContainerHighest, end: Alignment.bottomRight,
child: const Icon(Icons.image_not_supported_rounded), colors: isDark
) ? [
: CachedNetworkImage( scheme.surfaceContainerHigh
imageUrl: image, .withValues(alpha: 0.58),
fit: BoxFit.cover, scheme.surfaceContainerLow
placeholder: (_, __) => Container( .withValues(alpha: 0.36),
color: scheme.surfaceContainerHighest, ]
), : [
errorWidget: (_, __, ___) => Container( Colors.white.withValues(alpha: 0.88),
color: scheme.surfaceContainerHighest, Colors.white.withValues(alpha: 0.72),
child: const Icon( ],
Icons.broken_image_rounded, ),
size: 20, border: Border.all(
), color: isDark
), ? Colors.white.withValues(alpha: 0.13)
), : Colors.white.withValues(alpha: 0.85),
if (_isVideo) width: 1.1,
Positioned(
right: 4,
bottom: 4,
child: Container(
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.65),
borderRadius: BorderRadius.circular(4),
),
child: const Icon(
Icons.play_arrow_rounded,
size: 14,
color: Colors.white,
),
),
),
],
), ),
), ),
), child: Row(
const SizedBox(width: 12),
// Post details
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Row( // Squircle Thumbnail
children: [ ClipRRect(
Flexible( borderRadius: BorderRadius.circular(13),
child: Container( child: Container(
padding: const EdgeInsets.symmetric( width: 68,
horizontal: 6, height: 68,
vertical: 2, decoration: BoxDecoration(
), border: Border.all(
decoration: BoxDecoration( color: isDark
color: ? Colors.white.withValues(alpha: 0.10)
scheme.primaryContainer.withValues(alpha: 0.5), : scheme.outlineVariant.withValues(alpha: 0.30),
borderRadius: BorderRadius.circular(6), ),
), borderRadius: BorderRadius.circular(13),
child: Text( ),
post.providerName, child: Stack(
maxLines: 1, fit: StackFit.expand,
overflow: TextOverflow.ellipsis, children: [
style: Theme.of(context) image == null
.textTheme ? Container(
.labelSmall color: scheme.surfaceContainerHighest,
?.copyWith( child: const Icon(
fontWeight: FontWeight.w600, Icons.image_not_supported_rounded),
color: scheme.onPrimaryContainer, )
: CachedNetworkImage(
imageUrl: image,
fit: BoxFit.cover,
placeholder: (_, __) => Container(
color: scheme.surfaceContainerHighest,
),
errorWidget: (_, __, ___) => Container(
color: scheme.surfaceContainerHighest,
child: const Icon(
Icons.broken_image_rounded,
size: 20,
),
),
), ),
), if (_isVideo)
), Positioned(
), right: 4,
const SizedBox(width: 6), bottom: 4,
Text( child: Container(
timeStr, padding: const EdgeInsets.all(3),
style: Theme.of(context) decoration: BoxDecoration(
.textTheme color: Colors.black.withValues(alpha: 0.65),
.labelSmall borderRadius: BorderRadius.circular(5),
?.copyWith( ),
color: scheme.onSurfaceVariant, child: const Icon(
Icons.play_arrow_rounded,
size: 14,
color: Colors.white,
),
),
), ),
],
), ),
], ),
), ),
const SizedBox(height: 4), const SizedBox(width: 12),
Text( // Post details
post.tags.isEmpty ? '#${post.id}' : post.tags.take(4).join(' '), Expanded(
maxLines: 1, child: Column(
overflow: TextOverflow.ellipsis, crossAxisAlignment: CrossAxisAlignment.start,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w500,
),
),
if (post.score != 0) ...[
const SizedBox(height: 2),
Row(
children: [ children: [
Icon( Row(
Icons.thumb_up_rounded, children: [
size: 12, Flexible(
color: scheme.outline, child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 7,
vertical: 2,
),
decoration: BoxDecoration(
color: scheme.primary
.withValues(alpha: isDark ? 0.20 : 0.12),
borderRadius: BorderRadius.circular(6),
border: Border.all(
color: scheme.primary.withValues(
alpha: isDark ? 0.30 : 0.20),
),
),
child: Text(
post.providerName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.labelSmall
?.copyWith(
fontWeight: FontWeight.w700,
color: scheme.primary,
),
),
),
),
const SizedBox(width: 6),
Text(
timeStr,
style: Theme.of(context)
.textTheme
.labelSmall
?.copyWith(
color: scheme.onSurfaceVariant,
fontWeight: FontWeight.w500,
),
),
],
), ),
const SizedBox(width: 4), const SizedBox(height: 4),
Text( Text(
'${post.score}', post.tags.isEmpty ? '#${post.id}' : post.tags.take(4).join(' '),
style: Theme.of(context) maxLines: 1,
.textTheme overflow: TextOverflow.ellipsis,
.labelSmall style: Theme.of(context).textTheme.bodyMedium?.copyWith(
?.copyWith( fontWeight: FontWeight.w600,
color: scheme.outline, letterSpacing: -0.1,
), ),
), ),
if (post.score != 0) ...[
const SizedBox(height: 2),
Row(
children: [
Icon(
Icons.thumb_up_rounded,
size: 12,
color: scheme.outline,
),
const SizedBox(width: 4),
Text(
'${post.score}',
style: Theme.of(context)
.textTheme
.labelSmall
?.copyWith(
color: scheme.outline,
fontWeight: FontWeight.w600,
),
),
],
),
],
], ],
), ),
], ),
// Action buttons
IconButton(
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 36, minHeight: 36),
tooltip: isFavorite
? (isRu ? 'В избранном' : 'In favorites')
: (isRu ? 'В избранное' : 'Add to favorites'),
onPressed: () {
HapticFeedback.selectionClick();
onFavorite();
},
icon: Icon(
isFavorite
? Icons.favorite_rounded
: Icons.favorite_border_rounded,
color: isFavorite
? Colors.redAccent
: scheme.onSurfaceVariant,
),
),
IconButton(
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(minWidth: 36, minHeight: 36),
tooltip:
isRu ? 'Удалить из истории' : 'Delete from history',
onPressed: () {
HapticFeedback.lightImpact();
onDelete();
},
icon: Icon(
Icons.close_rounded,
size: 20,
color: scheme.onSurfaceVariant.withValues(alpha: 0.6),
),
),
], ],
), ),
), ),
// Action buttons ),
IconButton(
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
tooltip: isFavorite
? (isRu ? 'В избранном' : 'In favorites')
: (isRu ? 'В избранное' : 'Add to favorites'),
onPressed: onFavorite,
icon: Icon(
isFavorite
? Icons.favorite_rounded
: Icons.favorite_border_rounded,
color: isFavorite ? Colors.redAccent : scheme.onSurfaceVariant,
),
),
IconButton(
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
tooltip: isRu ? 'Удалить из истории' : 'Delete from history',
onPressed: onDelete,
icon: Icon(
Icons.close_rounded,
size: 20,
color: scheme.onSurfaceVariant.withValues(alpha: 0.6),
),
),
],
), ),
), ),
), ),
+6 -4
View File
@@ -167,8 +167,10 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
void _scrollToEnd() { void _scrollToEnd() {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (_tagScrollController.hasClients) { if (_tagScrollController.hasClients) {
final max = _tagScrollController.position.maxScrollExtent;
final target = (max - 40).clamp(0.0, max);
_tagScrollController.animateTo( _tagScrollController.animateTo(
_tagScrollController.position.maxScrollExtent, target,
duration: const Duration(milliseconds: 200), duration: const Duration(milliseconds: 200),
curve: Curves.easeOut, curve: Curves.easeOut,
); );
@@ -286,8 +288,8 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
const SizedBox(width: 6), const SizedBox(width: 6),
], ],
ConstrainedBox( ConstrainedBox(
constraints: const BoxConstraints( constraints: BoxConstraints(
minWidth: 120, minWidth: _tags.isEmpty ? 120 : 64,
maxWidth: 300, maxWidth: 300,
), ),
child: Focus( child: Focus(
@@ -567,7 +569,7 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
final draft = _controller.text.trim().toLowerCase(); final draft = _controller.text.trim().toLowerCase();
if (draft.isEmpty) return ''; if (draft.isEmpty) return '';
final raw = draft.split(RegExp(r'\s+')).last; final raw = draft.split(RegExp(r'\s+')).last;
return raw.replaceAll(RegExp(r'^[\(\)]+|[\(\)]+$'), '').trim(); return raw.trim();
} }
bool get _isEditing => _focusNode.hasFocus || _localDirty; bool get _isEditing => _focusNode.hasFocus || _localDirty;
+514 -79
View File
@@ -1,3 +1,4 @@
import 'dart:ui';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -9,7 +10,7 @@ import '../../app/responsive.dart';
import '../../backend/backend.dart'; import '../../backend/backend.dart';
import '../../core/utils/result.dart'; import '../../core/utils/result.dart';
class AppShell extends ConsumerWidget { class AppShell extends ConsumerStatefulWidget {
const AppShell({required this.child, super.key}); const AppShell({required this.child, super.key});
final Widget child; final Widget child;
@@ -32,69 +33,6 @@ class AppShell extends ConsumerWidget {
_Destination('settings', 'Settings', Icons.settings_rounded, '/settings'), _Destination('settings', 'Settings', Icons.settings_rounded, '/settings'),
]; ];
@override
Widget build(BuildContext context, WidgetRef ref) {
final settings =
ref.watch(appSettingsProvider).value ?? AppSettings.defaults;
final artistConfigs =
ref.watch(_enabledArtistConfigsProvider).value ?? const [];
final destinations =
_visibleDestinations(settings, artistConfigs.isNotEmpty);
final ru = settings.languageCode == 'ru';
return Shortcuts(
shortcuts: {
LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyF):
const _NavigateIntent('/search'),
LogicalKeySet(LogicalKeyboardKey.escape): const _BackIntent(),
LogicalKeySet(LogicalKeyboardKey.digit1): const _NavigateIntent('/'),
LogicalKeySet(LogicalKeyboardKey.digit2):
const _NavigateIntent('/search'),
LogicalKeySet(LogicalKeyboardKey.digit3):
const _NavigateIntent('/favorites'),
LogicalKeySet(LogicalKeyboardKey.digit4):
const _NavigateIntent('/viewed'),
LogicalKeySet(LogicalKeyboardKey.digit5):
const _NavigateIntent('/collections'),
LogicalKeySet(LogicalKeyboardKey.digit6):
const _NavigateIntent('/artists'),
LogicalKeySet(LogicalKeyboardKey.digit7):
const _NavigateIntent('/providers'),
LogicalKeySet(LogicalKeyboardKey.digit8):
const _NavigateIntent('/settings'),
},
child: Actions(
actions: {
_NavigateIntent: CallbackAction<_NavigateIntent>(
onInvoke: (intent) {
context.go(intent.location);
return null;
},
),
_BackIntent: CallbackAction<_BackIntent>(
onInvoke: (_) {
if (Navigator.of(context).canPop()) Navigator.of(context).pop();
return null;
},
),
},
child: Focus(
autofocus: true,
child: Responsive.isDesktop(context)
? _DesktopShell(
destinations: destinations,
ru: ru,
child: child,
)
: _MobileShell(
destinations: destinations,
ru: ru,
child: child,
),
),
),
);
}
static List<_Destination> _visibleDestinations( static List<_Destination> _visibleDestinations(
AppSettings settings, AppSettings settings,
bool hasArtists, bool hasArtists,
@@ -105,6 +43,139 @@ class AppShell extends ConsumerWidget {
return true; return true;
}).toList(growable: false); }).toList(growable: false);
} }
@override
ConsumerState<AppShell> createState() => _AppShellState();
}
class _AppShellState extends ConsumerState<AppShell> {
final List<String> _tabHistory = [];
String? _currentPath;
bool _isBackNavigating = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final path = GoRouterState.of(context).uri.path;
if (_isBackNavigating) {
_isBackNavigating = false;
_currentPath = path;
return;
}
if (_currentPath != null && _currentPath != path) {
if (path == '/') {
_tabHistory.clear();
} else {
_tabHistory.remove(_currentPath);
_tabHistory.add(_currentPath!);
if (_tabHistory.length > 25) {
_tabHistory.removeAt(0);
}
}
}
_currentPath = path;
}
bool _handleBack() {
if (Navigator.of(context).canPop()) {
Navigator.of(context).pop();
return true;
}
final currentPath = GoRouterState.of(context).uri.path;
while (_tabHistory.isNotEmpty && _tabHistory.last == currentPath) {
_tabHistory.removeLast();
}
if (_tabHistory.isNotEmpty) {
final previous = _tabHistory.removeLast();
_isBackNavigating = true;
context.go(previous);
return true;
}
if (currentPath != '/') {
_isBackNavigating = true;
context.go('/');
return true;
}
return false;
}
@override
Widget build(BuildContext context) {
final settings =
ref.watch(appSettingsProvider).value ?? AppSettings.defaults;
final artistConfigs =
ref.watch(_enabledArtistConfigsProvider).value ?? const [];
final destinations =
AppShell._visibleDestinations(settings, artistConfigs.isNotEmpty);
final ru = settings.languageCode == 'ru';
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (didPop) return;
final handled = _handleBack();
if (!handled) {
SystemNavigator.pop();
}
},
child: Shortcuts(
shortcuts: {
LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyF):
const _NavigateIntent('/search'),
LogicalKeySet(LogicalKeyboardKey.escape): const _BackIntent(),
LogicalKeySet(LogicalKeyboardKey.digit1): const _NavigateIntent('/'),
LogicalKeySet(LogicalKeyboardKey.digit2):
const _NavigateIntent('/search'),
LogicalKeySet(LogicalKeyboardKey.digit3):
const _NavigateIntent('/favorites'),
LogicalKeySet(LogicalKeyboardKey.digit4):
const _NavigateIntent('/viewed'),
LogicalKeySet(LogicalKeyboardKey.digit5):
const _NavigateIntent('/collections'),
LogicalKeySet(LogicalKeyboardKey.digit6):
const _NavigateIntent('/artists'),
LogicalKeySet(LogicalKeyboardKey.digit7):
const _NavigateIntent('/providers'),
LogicalKeySet(LogicalKeyboardKey.digit8):
const _NavigateIntent('/settings'),
},
child: Actions(
actions: {
_NavigateIntent: CallbackAction<_NavigateIntent>(
onInvoke: (intent) {
context.go(intent.location);
return null;
},
),
_BackIntent: CallbackAction<_BackIntent>(
onInvoke: (_) {
_handleBack();
return null;
},
),
},
child: Focus(
autofocus: true,
child: Responsive.isDesktop(context)
? _DesktopShell(
destinations: destinations,
ru: ru,
child: widget.child,
)
: _MobileShell(
destinations: destinations,
ru: ru,
child: widget.child,
),
),
),
),
);
}
} }
class _DesktopShell extends StatefulWidget { class _DesktopShell extends StatefulWidget {
@@ -281,29 +352,393 @@ class _MobileShell extends StatelessWidget {
? location == '/' ? location == '/'
: location.startsWith(item.location), : location.startsWith(item.location),
); );
final bottomInset = 76.0 + MediaQuery.paddingOf(context).bottom;
return Scaffold( return Scaffold(
body: child, extendBody: true,
body: MediaQuery(
data: MediaQuery.of(context).copyWith(
padding: MediaQuery.of(context).padding.copyWith(
bottom: bottomInset,
),
),
child: child,
),
floatingActionButton: location == '/settings' floatingActionButton: location == '/settings'
? null ? null
: FloatingActionButton.small( : Padding(
heroTag: 'mobile-settings', padding: const EdgeInsets.only(bottom: 0, right: 2),
tooltip: ru child: _LiquidGlassSettingsButton(
? '\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438' ru: ru,
: 'Settings', onTap: () => context.go('/settings'),
onPressed: () => context.go('/settings'), ),
child: const Icon(Icons.settings_rounded),
), ),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat, floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
bottomNavigationBar: NavigationBar( bottomNavigationBar: _LiquidGlassBottomBar(
selectedIndex: selected < 0 ? 0 : selected, selectedIndex: selected < 0 ? 0 : selected,
onDestinationSelected: (index) => context.go(items[index].location), onDestinationSelected: (index) => context.go(items[index].location),
destinations: [ items: items,
for (final item in items) ru: ru,
NavigationDestination( ),
icon: Icon(item.icon), );
label: item.mobileLabelFor(ru), }
}
class _LiquidGlassBottomBar extends StatefulWidget {
const _LiquidGlassBottomBar({
required this.selectedIndex,
required this.onDestinationSelected,
required this.items,
required this.ru,
});
final int selectedIndex;
final ValueChanged<int> onDestinationSelected;
final List<_Destination> items;
final bool ru;
@override
State<_LiquidGlassBottomBar> createState() => _LiquidGlassBottomBarState();
}
class _LiquidGlassBottomBarState extends State<_LiquidGlassBottomBar> {
int? _pressedIndex;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final scheme = theme.colorScheme;
final count = widget.items.length;
if (count == 0) return const SizedBox.shrink();
return SafeArea(
top: false,
left: false,
right: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 0, 14, 10),
child: LayoutBuilder(
builder: (context, constraints) {
final barWidth = constraints.maxWidth;
final itemWidth = barWidth / count;
final pillWidth = (itemWidth - 6).clamp(36.0, 64.0);
final pillLeft =
widget.selectedIndex * itemWidth + (itemWidth - pillWidth) / 2;
return Container(
height: 64,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: isDark ? 0.38 : 0.09),
blurRadius: 22,
offset: const Offset(0, 8),
spreadRadius: -2,
),
if (isDark)
BoxShadow(
color: scheme.primary.withValues(alpha: 0.07),
blurRadius: 18,
offset: const Offset(0, 2),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(28),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: isDark
? [
scheme.surfaceContainerHigh
.withValues(alpha: 0.70),
scheme.surface.withValues(alpha: 0.82),
]
: [
Colors.white.withValues(alpha: 0.84),
Colors.white.withValues(alpha: 0.68),
],
),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.16)
: Colors.white.withValues(alpha: 0.75),
width: 1.2,
),
),
child: Stack(
alignment: Alignment.centerLeft,
children: [
// Animated sliding liquid pill indicator
AnimatedPositioned(
duration: const Duration(milliseconds: 300),
curve: Curves.easeOutBack,
left: pillLeft,
top: 7,
child: Container(
width: pillWidth,
height: 32,
decoration: BoxDecoration(
color: scheme.primaryContainer.withValues(
alpha: isDark ? 0.75 : 0.88,
),
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: scheme.primary.withValues(
alpha: isDark ? 0.35 : 0.22,
),
width: 1,
),
boxShadow: [
BoxShadow(
color: scheme.primary.withValues(
alpha: isDark ? 0.22 : 0.12,
),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
),
),
// Navigation item buttons
Row(
children: [
for (var i = 0; i < count; i++)
Expanded(
child: _LiquidNavItem(
destination: widget.items[i],
label: widget.items[i]
.mobileLabelFor(widget.ru),
isSelected: widget.selectedIndex == i,
isPressed: _pressedIndex == i,
onTapDown: () =>
setState(() => _pressedIndex = i),
onTapUp: () =>
setState(() => _pressedIndex = null),
onTapCancel: () =>
setState(() => _pressedIndex = null),
onTap: () {
HapticFeedback.lightImpact();
widget.onDestinationSelected(i);
},
),
),
],
),
],
),
),
),
),
);
},
),
),
);
}
}
class _LiquidNavItem extends StatelessWidget {
const _LiquidNavItem({
required this.destination,
required this.label,
required this.isSelected,
required this.isPressed,
required this.onTapDown,
required this.onTapUp,
required this.onTapCancel,
required this.onTap,
});
final _Destination destination;
final String label;
final bool isSelected;
final bool isPressed;
final VoidCallback onTapDown;
final VoidCallback onTapUp;
final VoidCallback onTapCancel;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final isDark = theme.brightness == Brightness.dark;
final targetScale = isPressed ? 0.86 : (isSelected ? 1.05 : 1.0);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (_) => onTapDown(),
onTapUp: (_) => onTapUp(),
onTapCancel: onTapCancel,
onTap: onTap,
child: Center(
child: AnimatedScale(
scale: targetScale,
duration: const Duration(milliseconds: 180),
curve: Curves.easeOutCubic,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 32,
child: Center(
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 200),
transitionBuilder: (child, anim) => ScaleTransition(
scale: anim,
child: child,
),
child: Icon(
destination.icon,
key: ValueKey('${destination.id}_$isSelected'),
size: isSelected ? 22 : 20,
color: isSelected
? scheme.onPrimaryContainer
: (isDark
? scheme.onSurfaceVariant
.withValues(alpha: 0.78)
: scheme.onSurfaceVariant
.withValues(alpha: 0.85)),
),
),
),
),
const SizedBox(height: 2),
AnimatedDefaultTextStyle(
duration: const Duration(milliseconds: 200),
style: TextStyle(
fontSize: 10.5,
fontWeight:
isSelected ? FontWeight.w700 : FontWeight.w500,
color: isSelected
? (isDark ? scheme.primary : scheme.onSurface)
: scheme.onSurfaceVariant.withValues(alpha: 0.75),
letterSpacing: -0.2,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
child: Text(label),
),
],
),
),
),
);
}
}
class _LiquidGlassSettingsButton extends StatefulWidget {
const _LiquidGlassSettingsButton({
required this.ru,
required this.onTap,
});
final bool ru;
final VoidCallback onTap;
@override
State<_LiquidGlassSettingsButton> createState() =>
_LiquidGlassSettingsButtonState();
}
class _LiquidGlassSettingsButtonState extends State<_LiquidGlassSettingsButton> {
bool _pressed = false;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final scheme = theme.colorScheme;
return Tooltip(
message: widget.ru ? 'Настройки' : 'Settings',
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (_) => setState(() => _pressed = true),
onTapUp: (_) => setState(() => _pressed = false),
onTapCancel: () => setState(() => _pressed = false),
onTap: () {
HapticFeedback.mediumImpact();
widget.onTap();
},
child: AnimatedScale(
scale: _pressed ? 0.88 : 1.0,
duration: const Duration(milliseconds: 160),
curve: Curves.easeOutCubic,
child: Container(
width: 48,
height: 48,
decoration: BoxDecoration(
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: isDark ? 0.38 : 0.12),
blurRadius: 18,
offset: const Offset(0, 6),
spreadRadius: -1,
),
BoxShadow(
color: scheme.primary.withValues(alpha: isDark ? 0.20 : 0.12),
blurRadius: 12,
offset: const Offset(0, 2),
),
],
), ),
], child: ClipOval(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
center: const Alignment(-0.3, -0.4),
radius: 1.1,
colors: isDark
? [
scheme.surfaceContainerHigh.withValues(alpha: 0.85),
scheme.surface.withValues(alpha: 0.75),
]
: [
Colors.white.withValues(alpha: 0.92),
Colors.white.withValues(alpha: 0.70),
],
),
border: Border.all(
color: isDark
? Colors.white.withValues(alpha: 0.24)
: Colors.white.withValues(alpha: 0.85),
width: 1.4,
),
),
child: Center(
child: AnimatedRotation(
turns: _pressed ? 0.125 : 0.0,
duration: const Duration(milliseconds: 250),
curve: Curves.easeOutBack,
child: Icon(
Icons.settings_rounded,
size: 23,
color: scheme.primary,
),
),
),
),
),
),
),
),
), ),
); );
} }
+2
View File
@@ -596,6 +596,8 @@ class _FeedVideoPreviewState extends State<_FeedVideoPreview> {
controller: _controller, controller: _controller,
fit: BoxFit.cover, fit: BoxFit.cover,
controls: null, controls: null,
pauseUponEnteringBackgroundMode: false,
resumeUponEnteringForegroundMode: false,
), ),
), ),
), ),
+10 -1
View File
@@ -28,6 +28,7 @@ class PostMasonryGrid extends StatelessWidget {
this.loading = false, this.loading = false,
this.controller, this.controller,
this.gridMode = 'masonry', this.gridMode = 'masonry',
this.padding,
super.key, super.key,
}); });
@@ -51,11 +52,19 @@ class PostMasonryGrid extends StatelessWidget {
final bool loading; final bool loading;
final ScrollController? controller; final ScrollController? controller;
final String gridMode; final String gridMode;
final EdgeInsetsGeometry? padding;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final mobile = Responsive.isMobile(context); final mobile = Responsive.isMobile(context);
final pad = EdgeInsets.all(mobile ? 8 : 16); final bottomInset = MediaQuery.paddingOf(context).bottom;
final pad = padding ??
EdgeInsets.fromLTRB(
mobile ? 8 : 16,
mobile ? 8 : 16,
mobile ? 8 : 16,
(mobile ? 8 : 16) + (mobile ? (120.0 + bottomInset) : 0.0),
);
final spacing = mobile ? 8.0 : 12.0; final spacing = mobile ? 8.0 : 12.0;
Widget buildCard(Post post) { Widget buildCard(Post post) {
+78 -9
View File
@@ -3,22 +3,91 @@ import 'package:flutter/material.dart';
import '../../backend/backend.dart'; import '../../backend/backend.dart';
class ProviderStatusBadge extends StatelessWidget { class ProviderStatusBadge extends StatelessWidget {
const ProviderStatusBadge({required this.health, super.key}); const ProviderStatusBadge({
required this.health,
this.compact = false,
super.key,
});
final ProviderHealth? health; final ProviderHealth? health;
final bool compact;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
final status = health?.status ?? ProviderStatus.unknown; final status = health?.status ?? ProviderStatus.unknown;
final color = switch (status) {
ProviderStatus.online => Colors.green, final (color, labelRu, labelEn) = switch (status) {
ProviderStatus.offline => Colors.red, ProviderStatus.online => (
ProviderStatus.unknown => Colors.grey, const Color(0xFF10B981), // Emerald
'Онлайн',
'Online',
),
ProviderStatus.offline => (
const Color(0xFFEF4444), // Crimson Red
'Офлайн',
'Offline',
),
ProviderStatus.unknown => (
const Color(0xFF94A3B8), // Slate
'Не проверен',
'Unknown',
),
}; };
return Chip(
avatar: Icon(Icons.circle, color: color, size: 10), final isRu = Localizations.maybeLocaleOf(context)?.languageCode == 'ru';
label: Text(status.name), final label = isRu ? labelRu : labelEn;
visualDensity: VisualDensity.compact,
return Container(
padding: EdgeInsets.symmetric(
horizontal: compact ? 8 : 10,
vertical: compact ? 3 : 5,
),
decoration: BoxDecoration(
color: color.withValues(alpha: isDark ? 0.16 : 0.10),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: color.withValues(alpha: isDark ? 0.45 : 0.32),
width: 1.1,
),
boxShadow: [
BoxShadow(
color: color.withValues(alpha: isDark ? 0.18 : 0.08),
blurRadius: 6,
offset: const Offset(0, 1.5),
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 7,
height: 7,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: color.withValues(alpha: 0.8),
blurRadius: 5,
spreadRadius: 0.5,
),
],
),
),
const SizedBox(width: 6),
Text(
label,
style: theme.textTheme.labelSmall?.copyWith(
color: color,
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
),
],
),
); );
} }
} }
+103 -11
View File
@@ -1,36 +1,128 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../backend/models/tag_suggestion.dart';
class TagChip extends StatelessWidget { class TagChip extends StatelessWidget {
const TagChip({ const TagChip({
required this.tag, required this.tag,
this.category,
this.group,
this.onTap, this.onTap,
this.onLongPress, this.onLongPress,
super.key, super.key,
}); });
final String tag; final String tag;
final TagCategory? category;
final String? group;
final VoidCallback? onTap; final VoidCallback? onTap;
final VoidCallback? onLongPress; final VoidCallback? onLongPress;
TagCategory get _resolvedCategory {
if (category != null) return category!;
final g = (group ?? '').toLowerCase();
return switch (g) {
'artist' => TagCategory.artist,
'character' => TagCategory.character,
'copyright' => TagCategory.copyright,
'species' => TagCategory.species,
'meta' => TagCategory.meta,
'general' => TagCategory.general,
_ => tagCategoryFromString(g),
};
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
final chip = ActionChip( final isDark = Theme.of(context).brightness == Brightness.dark;
onPressed: onTap, final cat = _resolvedCategory;
label: Text(tag),
labelStyle: TextStyle( final (Color baseColor, Color textColor) = _colorsForCategory(cat, scheme, isDark);
color: scheme.onSecondaryContainer,
fontWeight: FontWeight.w700, final chipWidget = Container(
decoration: BoxDecoration(
color: baseColor.withValues(alpha: isDark ? 0.16 : 0.10),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: baseColor.withValues(alpha: isDark ? 0.40 : 0.28),
width: 1.0,
),
),
child: Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(10),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 6,
height: 6,
margin: const EdgeInsets.only(right: 6),
decoration: BoxDecoration(
color: baseColor,
shape: BoxShape.circle,
),
),
Text(
tag,
style: TextStyle(
color: textColor,
fontWeight: FontWeight.w700,
fontSize: 13,
letterSpacing: -0.1,
),
),
],
),
),
),
), ),
backgroundColor: scheme.secondaryContainer.withValues(alpha: 0.62),
side: BorderSide(color: scheme.outlineVariant.withValues(alpha: 0.65)),
visualDensity: VisualDensity.compact,
); );
if (onLongPress == null) return chip;
if (onLongPress == null) return chipWidget;
return GestureDetector( return GestureDetector(
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
onLongPress: onLongPress, onLongPress: onLongPress,
child: chip, child: chipWidget,
); );
} }
static (Color, Color) _colorsForCategory(
TagCategory cat,
ColorScheme scheme,
bool isDark,
) {
return switch (cat) {
TagCategory.artist => (
const Color(0xFFFF4757), // e621 / Gelbooru red/coral
isDark ? const Color(0xFFFF6B81) : const Color(0xFFD63031),
),
TagCategory.character => (
const Color(0xFF2ED573), // Vibrant character green
isDark ? const Color(0xFF7BED9F) : const Color(0xFF10AC84),
),
TagCategory.copyright => (
const Color(0xFFA55EEA), // Classic anime series purple
isDark ? const Color(0xFFD980FA) : const Color(0xFF8854D0),
),
TagCategory.species => (
const Color(0xFFFFA502), // e621 species amber/orange
isDark ? const Color(0xFFFFC048) : const Color(0xFFE67E22),
),
TagCategory.meta => (
const Color(0xFF1E90FF), // Meta / format cyan / ice blue
isDark ? const Color(0xFF70A1FF) : const Color(0xFF0984E3),
),
TagCategory.general || TagCategory.unknown => (
isDark ? scheme.primary : scheme.primary,
isDark ? scheme.onSurface : scheme.onSurface,
),
};
}
} }
+1 -1
View File
@@ -1,7 +1,7 @@
name: gel_rule_app name: gel_rule_app
description: Local backend/core layer for a Flutter booru browser app. description: Local backend/core layer for a Flutter booru browser app.
publish_to: "none" publish_to: "none"
version: 3.0.5+56 version: 3.1.8+69
environment: environment:
sdk: ">=3.3.0 <4.0.0" sdk: ">=3.3.0 <4.0.0"
+155
View File
@@ -0,0 +1,155 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gel_rule_app/backend/backend.dart';
import 'package:gel_rule_app/features/providers/presentation/provider_check_screen.dart';
import 'package:gel_rule_app/features/providers/presentation/provider_form_screen.dart';
import 'package:gel_rule_app/features/providers/presentation/providers_controller.dart';
import 'package:gel_rule_app/features/providers/presentation/providers_screen.dart';
ContentProviderConfig _sampleConfig({
required String id,
required String name,
String apiType = 'gelbooru',
String baseUrl = 'https://gelbooru.com',
bool enabled = true,
int priority = 10,
}) {
return ContentProviderConfig(
id: id,
name: name,
baseUrl: baseUrl,
apiType: apiType,
enabled: enabled,
priority: priority,
timeoutSeconds: 20,
customHeaders: const {},
createdAt: DateTime(2025, 1, 1),
updatedAt: DateTime(2025, 1, 1),
);
}
class _FakeProvidersController extends ProvidersController {
_FakeProvidersController(this._items);
final List<ContentProviderConfig> _items;
@override
Future<List<ContentProviderConfig>> build() async => _items;
}
void main() {
setUp(() {
TestWidgetsFlutterBinding.ensureInitialized();
});
testWidgets('ProvidersScreen renders overview card, provider cards, and actions',
(tester) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1.0;
addTearDown(() {
tester.view.resetPhysicalSize();
tester.view.resetDevicePixelRatio();
});
final sampleProviders = [
_sampleConfig(id: 'gelbooru', name: 'Gelbooru', apiType: 'gelbooru'),
_sampleConfig(
id: 'rule34',
name: 'Rule34',
apiType: 'rule34',
baseUrl: 'https://api.rule34.xxx'),
];
await tester.pumpWidget(
ProviderScope(
overrides: [
providersControllerProvider.overrideWith(
() => _FakeProvidersController(sampleProviders),
),
],
child: const MaterialApp(
home: ProvidersScreen(),
),
),
);
await tester.pumpAndSettle();
expect(find.text('Gelbooru'), findsWidgets);
expect(find.text('Rule34'), findsWidgets);
expect(find.byType(Switch), findsNWidgets(2));
expect(find.byIcon(Icons.network_check_rounded), findsWidgets);
expect(find.byIcon(Icons.add_rounded), findsOneWidget);
});
testWidgets('ProviderFormScreen renders presets, sections, and input fields',
(tester) async {
tester.view.physicalSize = const Size(400, 1600);
tester.view.devicePixelRatio = 1.0;
addTearDown(() {
tester.view.resetPhysicalSize();
tester.view.resetDevicePixelRatio();
});
await tester.pumpWidget(
const ProviderScope(
child: MaterialApp(
home: ProviderFormScreen(),
),
),
);
await tester.pumpAndSettle();
// Check presets are visible
expect(find.text('Danbooru'), findsOneWidget);
expect(find.text('e621'), findsOneWidget);
expect(find.byIcon(Icons.check_rounded), findsOneWidget);
});
testWidgets('ProviderCheckScreen renders metrics and health tiles',
(tester) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1.0;
addTearDown(() {
tester.view.resetPhysicalSize();
tester.view.resetDevicePixelRatio();
});
final sampleProviders = [
_sampleConfig(id: 'gelbooru', name: 'Gelbooru', apiType: 'gelbooru'),
];
await tester.pumpWidget(
ProviderScope(
overrides: [
providersControllerProvider.overrideWith(
() => _FakeProvidersController(sampleProviders),
),
providerDiagnosticsProvider.overrideWith(
(ref) async => const {},
),
providerHealthProvider.overrideWith(
(ref) => {
'gelbooru': ProviderHealth(
providerId: 'gelbooru',
status: ProviderStatus.online,
pingMs: 85,
apiVersion: '0.2.5',
lastCheckedAt: DateTime(2026, 1, 1),
),
},
),
],
child: const MaterialApp(
home: ProviderCheckScreen(),
),
),
);
await tester.pumpAndSettle();
expect(find.text('Gelbooru'), findsOneWidget);
expect(find.text('85 ms'), findsOneWidget);
});
}