From 14830c0a4af6e809215a0fd5847a1c2a90baf35a Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 20 Nov 2026 11:58:25 +0400 Subject: [PATCH 01/24] feat(stories): the feed, the story of a link and the events of stories over API v3 carry sid, the device's A/B segment, the stream and testmode as the web SDK does, poll answers and reviews carry sid, stream, testmode and their source (source_type stories, the story and the slide as strings) instead of story_id and slide_id, and going back on the first slide sends view again --- lib/src/popups_v3/popups_v3.dart | 14 +- .../widgets/personalization_story_viewer.dart | 11 +- lib/src/ui/widgets/stories_api_v3.dart | 147 ++++++++++++++---- lib/src/ui/widgets/stories_polls_api.dart | 113 +++++++++----- test/ui/stories_poll_test.dart | 15 +- test/ui/stories_poll_widget_test.dart | 6 +- test/ui/stories_polls_api_test.dart | 142 +++++++++++++---- test/ui/stories_share_test.dart | 102 +++++++++--- test/ui/stories_share_widget_test.dart | 54 ++++++- 9 files changed, 467 insertions(+), 137 deletions(-) diff --git a/lib/src/popups_v3/popups_v3.dart b/lib/src/popups_v3/popups_v3.dart index c2a1ae4..ce25176 100644 --- a/lib/src/popups_v3/popups_v3.dart +++ b/lib/src/popups_v3/popups_v3.dart @@ -70,6 +70,11 @@ class PopupsV3 with WidgetsBindingObserver implements PopupsV3Listener { return popups; } + /// Тестовый режим попапов магазина [sdk] ([testMode]) без создания попапов: их ещё + /// нет — выключен. Его же берут запросы сторис и опросов API v3. + static bool testModeOf(PersonalizationSdk sdk) => + _byShop[_shopOf(sdk)]?.testMode ?? false; + static String _shopOf(PersonalizationSdk sdk) { final own = sdk.shopId; if (own != null && own.isNotEmpty) return own; @@ -125,7 +130,8 @@ class PopupsV3 with WidgetsBindingObserver implements PopupsV3Listener { if (active) unawaited(engine.refresh(force: true)); } - /// Тестовый режим: попапы со статусом «Тест», показы не пишутся в частоту. + /// Тестовый режим: попапы со статусом «Тест», показы не пишутся в частоту. Им же + /// лента, события и опросы сторис API v3 шлют `testmode=true`. bool get testMode => engine.testMode; set testMode(bool value) { @@ -304,6 +310,10 @@ class _SdkPlatform implements PopupsV3Platform { 'ces' => StoryPollType.ces, _ => StoryPollType.nps, }; - await StoriesPollsApi(_sdk, _popups.appHost).review(type, body); + await StoriesPollsApi( + _sdk, + _popups.appHost, + streamAndTestMode: false, + ).review(type, body); } } diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index b409901..e643bdb 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -32,8 +32,8 @@ import 'stories_v3_scope.dart'; /// - касание левой трети — назад, правой — вперёд, середина ничего не делает; в RTL края /// меняются местами. Удержание от 200 мс — пауза, отпускание её снимает и никуда не /// листает. Назад на первом слайде первой сторис перезапускает слайд — прогресс и видео -/// с нуля, без перезагрузки и повторного `view`; вперёд на последнем слайде последней — -/// закрывает просмотр; +/// с нуля, без перезагрузки; вперёд на последнем слайде последней — закрывает +/// просмотр; /// - свайп вбок листает сторис; заход на сторис (просмотр слайда, трекинг `view`) — только /// когда страница осела, подглядывание соседней не считается. Свайп вниз дальше 120 или /// быстрее 800 в секунду закрывает, иначе слайд пружинит назад; пока тянут — пауза; @@ -415,10 +415,15 @@ class _PersonalizationStoryViewerState extends State case StoriesStep.slide: _entered(); case StoriesStep.restart: - // Тот же заход: медиа не перезагружается, `view` не повторяется. + // Тот же заход: медиа не перезагружается. С API v3 слайд показан снова — `view` + // ещё раз, как в вебе (повторы за 2 с сервер склеивает сам); старый трекинг — + // без повтора. _progress.value = 0; if (_videoReady) _video?.seekTo(Duration.zero); _gif?.restart(); + if (_v3Code != null) { + _trackV3(StoriesV3Event.view, _playback.story, _playback.slide); + } case StoriesStep.turn: _sync(); final target = _playback.turnTarget!; diff --git a/lib/src/ui/widgets/stories_api_v3.dart b/lib/src/ui/widgets/stories_api_v3.dart index b5d4c5a..82a2f18 100644 --- a/lib/src/ui/widgets/stories_api_v3.dart +++ b/lib/src/ui/widgets/stories_api_v3.dart @@ -5,7 +5,10 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; +import '../../init/sdk_init_handler.dart'; import '../../personalization_sdk.dart'; +import '../../popups_v3/popups_v3.dart'; +import '../../popups_v3/popups_v3_hooks.dart'; import '../../stories/stories_response.dart'; import '../../tracking/tracking_models.dart'; import 'stories_seen_store.dart'; @@ -24,6 +27,16 @@ enum StoriesV3Event { final String wire; } +/// Кто спрашивает API v3 ([StoriesApiV3.identity]). +typedef StoriesV3Identity = ({ + String shopId, + String did, + String sid, + String segment, + String stream, + bool testMode, +}); + /// Ответ HTTP: код и тело. typedef StoriesV3Response = ({int status, String body}); @@ -56,8 +69,9 @@ class StoriesV3Exception implements Exception { /// - события — `POST /api/v3/storefront/stories/{code}/events`; /// - ответы опросов слайдов — [post] (`/api/v3/polls/...`, `StoriesPollsApi`). /// -/// Запросу нужны `shop_id` и `did`, `sid` не нужен. Без `did` сервер отвечает 400, а SDK -/// получает его при init: запрос ждёт его ([identity]). +/// Запросы несут `shop_id`, `did`, `sid`, `segment`, `stream` и `testmode`, как веб +/// ([identity]). Без `did` сервер отвечает 400, а SDK получает его при init: запрос ждёт +/// его. abstract final class StoriesApiV3 { /// Глобальный хост API v3 без схемы (`app.rees46.ru`) — для блоков без своего; /// `null` или пусто — старый API. @@ -102,8 +116,15 @@ abstract final class StoriesApiV3 { ]) { return Uri.parse('https://$host').replace( pathSegments: ['api', 'v3', ...segments], - // Пустой запрос — без «?» на конце. - queryParameters: query.isEmpty ? null : query, + // Пустой запрос — без «?» на конце. Пустое значение — `key=`, как в вебе (сам + // `Uri` пишет просто `key`). + query: query.isEmpty + ? null + : [ + for (final MapEntry(:key, :value) in query.entries) + '${Uri.encodeQueryComponent(key)}=' + '${Uri.encodeQueryComponent(value)}', + ].join('&'), ); } @@ -154,22 +175,65 @@ abstract final class StoriesApiV3 { return Map.from(json); } - /// `shop_id` и `did` магазина [sdk]. `did` спрашивается раз в [didPoll], пока SDK его - /// не получит; не дождались за [timeout] — [TimeoutException]. - static Future<({String shopId, String did})> identity( + /// Последний `did` каждого магазина, которым ходили запросы: ключ сохранённых ответов + /// опросов, когда копии моста ещё нет ([knownDid]). + static final Map _dids = {}; + + /// Кто спрашивает: магазин, устройство и сеанс, группа A/B устройства, поток и + /// тестовый режим. `did` берётся из копии моста, без неё спрашивается раз в + /// [didPoll], пока SDK его не получит; не дождались за [timeout] — + /// [TimeoutException]. `sid` — сеанс моста (нет — пустая строка), `segment` — + /// `segments.getAbGroup()` (до init пустой), `stream` — поток init (по умолчанию + /// `flutter`), тестовый режим — у попапов v3 (`sdk.popups.testMode`). + static Future identity( PersonalizationSdk sdk, { Duration timeout = didTimeout, }) async { final shop = StoriesSeenStore.shopOf(sdk); if (shop.isEmpty) throw StateError('stories API v3: unknown shop_id'); + final did = await _did(sdk, timeout); + _dids[shop] = did; + var segment = ''; + try { + segment = sdk.segments.getAbGroup(); + } catch (_) { + // Группы ещё нет — пустая строка, как без согласия в вебе. + } + return ( + shopId: shop, + did: did, + sid: await _sid(sdk), + segment: segment, + stream: streamOf(sdk), + testMode: PopupsV3.testModeOf(sdk), + ); + } + + /// `did` магазина [sdk] сейчас, без ожидания: копия моста, иначе последний, с которым + /// ходили запросы; не знаем — пустая строка. + static String knownDid(PersonalizationSdk sdk) { + final mirrored = sdk.deviceId ?? ''; + if (mirrored.isNotEmpty) return mirrored; + return _dids[StoriesSeenStore.shopOf(sdk)] ?? ''; + } + + /// Поток магазина [sdk] из init; не задан — `flutter`. + static String streamOf(PersonalizationSdk sdk) { + final stream = PopupsV3Hooks.configOf(sdk.tracking)?.stream?.trim() ?? ''; + return stream.isEmpty ? SdkInitHandler.defaultStream : stream; + } + + static Future _did(PersonalizationSdk sdk, Duration timeout) async { for (var waited = Duration.zero; ; waited += didPoll) { - String? did; - try { - did = await sdk.getDid(); - } catch (_) { - // Инстанс ещё не готов — спросим снова. + var did = sdk.deviceId; + if (did == null || did.isEmpty) { + try { + did = await sdk.getDid(); + } catch (_) { + // Инстанс ещё не готов — спросим снова. + } } - if (did != null && did.isNotEmpty) return (shopId: shop, did: did); + if (did != null && did.isNotEmpty) return did; if (waited >= timeout) { throw TimeoutException('stories API v3: no did', timeout); } @@ -177,6 +241,29 @@ abstract final class StoriesApiV3 { } } + static Future _sid(PersonalizationSdk sdk) async { + final mirrored = sdk.sessionId ?? ''; + if (mirrored.isNotEmpty) return mirrored; + try { + return await sdk.getSid(); + } catch (_) { + // Нет сеанса — пустой `sid`. + return ''; + } + } + + /// Параметры ленты и сторис по ссылке: `shop_id`, `did`, `sid`, `segment`, `stream` и + /// `testmode=true` только в тестовом режиме. + static Map identityQuery(StoriesV3Identity id) => + { + 'shop_id': id.shopId, + 'did': id.did, + 'sid': id.sid, + 'segment': id.segment, + 'stream': id.stream, + if (id.testMode) 'testmode': 'true', + }; + /// Лента блока [code] с хоста [host]. static Future feed( PersonalizationSdk sdk, @@ -186,11 +273,7 @@ abstract final class StoriesApiV3 { final id = await identity(sdk); final response = await send( 'GET', - uri( - host, - [code], - {'shop_id': id.shopId, 'did': id.did}, - ), + uri(host, [code], identityQuery(id)), null, ); return parseResponse(response); @@ -210,8 +293,7 @@ abstract final class StoriesApiV3 { host, [link.code, 'story', link.storyId], { - 'shop_id': id.shopId, - 'did': id.did, + ...identityQuery(id), if (link.slideId != null) 'slide_id': link.slideId!, }, ), @@ -243,13 +325,7 @@ abstract final class StoriesApiV3 { 'POST', uri(host, [code, 'events'], const {}), jsonEncode( - eventBody( - shopId: id.shopId, - did: id.did, - event: event, - storyId: storyId, - slideId: slideId, - ), + eventBody(id, event: event, storyId: storyId, slideId: slideId), ), ); if (response.status < 200 || response.status >= 300) { @@ -270,18 +346,23 @@ abstract final class StoriesApiV3 { } } - /// Тело события: id кампании — числом, как в ленте; id слайда — всегда строкой. - static Map eventBody({ - required String shopId, - required String did, + /// Тело события: кто спрашивает ([identityQuery], `testmode` — `true`), событие, id + /// кампании — числом, если он числовой, как в ленте; id слайда — всегда строкой + /// (`12_0` тоже). + static Map eventBody( + StoriesV3Identity id, { required StoriesV3Event event, required String storyId, required String slideId, }) { final number = int.tryParse(storyId); return { - 'shop_id': shopId, - 'did': did, + 'shop_id': id.shopId, + 'did': id.did, + 'sid': id.sid, + 'segment': id.segment, + 'stream': id.stream, + if (id.testMode) 'testmode': true, 'event': event.wire, 'story_id': number != null && '$number' == storyId ? number : storyId, 'slide_id': slideId, diff --git a/lib/src/ui/widgets/stories_polls_api.dart b/lib/src/ui/widgets/stories_polls_api.dart index f68b07d..915cfaa 100644 --- a/lib/src/ui/widgets/stories_polls_api.dart +++ b/lib/src/ui/widgets/stories_polls_api.dart @@ -22,58 +22,82 @@ class StoryPollReply { /// По умолчанию — [StoriesPollsApi] (HTTP API v3). Тесты и офлайн-демо подменяют его у /// `PersonalizationStoriesV3` и `PersonalizationStoriesV3.handleLink` (`pollsTransport`). abstract interface class StoryPollsTransport { - /// Ответ мини-опроса [code]. [body] — `{option_ids | text, story_id, slide_id}` - /// ([storyPollAnswerBody]); `shop_id`, `did` и `sid` добавляет транспорт. + /// Ответ мини-опроса [code]. [body] — `{option_ids | text}` и источник ответа + /// ([storyPollAnswerBody]); `shop_id`, `did`, `sid`, `stream` и `testmode` добавляет + /// транспорт. Future answerMiniPoll(String code, Map body); /// Оценка шкалы [kind] (NPS, CSAT, CES). [body] — `{channel, category | campaign, - /// rate}` ([storyPollReviewBody]); `shop_id`, `did` и `sid` добавляет транспорт. + /// rate[, comment]}` и источник ([storyPollReviewBody]); `shop_id`, `did`, `sid`, + /// `stream` и `testmode` добавляет транспорт. Future review(StoryPollType kind, Map body); } -/// Тело ответа мини-опроса: варианты [optionIds] или текст [text]; id кампании — -/// числом, как в ленте; id слайда — всегда строкой (у товарных слайдов он `39_0`). +/// Источник ответа для отчётов опросов, как в вебе: `source_type: stories`, +/// `source_id` — кампания, `source_item_id` — слайд, всё строками (у слайдов товарных +/// кампаний id вида `12_0`). Без кампании источника нет; пустой слайд не уходит. +Map storyPollSource({ + required String storyId, + required String slideId, +}) => storyId.isEmpty + ? const {} + : { + 'source_type': 'stories', + 'source_id': storyId, + if (slideId.isNotEmpty) 'source_item_id': slideId, + }; + +/// Тело ответа мини-опроса: варианты [optionIds] или текст [text] и источник ответа +/// ([storyPollSource]). Map storyPollAnswerBody({ List? optionIds, String? text, required String storyId, required String slideId, -}) { - final number = int.tryParse(storyId); - return { - 'option_ids': ?optionIds, - 'text': ?text, - if (storyId.isNotEmpty) - 'story_id': number != null && '$number' == storyId ? number : storyId, - if (slideId.isNotEmpty) 'slide_id': slideId, - }; -} +}) => { + 'option_ids': ?optionIds, + 'text': ?text, + ...storyPollSource(storyId: storyId, slideId: slideId), +}; -/// Тело оценки шкалы [poll]: канал опроса (пусто — `stories`), код — `category` у NPS -/// и `campaign` у CSAT и CES. -Map storyPollReviewBody(StoryPollElement poll, int rate) => - { - 'channel': poll.channel.isNotEmpty ? poll.channel : 'stories', - poll.pollType == StoryPollType.nps ? 'category' : 'campaign': poll.code, - 'rate': rate, - }; +/// Тело оценки [rate] шкалы [poll]: канал опроса (пусто — `stories`), код — `category` +/// у NPS и `campaign` у CSAT и CES, комментарий [comment] — только непустой (ответ на +/// вопрос полосы уходит второй оценкой с той же оценкой), и источник ответа +/// ([storyPollSource]). +Map storyPollReviewBody( + StoryPollElement poll, + num rate, { + String? comment, + String storyId = '', + String slideId = '', +}) => { + 'channel': poll.channel.isNotEmpty ? poll.channel : 'stories', + poll.pollType == StoryPollType.nps ? 'category' : 'campaign': poll.code, + 'rate': rate, + if (comment != null && comment.isNotEmpty) 'comment': comment, + ...storyPollSource(storyId: storyId, slideId: slideId), +}; /// Опросы API v3 на хосте [host] просмотра, с которого пришла лента: /// - мини-опрос — `POST /api/v3/polls/mini_polls/{code}/answers`; /// - шкала — `POST /api/v3/polls/{nps|csat|ces}/reviews`. /// -/// К телу добавляются `shop_id`, `did` (ждём его, как лента: [StoriesApiV3.identity]) и -/// `sid` сеанса SDK — всегда, без сеанса пустой строкой. Транспорт, таймаут и разбор +/// К телу добавляются `shop_id`, `did` (ждём его, как лента: [StoriesApiV3.identity]), +/// `sid` сеанса SDK — всегда, без сеанса пустой строкой, — `stream` и `testmode: true` в +/// тестовом режиме; `segment`, как и веб, — нет. Транспорт, таймаут и разбор /// `{status, payload}` — [StoriesApiV3.post]; ошибки — его, в отладочный лог с кодом HTTP /// и `message` сервера. class StoriesPollsApi implements StoryPollsTransport { - StoriesPollsApi(this.sdk, this.host); + StoriesPollsApi(this.sdk, this.host, {this.streamAndTestMode = true}); final PersonalizationSdk sdk; /// Хост API v3 без схемы (`app.rees46.ru`). final String host; + /// Слать `stream` и `testmode`, как опросы сторис; отзывы попапов v3 их не шлют. + final bool streamAndTestMode; + @override Future answerMiniPoll( String code, @@ -126,19 +150,26 @@ class StoriesPollsApi implements StoryPollsTransport { } } - Future> _identified(Map body) async { - final id = await StoriesApiV3.identity(sdk); - var sid = ''; - try { - sid = await sdk.getSid(); - } catch (_) { - // Нет сеанса — пустой `sid`. - } - return { - 'shop_id': id.shopId, - 'did': id.did, - 'sid': sid, - ...body, - }; - } + Future> _identified(Map body) async => + identifiedBody( + await StoriesApiV3.identity(sdk), + body, + streamAndTestMode: streamAndTestMode, + ); + + /// Тело запроса опроса: кто спрашивает и [body]. + static Map identifiedBody( + StoriesV3Identity id, + Map body, { + bool streamAndTestMode = true, + }) => { + 'shop_id': id.shopId, + 'did': id.did, + 'sid': id.sid, + if (streamAndTestMode) ...{ + 'stream': id.stream, + if (id.testMode) 'testmode': true, + }, + ...body, + }; } diff --git a/test/ui/stories_poll_test.dart b/test/ui/stories_poll_test.dart index 5479f42..1fed776 100644 --- a/test/ui/stories_poll_test.dart +++ b/test/ui/stories_poll_test.dart @@ -147,8 +147,9 @@ void main() { expect(transport.calls.single.$2, 'gift_recipient'); expect(transport.calls.single.$3, { 'option_ids': [2], - 'story_id': 5, - 'slide_id': '101', + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '101', }); expect(poll.sending, isTrue); expect(poll.selected, {2}); @@ -269,8 +270,9 @@ void main() { ..submitChoices(); expect(transport.calls.single.$3, { 'option_ids': [1, 3], - 'story_id': 5, - 'slide_id': '101', + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '101', }); await reply( 0, @@ -304,8 +306,9 @@ void main() { ..submitText(); expect(transport.calls.single.$3, { 'text': 'Мастер и', - 'story_id': 5, - 'slide_id': '101', + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '101', }); expect(poll.canSubmit, isFalse, reason: 'off while sending'); await reply( diff --git a/test/ui/stories_poll_widget_test.dart b/test/ui/stories_poll_widget_test.dart index cb2038f..1598f6e 100644 --- a/test/ui/stories_poll_widget_test.dart +++ b/test/ui/stories_poll_widget_test.dart @@ -1210,9 +1210,11 @@ void main() { 'shop_id': 'shop', 'did': 'did-1', 'sid': 'sid-1', + 'stream': 'flutter', 'option_ids': [2], - 'story_id': 1, - 'slide_id': '1', + 'source_type': 'stories', + 'source_id': '1', + 'source_item_id': '1', }); expect(find.text('Спасибо!'), findsOneWidget); await closeViewer(tester); diff --git a/test/ui/stories_polls_api_test.dart b/test/ui/stories_polls_api_test.dart index 0c7f5cb..81daf73 100644 --- a/test/ui/stories_polls_api_test.dart +++ b/test/ui/stories_polls_api_test.dart @@ -5,7 +5,10 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/core/native_events.dart'; import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/popups_v3/popups_v3.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_hooks.dart'; import 'package:rees46_sdk/src/stories/stories_response.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_polls_api.dart'; @@ -55,31 +58,69 @@ void main() { }); group('bodies', () { - test( - 'a mini poll: the campaign as a number, the slide always a string', - () { - expect( - storyPollAnswerBody( - optionIds: [2], - storyId: '5', - slideId: '101', - ), - { - 'option_ids': [2], - 'story_id': 5, - 'slide_id': '101', - }, - ); - expect( - storyPollAnswerBody(text: 'Мастер', storyId: '39', slideId: '39_0'), - { - 'text': 'Мастер', - 'story_id': 39, - 'slide_id': '39_0', - }, - ); - }, - ); + test('a mini poll: the source as strings, no story_id / slide_id', () { + expect( + storyPollAnswerBody(optionIds: [2], storyId: '5', slideId: '101'), + { + 'option_ids': [2], + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '101', + }, + ); + expect( + storyPollAnswerBody(text: 'Мастер', storyId: '39', slideId: '39_0'), + { + 'text': 'Мастер', + 'source_type': 'stories', + 'source_id': '39', + 'source_item_id': '39_0', + }, + ); + }); + + test('no story — no source; no slide — no source_item_id', () { + expect( + storyPollAnswerBody(optionIds: [1], storyId: '', slideId: '7'), + { + 'option_ids': [1], + }, + ); + expect(storyPollSource(storyId: '5', slideId: ''), { + 'source_type': 'stories', + 'source_id': '5', + }); + }); + + test('a review: the same rate with a comment, the source as strings', () { + expect( + storyPollReviewBody( + _poll(StoryPollType.nps), + 3, + comment: 'Долго', + storyId: '5', + slideId: '12_0', + ), + { + 'channel': 'stories', + 'category': 'delivery', + 'rate': 3, + 'comment': 'Долго', + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '12_0', + }, + ); + expect( + storyPollReviewBody(_poll(StoryPollType.csat), 4, comment: ''), + { + 'channel': 'stories', + 'campaign': 'delivery', + 'rate': 4, + }, + reason: 'an empty comment and no story are not sent', + ); + }); test('no code and a blank channel go as they are', () { expect( @@ -153,9 +194,11 @@ void main() { 'shop_id': 'shop', 'did': 'did-1', 'sid': 'sid-1', + 'stream': 'flutter', 'option_ids': [2], - 'story_id': 5, - 'slide_id': '101', + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '101', }); expect(result.answer!.id, 77); expect(result.answer!.optionIds, [2]); @@ -254,12 +297,57 @@ void main() { 'shop_id': 'shop', 'did': 'did-1', 'sid': 'sid-1', + 'stream': 'flutter', 'channel': 'stories', 'category': 'delivery', 'rate': 3, }); }); + group('identity', () { + tearDown(PopupsV3.reset); + + test( + 'the configured stream and test mode; no segment, as the web', + () async { + PopupsV3Hooks.initialized( + sdk.tracking, + const SdkInitConfig(shopId: 'shop', stream: ' android-tv '), + ); + sdk.popups.testMode = true; + NativeEvents.instance.shop('shop').segment = 'B'; + addTearDown(() => NativeEvents.instance.shop('shop').segment = null); + await polls.review(StoryPollType.nps, {'rate': 1}); + expect(requests.single.body, { + 'shop_id': 'shop', + 'did': 'did-1', + 'sid': 'sid-1', + 'stream': 'android-tv', + 'testmode': true, + 'rate': 1, + }); + }, + ); + + test( + 'the bridge copies of did and sid win over asking the bridge', + () async { + final mirror = NativeEvents.instance.shop('shop') + ..deviceId = 'did-mirror' + ..sessionId = 'sid-mirror'; + addTearDown(() { + mirror + ..deviceId = null + ..sessionId = null; + }); + await polls.answerMiniPoll('x', {'text': 'a'}); + expect(requests.single.body['did'], 'did-mirror'); + expect(requests.single.body['sid'], 'sid-mirror'); + expect(StoriesApiV3.knownDid(sdk), 'did-mirror'); + }, + ); + }); + group('errors', () { for (final status in [400, 402, 403, 404, 429, 500, 503]) { test('HTTP $status, with its code and message', () async { diff --git a/test/ui/stories_share_test.dart b/test/ui/stories_share_test.dart index 0dbfbd2..7d2b8ac 100644 --- a/test/ui/stories_share_test.dart +++ b/test/ui/stories_share_test.dart @@ -274,32 +274,92 @@ void main() { ); }); - test('the event: the campaign id a number, the slide id a string', () { - expect( - StoriesApiV3.eventBody( + test( + 'the event: who asks, the campaign id a number, the slide a string', + () { + const id = ( shopId: 'shop', did: 'did', - event: StoriesV3Event.sharedOpen, - storyId: '40', - slideId: '37', - ), - { - 'shop_id': 'shop', - 'did': 'did', - 'event': 'shared_open', - 'story_id': 40, - 'slide_id': '37', - }, - ); - final virtual = StoriesApiV3.eventBody( + sid: 'sid', + segment: 'A', + stream: 'flutter', + testMode: false, + ); + expect( + StoriesApiV3.eventBody( + id, + event: StoriesV3Event.sharedOpen, + storyId: '40', + slideId: '37', + ), + { + 'shop_id': 'shop', + 'did': 'did', + 'sid': 'sid', + 'segment': 'A', + 'stream': 'flutter', + 'event': 'shared_open', + 'story_id': 40, + 'slide_id': '37', + }, + ); + final virtual = StoriesApiV3.eventBody( + ( + shopId: 'shop', + did: 'did', + sid: '', + segment: '', + stream: 'qa', + testMode: true, + ), + event: StoriesV3Event.view, + storyId: '39', + slideId: '39_0', + ); + expect(virtual['story_id'], 39); + expect(virtual['slide_id'], '39_0'); + expect(virtual['testmode'], true); + expect(virtual['segment'], '', reason: 'an unknown group is empty'); + expect( + StoriesApiV3.eventBody( + id, + event: StoriesV3Event.click, + storyId: 'promo', + slideId: '1', + )['story_id'], + 'promo', + reason: 'not a number — a string', + ); + }, + ); + + test('the feed query: who asks, testmode only in test mode', () { + const id = ( shopId: 'shop', did: 'did', - event: StoriesV3Event.view, - storyId: '39', - slideId: '39_0', + sid: 'sid', + segment: 'B', + stream: 'flutter', + testMode: false, + ); + expect(StoriesApiV3.identityQuery(id), { + 'shop_id': 'shop', + 'did': 'did', + 'sid': 'sid', + 'segment': 'B', + 'stream': 'flutter', + }); + expect( + StoriesApiV3.identityQuery(( + shopId: 'shop', + did: 'did', + sid: 'sid', + segment: 'B', + stream: 'flutter', + testMode: true, + ))['testmode'], + 'true', ); - expect(virtual['story_id'], 39); - expect(virtual['slide_id'], '39_0'); }); test('addresses go to the v3 host, the scheme is optional', () { diff --git a/test/ui/stories_share_widget_test.dart b/test/ui/stories_share_widget_test.dart index 8ec3253..5a21d8a 100644 --- a/test/ui/stories_share_widget_test.dart +++ b/test/ui/stories_share_widget_test.dart @@ -4,7 +4,9 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/core/native_events.dart'; import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/popups_v3/popups_v3_hooks.dart'; import 'package:rees46_sdk/src/v3/personalization_v3.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; @@ -85,6 +87,9 @@ class _FakeHostApi extends pigeon.PersonalizationHostApi { @override Future getDid(String? shopId) async => 'did-1'; + @override + Future getSid(String? shopId) async => 'sid-1'; + @override Future legacyGetStories(String code, String? shopId) async => bridgeFeed ?? (throw StateError('the bridge feed is off with API v3')); @@ -144,6 +149,9 @@ class _Server { final List gets = []; final List events = []; + /// Bodies of the events, in order. + final List> bodies = >[]; + /// Hosts of all requests, in order. final List hosts = []; @@ -155,6 +163,7 @@ class _Server { expect(event['shop_id'], 'shop'); expect(event['did'], 'did-1'); events.add('${event['event']} ${event['story_id']}/${event['slide_id']}'); + bodies.add(event); return (status: 200, body: '{"status":"success"}'); } gets.add('${uri.path}?${uri.query}'); @@ -230,7 +239,7 @@ void main() { ) async { await bar(tester); expect(server.gets, [ - '/api/v3/storefront/stories/$_code?shop_id=shop&did=did-1', + '/api/v3/storefront/stories/$_code?shop_id=shop&did=did-1&sid=sid-1&segment=&stream=flutter', ]); await open(tester, 'Products'); expect(find.text('Product 39_0'), findsOneWidget); @@ -239,6 +248,47 @@ void main() { expect(api.sources, ['stories/$_code']); }); + testWidgets('the feed and the events carry sid, segment, stream, testmode', ( + tester, + ) async { + PopupsV3Hooks.initialized( + sdk.tracking, + const SdkInitConfig(shopId: 'shop', stream: 'qa'), + ); + sdk.popups.testMode = true; + addTearDown(PopupsV3.reset); + NativeEvents.instance.shop('shop').segment = 'B'; + addTearDown(() => NativeEvents.instance.shop('shop').segment = null); + await bar(tester); + expect(server.gets, [ + '/api/v3/storefront/stories/$_code' + '?shop_id=shop&did=did-1&sid=sid-1&segment=B&stream=qa&testmode=true', + ]); + await open(tester, 'Media'); + expect(server.bodies.single, { + 'shop_id': 'shop', + 'did': 'did-1', + 'sid': 'sid-1', + 'segment': 'B', + 'stream': 'qa', + 'testmode': true, + 'event': 'view', + 'story_id': 40, + 'slide_id': '37', + }); + }); + + testWidgets('back on the first slide restarts it and sends view again', ( + tester, + ) async { + await bar(tester); + await open(tester, 'Products'); + final viewer = tester.getRect(find.byType(PersonalizationStoryViewer)); + await tester.tapAt(Offset(viewer.left + 10, viewer.center.dy)); + await tester.pump(); + expect(server.events, ['view 39/39_0', 'view 39/39_0']); + }); + testWidgets('share: the campaign link, a pause until the sheet closes', ( tester, ) async { @@ -492,7 +542,7 @@ void main() { await _settle(tester); expect(server.gets, [ '/api/v3/storefront/stories/$_code/story/40' - '?shop_id=shop&did=did-1&slide_id=38', + '?shop_id=shop&did=did-1&sid=sid-1&segment=&stream=flutter&slide_id=38', ]); expect(find.text('Product 38'), findsOneWidget, reason: 'start_position'); expect(server.events, ['view 40/38', 'shared_open 40/38']); From 9f5483eda7966e85b359bebf731cdfab76645f2f Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 20 Nov 2026 12:06:00 +0400 Subject: [PATCH 02/24] feat(stories): poll answers of stories over API v3 are kept on the device for 90 days by did, poll kind, code, story and slide as the web SDK keeps them, the feed's answer winning over the saved one; a rate whose band has a question asks it with a comment field of up to 5000 characters and sends the same rate with the comment, then the band's success; the card shows what the web shows (no results header, no vote count, thanks_text after the rows), colours the scale with the kit's danger and warning tokens, sits at y_offset up to 16 above the slide's bottom, and its built-in texts are Russian or English by the device language --- lib/src/stories/stories_poll.dart | 48 +- .../personalization_story_poll.dart | 286 +++++------ .../ui/widgets/personalization_stories.dart | 3 + .../widgets/personalization_stories_v3.dart | 38 +- .../widgets/personalization_story_viewer.dart | 3 +- lib/src/ui/widgets/stories_poll.dart | 433 +++++++++++----- lib/src/ui/widgets/stories_slide_view.dart | 29 +- lib/src/ui/widgets/stories_v3_scope.dart | 8 +- test/stories/stories_poll_response_test.dart | 44 ++ test/ui/stories_poll_test.dart | 484 +++++++++++++----- test/ui/stories_poll_widget_test.dart | 218 +++++--- test/ui/stories_text_block_position_test.dart | 4 +- 12 files changed, 1065 insertions(+), 533 deletions(-) diff --git a/lib/src/stories/stories_poll.dart b/lib/src/stories/stories_poll.dart index 19ace4f..9d108cc 100644 --- a/lib/src/stories/stories_poll.dart +++ b/lib/src/stories/stories_poll.dart @@ -49,20 +49,35 @@ class StoryPollOption { final String label; } -/// Полоса шкалы `from..to` и текст благодарности за оценку из неё. +/// Полоса шкалы `from..to`: вопрос после оценки из неё и текст благодарности. class StoryPollBand { - const StoryPollBand({required this.from, required this.to, this.success}); + const StoryPollBand({ + required this.from, + required this.to, + this.question, + this.success, + }); final double from; final double to; + /// Вопрос после оценки из полосы: ответ на него уходит комментарием к той же оценке; + /// `null` — не задан. + final String? question; + /// Текст под отвеченной шкалой; `null` — не задан. final String? success; } -/// Ответ посетителя: варианты, текст или оценка. +/// Ответ посетителя: варианты, текст или оценка (с комментарием). class StoryPollAnswer { - const StoryPollAnswer({this.id, this.optionIds, this.text, this.rate}); + const StoryPollAnswer({ + this.id, + this.optionIds, + this.text, + this.rate, + this.comment, + }); final int? id; final List? optionIds; @@ -71,6 +86,9 @@ class StoryPollAnswer { /// Оценка шкалы. Дробная тоже ответ, но ни одну ячейку не подсвечивает. final num? rate; + /// Ответ на вопрос полосы оценки; `null` — его не давали. + final String? comment; + /// Ответ есть: непустые варианты, непустой текст или оценка. bool get isAnswered => (optionIds?.isNotEmpty ?? false) || @@ -82,13 +100,24 @@ class StoryPollAnswer { if (json is! Map) return null; final ids = json['option_ids']; final text = json['text']; + final comment = json['comment']; return StoryPollAnswer( id: toIntOrNull(json['id']), optionIds: ids is List ? [for (final id in ids) ?_whole(id)] : null, text: text is String ? text : null, rate: _number(json['rate']), + comment: comment is String ? comment : null, ); } + + /// Ответ в JSON, как его читает [tryParse]: пустые поля не пишутся. + Map toJson() => { + 'id': ?id, + 'option_ids': ?optionIds, + 'text': ?text, + 'rate': ?rate, + 'comment': ?comment, + }; } /// Итоги мини-опроса (`results`, только при `show_results`). @@ -113,6 +142,16 @@ class StoryPollResults { return 0; } + /// Итоги в JSON, как их читает [tryParse]. + Map toJson() => { + 'total': total, + if (options case final options?) + 'options': >[ + for (final option in options) + {'id': option.id, 'percent': option.percent}, + ], + }; + /// Итоги из JSON; не объект — `null`. static StoryPollResults? tryParse(Object? json) { if (json is! Map) return null; @@ -277,6 +316,7 @@ class StoryPollElement extends StoryElement { StoryPollBand( from: from, to: to, + question: toNonEmptyStringOrNull(band['question']), success: toNonEmptyStringOrNull(band['success']), ), ], diff --git a/lib/src/ui/components/personalization_story_poll.dart b/lib/src/ui/components/personalization_story_poll.dart index 84ff8ec..69e5c84 100644 --- a/lib/src/ui/components/personalization_story_poll.dart +++ b/lib/src/ui/components/personalization_story_poll.dart @@ -26,7 +26,7 @@ import '../widgets/stories_polls_api.dart'; /// в ките есть токен с тем же значением, взят токен. abstract final class _Poll { // Цвета. - /// Акцент: выбор, основная кнопка, точка шапки итогов. + /// Акцент: выбор, основная кнопка, зелёная треть шкалы (в ките нет токена успеха). static const Color accent = Color(0xFF22C55E); /// Заливка выбранного варианта до отправки — акцент 20 %. @@ -59,11 +59,6 @@ abstract final class _Poll { static const double padding = PersonalizationSpacing.xl2; static const double blur = 20; static const double cardBorderWidth = 1; - static const double dot = 6; - static const double dotGap = PersonalizationSpacing.md; - - /// От шапки итогов до вопроса. - static const double headerGap = PersonalizationSpacing.lg; /// От вопроса до содержимого, от содержимого до подвала, кнопки и текста полосы. static const double gap = PersonalizationSpacing.xl; @@ -101,16 +96,18 @@ abstract final class _Poll { ); static const double checkStroke = 2.5; static const double dimmed = 0.55; + + /// Заливка невыбранной цифры шкалы — её цвет на 20 %. + static const double tint = 0.2; + + /// Зазор между цифрами шкалы. + static const double cellGap = PersonalizationSpacing.xs; static const double sendingOpacity = 0.85; static const double linkPadding = PersonalizationSpacing.sm; static const Duration fillDuration = Duration(milliseconds: 600); static const Curve fillCurve = Cubic(0.2, 0.8, 0.2, 1); // Шрифт — кегли кита. - static const TextStyle header = PersonalizationTypography.xsEmphasized; - - /// Разрядка шапки итогов — 0,08 em. - static const double headerTracking = 0.08; static const TextStyle question = PersonalizationTypography.lgEmphasized; /// Межстрочный вопроса. @@ -133,7 +130,13 @@ abstract final class _Poll { /// хоста (как у `PersonalizationInputField`). Свернули приложение — клавиатура уходит; /// система убрала клавиатуру («назад» на Android) — поле отпускает фокус. /// - Карточка матовая: размывает слайд под собой. -/// - Тексты итогов выбора — по языку устройства ([StoryPollResultTexts]). +/// - Что на карточке — как в вебе: вопрос; у выбора — варианты, после ответа с +/// подсвеченным ответом и процентами, если сервер вернул итоги, и `thanks_text`; у +/// текста после ответа — галочка, `thanks_text` и сам ответ; шкала — цифры цветов +/// полос (Danger, Warning, зелёный опроса), после ответа выбранная оценка, остальные +/// приглушены и не нажимаются; дальше вопрос полосы с полем комментария (до 5000, со +/// счётчиком) или её `success`. Вид — токены кита. +/// - Встроенные тексты — по языку устройства ([StoryPollTexts]). /// - RTL: поля, полоски итогов и шкала зеркалятся. class PersonalizationStoryPoll extends StatefulWidget { const PersonalizationStoryPoll({ @@ -143,6 +146,7 @@ class PersonalizationStoryPoll extends StatefulWidget { required this.slideId, required this.transport, this.shopId = '', + this.did = '', this.texts = const StoryPollTexts(), this.live = true, this.onHold, @@ -153,8 +157,9 @@ class PersonalizationStoryPoll extends StatefulWidget { final String slideId; final StoryPollsTransport transport; - /// Магазин — ключ хранилища ответов сессии. + /// Магазин и устройство — ключ сохранённых ответов ([StoryPollStore]). final String shopId; + final String did; /// Тексты хоста; `labels` опроса важнее. final StoryPollTexts texts; @@ -178,6 +183,7 @@ class _PersonalizationStoryPollState extends State slideId: widget.slideId, transport: widget.transport, shopId: widget.shopId, + did: widget.did, texts: widget.texts, active: widget.live, onHold: (held) => widget.onHold?.call(held), @@ -188,6 +194,7 @@ class _PersonalizationStoryPollState extends State /// Пальцы на карточке. final Set _pointers = {}; bool _wasAnswered = false; + String? _wasFollowUp; /// Высота клавиатуры в прошлый раз. double _keyboard = 0; @@ -197,6 +204,7 @@ class _PersonalizationStoryPollState extends State super.initState(); WidgetsBinding.instance.addObserver(this); _wasAnswered = _poll.answered; + _wasFollowUp = _poll.followUp; _poll.addListener(_onPoll); _focus.addListener(_onFocus); } @@ -230,7 +238,7 @@ class _PersonalizationStoryPollState extends State @override void didChangeLocales(List? locales) { - // Тексты итогов — по языку устройства. + // Встроенные тексты — по языку устройства. if (mounted) setState(() {}); } @@ -253,7 +261,11 @@ class _PersonalizationStoryPollState extends State _input.clear(); _focus.requestFocus(); } + // Вопрос полосы после оценки — пустое поле, без фокуса, как в вебе. + final followUp = _poll.followUp; + if (followUp != null && _wasFollowUp == null) _input.clear(); _wasAnswered = _poll.answered; + _wasFollowUp = followUp; setState(() {}); } @@ -271,28 +283,13 @@ class _PersonalizationStoryPollState extends State _poll.pressed = _pointers.isNotEmpty; } - /// Тексты итогов у отвеченного выбора; у остального — `null`. - StoryPollResultTexts? get _summary { - final choice = switch (widget.poll.kind) { - StoryMiniPollKind.singleChoice || - StoryMiniPollKind.multipleChoice => true, - _ => false, - }; - if (!choice || !_poll.answered) return null; - return StoryPollResultTexts.of( - WidgetsBinding.instance.platformDispatcher.locale.languageCode, - ); - } - @override Widget build(BuildContext context) { final theme = PersonalizationTheme.of(context); final poll = _poll; - final texts = poll.texts; + final texts = _texts; final element = widget.poll; - final summary = _summary; final rows = <(Widget, double)>[ - if (summary != null) (_header(theme, summary.results), 0), if (element.question.isNotEmpty) ( Text( @@ -303,9 +300,9 @@ class _PersonalizationStoryPollState extends State height: _Poll.questionLine / _Poll.question.fontSize!, ), ), - _Poll.headerGap, + 0, ), - ..._body(theme, summary), + ..._body(theme, texts), if (poll.answered && element.allowReanswer) ( Align( @@ -417,63 +414,90 @@ class _PersonalizationStoryPollState extends State /// Содержимое карточки по виду и состоянию: строки и зазор перед каждой. extension on _PersonalizationStoryPollState { + /// Тексты карточки: `labels`, хост, встроенные по языку устройства. + StoryPollTexts get _texts => _poll.textsFor( + WidgetsBinding.instance.platformDispatcher.locale.languageCode, + ); + List<(Widget, double)> _body( PersonalizationTheme theme, - StoryPollResultTexts? summary, + StoryPollTexts texts, ) { final poll = _poll; final element = widget.poll; if (element.pollType.isScale) { - final band = poll.answered + final followUp = poll.followUp; + final band = poll.answered && followUp == null ? storyPollBandText(element, poll.answer?.rate) : null; return <(Widget, double)>[ (_scale(theme), _Poll.gap), + if (followUp != null) ...<(Widget, double)>[ + (Text(followUp, style: _style(theme, _Poll.smallStrong)), _Poll.gap), + ..._fieldRows(theme, texts.submit, poll.submitComment), + ], if (band != null && band.isNotEmpty) (Text(band, style: _style(theme, _Poll.small)), _Poll.gap), ]; } + final thanks = element.thanksText; switch (element.kind) { case StoryMiniPollKind.singleChoice || StoryMiniPollKind.multipleChoice - when summary != null: + when poll.answered: return <(Widget, double)>[ (_answeredOptions(theme), _Poll.gap), - (_footer(theme, summary), _Poll.gap), + if (thanks.isNotEmpty) + (Text(thanks, style: _style(theme, _Poll.smallStrong)), _Poll.gap), ]; case StoryMiniPollKind.singleChoice: return <(Widget, double)>[(_choiceOptions(theme), _Poll.gap)]; case StoryMiniPollKind.multipleChoice: return <(Widget, double)>[ (_choiceOptions(theme, multiple: true), _Poll.gap), - (_submit(theme, poll.submitChoices), _Poll.gap), + (_submit(theme, _submitLabel(texts), poll.submitChoices), _Poll.gap), ]; case StoryMiniPollKind.text when poll.answered: return <(Widget, double)>[(_done(theme), _Poll.gap)]; case StoryMiniPollKind.text: - final limit = element.maxLength; - return <(Widget, double)>[ - (_field(theme), _Poll.gap), - if (limit != null) - ( - Text( - '${poll.text.length}/$limit', - textAlign: TextAlign.end, - style: _style( - theme, - _Poll.note, - color: theme.colors.textDarkSecondary, - tabular: true, - ), - ), - _Poll.counterGap, - ), - (_submit(theme, poll.submitText), _Poll.fieldGap), - ]; + return _fieldRows(theme, _submitLabel(texts), poll.submitText); case null: return const <(Widget, double)>[]; } } + /// Подпись кнопки мини-опроса: `submit_label`, без неё — текст карточки. + String _submitLabel(StoryPollTexts texts) => + widget.poll.submitLabel.isNotEmpty + ? widget.poll.submitLabel + : texts.submit; + + /// Поле, счётчик при пределе длины и кнопка [label], которая зовёт [send]. + List<(Widget, double)> _fieldRows( + PersonalizationTheme theme, + String label, + VoidCallback send, + ) { + final limit = _poll.fieldLimit; + return <(Widget, double)>[ + (_field(theme), _Poll.gap), + if (limit != null) + ( + Text( + '${_poll.text.length}/$limit', + textAlign: TextAlign.end, + style: _style( + theme, + _Poll.note, + color: theme.colors.textDarkSecondary, + tabular: true, + ), + ), + _Poll.counterGap, + ), + (_submit(theme, label, send), _Poll.fieldGap), + ]; + } + Widget _list(List children) => Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -519,72 +543,7 @@ extension on _PersonalizationStoryPollState { ]); } - /// Шапка итогов: точка акцента и «РЕЗУЛЬТАТЫ». - Widget _header(PersonalizationTheme theme, String text) => Row( - children: [ - const SizedBox.square( - dimension: _Poll.dot, - child: DecoratedBox( - decoration: BoxDecoration( - color: _Poll.accent, - shape: BoxShape.circle, - ), - ), - ), - const SizedBox(width: _Poll.dotGap), - Flexible( - child: Text( - text.toUpperCase(), - semanticsLabel: text, - style: _style( - theme, - _Poll.header, - color: theme.colors.textDarkSecondary, - tracking: _Poll.headerTracking * _Poll.header.fontSize!, - ), - ), - ), - ], - ); - - /// Подвал итогов: благодарность опроса или «Спасибо! Голос учтён»; справа — число - /// голосов, если оно есть. - Widget _footer(PersonalizationTheme theme, StoryPollResultTexts texts) { - final thanks = widget.poll.thanksText; - final total = _poll.results?.total ?? 0; - final strong = _style(theme, _Poll.smallStrong); - final muted = _style( - theme, - _Poll.small, - color: theme.colors.textDarkSecondary, - ); - return Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: thanks.isNotEmpty - ? Text(thanks, style: strong) - : Text.rich( - TextSpan( - children: [ - TextSpan(text: texts.thanks, style: strong), - TextSpan(text: ' ${texts.counted}', style: muted), - ], - ), - ), - ), - if (total > 0) ...[ - const SizedBox(width: _Poll.letterGap), - Text(texts.votes(total), style: muted), - ], - ], - ); - } - - Widget _submit(PersonalizationTheme theme, VoidCallback send) { - final label = widget.poll.submitLabel.isNotEmpty - ? widget.poll.submitLabel - : _poll.texts.submit; + Widget _submit(PersonalizationTheme theme, String label, VoidCallback send) { final enabled = _poll.canSubmit; return Semantics( button: true, @@ -618,11 +577,12 @@ extension on _PersonalizationStoryPollState { /// Поле, отвеченный текст и шкала. extension on _PersonalizationStoryPollState { - /// Поле ввода: растёт до [_Poll.fieldLines] строк; предел `max_length` обрезает - /// ввод; пока идёт отправка, текст не меняется, а клавиатура остаётся. + /// Поле ввода: растёт до [_Poll.fieldLines] строк; предел (`max_length`, у + /// комментария — 5000) обрезает ввод; пока идёт отправка, текст не меняется, а + /// клавиатура остаётся. Подсказка `placeholder` — только у текстового опроса. Widget _field(PersonalizationTheme theme) { final style = _style(theme, _Poll.body); - final placeholder = widget.poll.placeholder; + final placeholder = _poll.followUp == null ? widget.poll.placeholder : ''; return Container( constraints: const BoxConstraints(minHeight: _Poll.field), padding: _Poll.fieldPadding, @@ -649,7 +609,7 @@ extension on _PersonalizationStoryPollState { style: style, inputFormatters: [ _PollInputFormatter( - limit: widget.poll.maxLength, + limit: _poll.fieldLimit, frozen: () => _poll.sending, ), ], @@ -696,17 +656,19 @@ extension on _PersonalizationStoryPollState { ); } - /// Шкала — дорожка, цифры поровну. В форме нажатие отправляет; выбранная — капсула - /// цвета её полосы, у отвеченной остальные приглушены. + /// Шкала — дорожка, цифры поровну, каждая — в цвете своей трети: Danger, Warning и + /// зелёный опроса (у NPS 0–6, 7–8 и 9–10). В форме нажатие отправляет; выбранная — + /// залита цветом, у отвеченной остальные приглушены и не нажимаются. Widget _scale(PersonalizationTheme theme) { final element = widget.poll; final values = storyPollScaleRange(element); if (values.isEmpty) return const SizedBox.shrink(); final answered = _poll.answered; final highlighted = _poll.rateValue; + final colors = theme.colors; return Container( constraints: const BoxConstraints(minHeight: _Poll.track), - padding: const EdgeInsets.symmetric(horizontal: _Poll.trackPadding), + padding: const EdgeInsets.all(_Poll.trackPadding), decoration: const BoxDecoration( color: _Poll.well, borderRadius: BorderRadius.all( @@ -722,15 +684,16 @@ extension on _PersonalizationStoryPollState { child: _ScaleCell( theme: theme, value: value, - // Без полос — акцент. - color: element.bands.isEmpty - ? _Poll.accent - : storyPollScaleColor( - element.pollType, - value, - values.first, - values.last, - ), + color: switch (storyPollScaleTone( + element.pollType, + value, + values.first, + values.last, + )) { + StoryPollScaleTone.danger => colors.semanticDanger, + StoryPollScaleTone.warning => colors.semanticWarning, + StoryPollScaleTone.success => _Poll.accent, + }, selected: value == highlighted, dimmed: answered && value != highlighted, onTap: answered || _poll.sending @@ -1030,30 +993,31 @@ class _ScaleCell extends StatelessWidget { selected: selected, child: _Tap( onTap: onTap, - child: DecoratedBox( - decoration: selected - ? BoxDecoration( - color: color, - borderRadius: BorderRadius.circular( - PersonalizationRadius.rounded, - ), - ) - : const BoxDecoration(), - child: Center( - child: Opacity( - opacity: dimmed ? _Poll.dimmed : 1, - child: FittedBox( - fit: BoxFit.scaleDown, - child: Text( - '$value', - maxLines: 1, - style: _style( - theme, - _Poll.bodyStrong, - color: selected - ? _onFill(color, theme.colors.textDarkPrimary) - : theme.colors.textDarkPrimary, - tabular: true, + child: Opacity( + opacity: dimmed ? _Poll.dimmed : 1, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: _Poll.cellGap / 2), + child: DecoratedBox( + decoration: BoxDecoration( + color: selected ? color : color.withValues(alpha: _Poll.tint), + borderRadius: BorderRadius.circular( + PersonalizationRadius.rounded, + ), + ), + child: Center( + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + '$value', + maxLines: 1, + style: _style( + theme, + _Poll.bodyStrong, + color: selected + ? _onFill(color, theme.colors.textDarkPrimary) + : theme.colors.textDarkPrimary, + tabular: true, + ), ), ), ), diff --git a/lib/src/ui/widgets/personalization_stories.dart b/lib/src/ui/widgets/personalization_stories.dart index 286ec20..a5e0825 100644 --- a/lib/src/ui/widgets/personalization_stories.dart +++ b/lib/src/ui/widgets/personalization_stories.dart @@ -534,6 +534,9 @@ Future> _fetch( } else { request = sdk.getStories(code); } + // Сохранённые ответы опросов открываются заранее, но ленту не держат: карточка, + // показанная раньше, возьмёт их, когда хранилище откроется. + if (host != null) unawaited(StoryPollStore.instance.load()); // Просмотренное читается вместе с блоком; ошибка блока приходит как есть. final results = await Future.wait(>[ request, diff --git a/lib/src/ui/widgets/personalization_stories_v3.dart b/lib/src/ui/widgets/personalization_stories_v3.dart index f57b9ae..9e88143 100644 --- a/lib/src/ui/widgets/personalization_stories_v3.dart +++ b/lib/src/ui/widgets/personalization_stories_v3.dart @@ -16,8 +16,8 @@ part of 'personalization_stories.dart'; /// /// Опросы слайдов — тоже только с API v3: ответы уходят на хост блока, а /// [pollsTransport] их подменяет (тесты, офлайн-демо). Просмотр под -/// [PersonalizationStoriesV3] со своим [pollsTransport] рисует опросы и без API v3. Ответы -/// сессии помнят все блоки, `show` и [handleLink] — до конца процесса. +/// [PersonalizationStoriesV3] со своим [pollsTransport] рисует опросы и без API v3. Ответ +/// хранится на устройстве по `did` 90 дней, как в вебе; ответ из ленты важнее него. /// /// ```dart /// PersonalizationStoriesV3( @@ -33,9 +33,9 @@ class PersonalizationStoriesV3 extends StatelessWidget { this.shareLabel = 'Share', this.shareUrlTransform, this.pollsTransport, - this.pollReanswerText = 'Answer again', - this.pollSubmitText = 'Send', - this.pollErrorText = 'Failed to send the answer. Please try again', + this.pollReanswerText, + this.pollSubmitText, + this.pollErrorText, required this.child, }) : ownApiV3Domain = apiV3Domain; @@ -56,10 +56,12 @@ class PersonalizationStoriesV3 extends StatelessWidget { final StoryPollsTransport? pollsTransport; /// Тексты карточки опроса: ссылка «Ответить заново», кнопка отправки без своей подписи - /// опроса и ошибка отправки. Непустые `labels` опроса от сервера важнее. - final String pollReanswerText; - final String pollSubmitText; - final String pollErrorText; + /// опроса (и кнопка комментария к оценке шкалы) и ошибка отправки. Непустые `labels` + /// опроса от сервера важнее; `null` или пусто — встроенные по языку устройства + /// (русские или английские). + final String? pollReanswerText; + final String? pollSubmitText; + final String? pollErrorText; /// Поддерево в режиме v3. final Widget child; @@ -81,9 +83,9 @@ class PersonalizationStoriesV3 extends StatelessWidget { shareUrlTransform: shareUrlTransform, pollsTransport: pollsTransport, pollTexts: StoryPollTexts( - reanswer: pollReanswerText, - error: pollErrorText, - submit: pollSubmitText, + reanswer: pollReanswerText ?? '', + error: pollErrorText ?? '', + submit: pollSubmitText ?? '', ), ), child: child, @@ -133,9 +135,9 @@ class PersonalizationStoriesV3 extends StatelessWidget { iconBuilder, String Function(String url)? shareUrlTransform, StoryPollsTransport? pollsTransport, - String pollReanswerText = 'Answer again', - String pollSubmitText = 'Send', - String pollErrorText = 'Failed to send the answer. Please try again', + String? pollReanswerText, + String? pollSubmitText, + String? pollErrorText, String? apiV3Domain, }) { final link = parseStoriesShareLink(url); @@ -172,9 +174,9 @@ class PersonalizationStoriesV3 extends StatelessWidget { shareUrlTransform: shareUrlTransform, pollsTransport: pollsTransport, pollTexts: StoryPollTexts( - reanswer: pollReanswerText, - error: pollErrorText, - submit: pollSubmitText, + reanswer: pollReanswerText ?? '', + error: pollErrorText ?? '', + submit: pollSubmitText ?? '', ), ); unawaited( diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index e643bdb..fc8a925 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -205,7 +205,7 @@ class PersonalizationStoryViewer extends StatefulWidget { // без него — на хост API v3 просмотра ([StoriesPollsApi], нужен `sdk`); нет ни того ни // другого — опросы не рисуются. Свой транспорт рисует их и без API v3. Пока карточку // держат пальцем, в фокусе её поле или идёт отправка — пауза; касания карточки слайд не -// листают. Ответы помнятся до конца процесса ([StoryPollStore]). +// листают. Ответы помнятся на устройстве по did 90 дней ([StoryPollStore]). class _PersonalizationStoryViewerState extends State with SingleTickerProviderStateMixin, WidgetsBindingObserver { late final StoriesPlayback _playback = StoriesPlayback( @@ -962,6 +962,7 @@ class _PersonalizationStoryViewerState extends State pollShopId: widget.sdk == null ? '' : StoriesSeenStore.shopOf(widget.sdk!), + pollDid: widget.sdk == null ? '' : StoriesApiV3.knownDid(widget.sdk!), onPollHold: (held) { if (mounted) _setPaused(StoriesPauseReason.poll, held); }, diff --git a/lib/src/ui/widgets/stories_poll.dart b/lib/src/ui/widgets/stories_poll.dart index 823f382..8243bac 100644 --- a/lib/src/ui/widgets/stories_poll.dart +++ b/lib/src/ui/widgets/stories_poll.dart @@ -1,24 +1,35 @@ -import 'dart:math' as math; +import 'dart:async'; +import 'dart:convert'; +import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; -import 'package:flutter/painting.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '../../stories/stories_response.dart'; import 'stories_polls_api.dart'; -/// Тексты карточки опроса: умолчания < тексты хоста < `labels` элемента. +/// Тексты карточки опроса: `labels` элемента < тексты хоста < встроенные по языку +/// устройства (русские для `ru`, остальные — английские). Пустой текст хоста — не задан. @immutable class StoryPollTexts { - const StoryPollTexts({ - this.reanswer = defaultReanswer, - this.error = defaultError, - this.submit = defaultSubmit, - }); + const StoryPollTexts({this.reanswer = '', this.error = '', this.submit = ''}); - static const String defaultReanswer = 'Answer again'; - static const String defaultError = - 'Failed to send the answer. Please try again'; - static const String defaultSubmit = 'Send'; + /// Встроенные русские. + static const StoryPollTexts ru = StoryPollTexts( + reanswer: 'Ответить заново', + error: 'Не удалось отправить ответ. Попробуйте еще раз', + submit: 'Отправить', + ); + + /// Встроенные английские. + static const StoryPollTexts en = StoryPollTexts( + reanswer: 'Answer again', + error: 'Failed to send the answer. Please try again', + submit: 'Send', + ); + + /// Встроенные для кода языка [language]: `ru` — русские, остальные — английские. + static StoryPollTexts builtIn(String language) => language == 'ru' ? ru : en; /// Ссылка «Ответить заново» у отвеченного опроса с `allow_reanswer`. final String reanswer; @@ -26,85 +37,34 @@ class StoryPollTexts { /// Отправка не удалась. final String error; - /// Кнопка отправки, когда у опроса нет `submit_label`. + /// Кнопка отправки, когда у опроса нет `submit_label`, и кнопка комментария к оценке + /// шкалы. final String submit; /// Тексты для [poll]: непустые `labels` сервера, иначе непустые тексты хоста, иначе - /// умолчания. - StoryPollTexts forPoll(StoryPollElement poll) { + /// встроенные языка [language] (по умолчанию — устройства). + StoryPollTexts forPoll(StoryPollElement poll, {String? language}) { + final builtIn = StoryPollTexts.builtIn( + language ?? ui.PlatformDispatcher.instance.locale.languageCode, + ); String pick(String? label, String host, String fallback) => label ?? (host.isNotEmpty ? host : fallback); return StoryPollTexts( - reanswer: pick(poll.labels.reanswer, reanswer, defaultReanswer), - error: pick(poll.labels.error, error, defaultError), - submit: pick(poll.labels.submit, submit, defaultSubmit), + reanswer: pick(poll.labels.reanswer, reanswer, builtIn.reanswer), + error: pick(poll.labels.error, error, builtIn.error), + submit: pick(poll.labels.submit, submit, builtIn.submit), ); } -} - -/// Тексты итогов опроса с выбором: шапка «Результаты», «Спасибо! Голос учтён» и число -/// голосов. Язык — устройства, как у текстов попапов v3: русский для `ru`, остальные — -/// английский. -@immutable -class StoryPollResultTexts { - const StoryPollResultTexts._({ - required this.results, - required this.thanks, - required this.counted, - required bool russian, - }) : _russian = russian; - - static const StoryPollResultTexts ru = StoryPollResultTexts._( - results: 'Результаты', - thanks: 'Спасибо!', - counted: 'Голос учтён', - russian: true, - ); - static const StoryPollResultTexts en = StoryPollResultTexts._( - results: 'Results', - thanks: 'Thank you!', - counted: 'Vote counted', - russian: false, - ); - - /// По коду языка [language]: `ru` — русский, остальные — английский. - static StoryPollResultTexts of(String language) => language == 'ru' ? ru : en; - - /// Шапка итогов; на карточке — прописными. - final String results; - - /// Благодарность, когда у опроса нет своего `thanks_text`. - final String thanks; - - /// Продолжение благодарности. - final String counted; - final bool _russian; - - /// Число голосов [count] с разрядами (у русского — неразрывный пробел) и склонением: - /// «1 голос», «1 248 голосов», «1 vote», «1,248 votes». - String votes(int count) { - final number = _grouped(count, _russian ? '\u00A0' : ','); - if (!_russian) return '$number ${count == 1 ? 'vote' : 'votes'}'; - final tens = count.abs() % 100; - final ones = count.abs() % 10; - final noun = ones == 1 && tens != 11 - ? 'голос' - : ones >= 2 && ones <= 4 && (tens < 12 || tens > 14) - ? 'голоса' - : 'голосов'; - return '$number $noun'; - } + @override + bool operator ==(Object other) => + other is StoryPollTexts && + other.reanswer == reanswer && + other.error == error && + other.submit == submit; - static String _grouped(int value, String separator) { - final digits = value.abs().toString(); - final out = StringBuffer(value < 0 ? '-' : ''); - for (var i = 0; i < digits.length; i++) { - if (i > 0 && (digits.length - i) % 3 == 0) out.write(separator); - out.write(digits[i]); - } - return out.toString(); - } + @override + int get hashCode => Object.hash(reanswer, error, submit); } /// Оценки шкалы: `rate_min..rate_max`, по умолчанию NPS 0..10, CSAT 1..5, CES 1..7; не @@ -122,58 +82,173 @@ List storyPollScaleRange(StoryPollElement poll) { ]; } -const List _npsColors = [ - Color(0xFFFCA5A5), - Color(0xFFFCA5A5), - Color(0xFFFCA5A5), - Color(0xFFFDBA74), - Color(0xFFFDBA74), - Color(0xFFFDBA74), - Color(0xFFFCD34D), -]; - -/// Цвет ячейки [value] шкалы [min]..[max]: NPS 0..10 — 0–6 красные и оранжевые, 7–8 -/// жёлтые, 9–10 зелёные; остальные — по третям диапазона. -Color storyPollScaleColor(StoryPollType kind, int value, int min, int max) { +/// Цвет цифры шкалы — семантический тон кита. +enum StoryPollScaleTone { danger, warning, success } + +/// Тон цифры [value] шкалы [min]..[max], как цвета веба: у NPS 0..10 — 0–6 Danger, 7–8 +/// Warning, 9–10 зелёный; у остальных — по третям диапазона. +StoryPollScaleTone storyPollScaleTone( + StoryPollType kind, + int value, + int min, + int max, +) { if (kind == StoryPollType.nps && min == 0 && max == 10) { - if (value <= 6) return _npsColors[math.max(0, value)]; - return value <= 8 ? const Color(0xFFFDE68A) : const Color(0xFF86EFAC); + if (value <= 6) return StoryPollScaleTone.danger; + return value <= 8 ? StoryPollScaleTone.warning : StoryPollScaleTone.success; } final position = max > min ? (value - min) / (max - min) : 1; - if (position < 0.34) return const Color(0xFFFCA5A5); - return position < 0.68 ? const Color(0xFFFDE68A) : const Color(0xFF86EFAC); + if (position < 0.34) return StoryPollScaleTone.danger; + return position < 0.68 + ? StoryPollScaleTone.warning + : StoryPollScaleTone.success; } -/// Текст `success` полосы шкалы, где `from ≤ rate ≤ to`; нет такой — `null`. -String? storyPollBandText(StoryPollElement poll, num? rate) { +/// Длина комментария к оценке шкалы — ответа на вопрос полосы. +const int storyPollCommentMaxLength = 5000; + +/// Полоса шкалы, где `from ≤ rate ≤ to`; нет такой — `null`. +StoryPollBand? storyPollBandOf(StoryPollElement poll, num? rate) { if (rate == null) return null; for (final band in poll.bands) { - if (rate >= band.from && rate <= band.to) return band.success; + if (rate >= band.from && rate <= band.to) return band; } return null; } +/// Текст `success` полосы оценки [rate]; нет — `null`. +String? storyPollBandText(StoryPollElement poll, num? rate) => + storyPollBandOf(poll, rate)?.success; + +/// Вопрос полосы оценки [rate] без пробелов по краям; нет или пустой — `null`. +String? storyPollBandQuestion(StoryPollElement poll, num? rate) { + final question = storyPollBandOf(poll, rate)?.question?.trim() ?? ''; + return question.isEmpty ? null : question; +} + /// Ответ опроса и итоги, как их показать. typedef StoryPollState = ({StoryPollAnswer? answer, StoryPollResults? results}); -/// Ответы опросов за сессию: в памяти процесса, одно на все виджеты, `show` и -/// ссылки. Ключ — магазин, вид опроса и код. Важнее ответа из ленты: лента -/// сторис не перезагружается после ответа. На диск не пишется. +/// Где опрос: магазин и устройство (`did`) — пространство ответов, кампания и слайд. +typedef StoryPollPlace = ({ + String shopId, + String did, + String storyId, + String slideId, +}); + +/// Ответы опросов на устройстве — как `localStorage` веба: +/// - запись — `{answer, results, saved_at}` (мс эпохи) в SharedPreferences под ключом +/// `personalization.storiesPolls.<магазин>.stories_poll__<вид>_<код>_<сторис>_<слайд>` +/// ([keyOf]); без `did` ничего не читается и не пишется; +/// - живёт 90 дней ([ttl]): старше или без даты — удаляется при чтении; +/// - что показать ([stateOf]): отправленное в этом процессе (так веб меняет элемент +/// ленты в кэше) < ответ ленты < сохранённое < ничего; лента важнее сохранённого. class StoryPollStore { + StoryPollStore({DateTime Function()? clock}) : _clock = clock ?? DateTime.now; + /// Хранилище процесса. Тесты подменяют его. static StoryPollStore instance = StoryPollStore(); - final Map _states = {}; + /// Сколько помнить ответ — столько же лента сервера помнит его сама. + static const Duration ttl = Duration(days: 90); + + static const String _prefix = 'personalization.storiesPolls'; - static String _key(String shopId, StoryPollElement poll) => - '$shopId\n${poll.pollType.wire}\n${poll.code}'; + final DateTime Function() _clock; + final Expando _sent = Expando('storyPoll'); + SharedPreferences? _preferences; + Future? _opening; - /// Сохранённый ответ опроса [poll] магазина [shopId]; нет — `null`. - StoryPollState? read(String shopId, StoryPollElement poll) => - _states[_key(shopId, poll)]; + /// Записи устройства читаются без ожидания: хранилище открыто ([load]). + bool get ready => _preferences != null; - void write(String shopId, StoryPollElement poll, StoryPollState state) => - _states[_key(shopId, poll)] = state; + /// Открыть хранилище устройства; ошибка — ответы живут только в памяти. + Future load() => _opening ??= _open(); + + Future _open() async { + try { + _preferences = await SharedPreferences.getInstance(); + } catch (error) { + debugPrint( + 'PersonalizationStories: saved poll answers unavailable — $error', + ); + } + } + + /// Ключ записи опроса [poll] в месте [place]; без `did` — `null`. + static String? keyOf(StoryPollElement poll, StoryPollPlace place) { + if (place.did.isEmpty) return null; + return '$_prefix.${place.shopId}.stories_poll_${place.did}_' + '${poll.pollType.wire}_${poll.code}_${place.storyId}_${place.slideId}'; + } + + /// Что показать у опроса [poll] сейчас: отправленное в процессе, ответ ленты, + /// сохранённое на устройстве ([saved]); ничего — ответ и итоги ленты как есть. + StoryPollState stateOf(StoryPollElement poll, StoryPollPlace place) { + final sent = _sent[poll]; + if (sent != null) return sent; + final feed = (answer: poll.answer, results: poll.results); + if (poll.answer != null) return feed; + return saved(poll, place) ?? feed; + } + + /// Ответ [poll] отправлен в этом процессе. + bool sentOf(StoryPollElement poll) => _sent[poll] != null; + + /// Сохранённая запись опроса [poll]; нет, без `did`, хранилище не открыто, битая — + /// `null`. Старше [ttl] или без даты — удаляется. + StoryPollState? saved(StoryPollElement poll, StoryPollPlace place) { + final key = keyOf(poll, place); + final preferences = _preferences; + if (key == null || preferences == null) return null; + try { + final raw = preferences.getString(key); + if (raw == null) return null; + final value = jsonDecode(raw); + if (value is! Map || value['answer'] is! Map) return null; + final savedAt = value['saved_at']; + if (savedAt is! num || + _clock().millisecondsSinceEpoch - savedAt > ttl.inMilliseconds) { + preferences.remove(key).ignore(); + return null; + } + return ( + answer: StoryPollAnswer.tryParse(value['answer']), + results: StoryPollResults.tryParse(value['results']), + ); + } catch (error) { + debugPrint('PersonalizationStories: saved poll answer skipped — $error'); + return null; + } + } + + /// Ответ [state] опроса [poll] отправлен: он заменяет ответ этого элемента ленты в + /// процессе и пишется на устройство (без `did` — только в процессе). + void write( + StoryPollElement poll, + StoryPollPlace place, + StoryPollState state, + ) { + _sent[poll] = state; + final key = keyOf(poll, place); + if (key == null) return; + final record = jsonEncode({ + 'answer': (state.answer ?? const StoryPollAnswer()).toJson(), + 'results': state.results?.toJson(), + 'saved_at': _clock().millisecondsSinceEpoch, + }); + unawaited(_save(key, record)); + } + + Future _save(String key, String record) async { + await load(); + try { + await _preferences?.setString(key, record); + } catch (error) { + debugPrint('PersonalizationStories: poll answer not saved — $error'); + } + } } /// Касания, начатые на карточке опроса или на подложке под открытой клавиатурой: слайд @@ -191,16 +266,20 @@ abstract final class StoryPollPointers { /// Логика карточки опроса — как `createPoll` веб-SDK, без UI. /// -/// - Состояния: форма и отвеченное ([answered]). Отвеченное — когда есть запись хранилища -/// сессии ([StoryPollStore]) или у ответа ленты есть варианты, текст или оценка. +/// - Состояния: форма и отвеченное ([answered]). Что показать сначала — [StoryPollStore]: +/// отправленное в процессе, ответ ленты, сохранённое на устройстве; отвечено, когда +/// ответ отправлен в процессе или в нём есть варианты, текст или оценка. /// - Выбор одного и шкала отправляются нажатием ([choose], [rate]); выбор сразу /// подсвечен, при ошибке откатывается к прежнему. Выбор нескольких и текст — кнопкой /// ([submitChoices], [submitText]); варианты уходят в порядке опроса, текст — без /// пробелов по краям. +/// - Шкала: у полосы оценки есть вопрос, а у ответа нет комментария — после оценки +/// вопрос и поле ([followUp]); [submitComment] шлёт ту же оценку с комментарием, потом +/// `success` полосы. Ушли со слайда без комментария — при следующем показе вопрос снова. /// - Пока идёт отправка ([sending]), всё выключено, повторы игнорируются. Ошибка — /// [failed], всё снова доступно, автоповтора нет; в лог её пишет транспорт. /// - [reanswer] при `allow_reanswer` возвращает форму с прежним ответом (у текста — -/// пустое поле). +/// пустое поле); новая оценка шкалы уходит без комментария. /// - Слайд держит [onHold]: пока карточку держат пальцем ([pressed]), в фокусе поле /// ([focused]) или идёт отправка — и только пока карточка [active] (живой слайд). /// @@ -213,20 +292,26 @@ class StoryPollController extends ChangeNotifier { required this.slideId, required this.transport, this.shopId = '', + this.did = '', StoryPollTexts texts = const StoryPollTexts(), this.onHold, bool active = true, StoryPollStore? store, - }) : texts = texts.forPoll(poll), + }) : hostTexts = texts, _active = active, _store = store ?? StoryPollStore.instance { - final saved = _store.read(shopId, poll); - _answer = saved != null ? saved.answer : poll.answer; - _results = saved != null ? saved.results : poll.results; - // Запись хранилища — это успешная отправка: отвечено, даже если ответ ничего не - // выделяет. - _answered = saved != null || (_answer?.isAnswered ?? false); - _resetForm(); + _show(_store.stateOf(poll, _place)); + // Хранилище устройства ещё не открыто — сохранённое придёт позже, если до тех пор + // карточку не трогали. + if (!_store.ready && did.isNotEmpty && poll.answer == null) { + _store.load().then((_) { + if (_disposed || _touched || _store.sentOf(poll)) return; + final saved = _store.saved(poll, _place); + if (saved == null) return; + _show(saved); + _changed(); + }); + } } final StoryPollElement poll; @@ -234,11 +319,15 @@ class StoryPollController extends ChangeNotifier { final String slideId; final StoryPollsTransport transport; - /// Магазин — часть ключа хранилища. + /// Магазин — часть ключа сохранённых ответов. final String shopId; - /// Тексты с учётом `labels` опроса. - final StoryPollTexts texts; + /// Устройство (`did`) — часть ключа сохранённых ответов; пусто — ответ живёт только в + /// процессе. + final String did; + + /// Тексты хоста. + final StoryPollTexts hostTexts; /// Держать слайд (`true`) или отпустить. final ValueChanged? onHold; @@ -249,6 +338,7 @@ class StoryPollController extends ChangeNotifier { bool _answered = false; bool _sending = false; bool _failed = false; + bool _touched = false; Set _selected = const {}; num? _rate; String _text = ''; @@ -258,6 +348,15 @@ class StoryPollController extends ChangeNotifier { bool _held = false; bool _disposed = false; + StoryPollPlace get _place => + (shopId: shopId, did: did, storyId: storyId, slideId: slideId); + + /// Тексты с учётом `labels` опроса — языка устройства или [language]. + StoryPollTexts textsFor([String? language]) => + hostTexts.forPoll(poll, language: language); + + StoryPollTexts get texts => textsFor(); + StoryPollAnswer? get answer => _answer; StoryPollResults? get results => _results; bool get answered => _answered; @@ -273,25 +372,46 @@ class StoryPollController extends ChangeNotifier { num? get rateValue => _answered ? _answer?.rate : _rate; String get text => _text; - /// На карточке поле ввода (форма текстового опроса). - bool get showsField => !_answered && poll.kind == StoryMiniPollKind.text; + /// Вопрос полосы отвеченной оценки, пока к ней нет комментария; иначе `null`. + String? get followUp { + if (!_answered || !poll.pollType.isScale) return null; + final answer = _answer; + if (answer == null || answer.rate == null) return null; + if ((answer.comment ?? '').isNotEmpty) return null; + return storyPollBandQuestion(poll, answer.rate); + } + + /// На карточке поле ввода: форма текстового опроса или вопрос полосы шкалы. + bool get showsField => + (!_answered && poll.kind == StoryMiniPollKind.text) || followUp != null; + + /// Предел длины поля: `max_length` текстового опроса, у комментария — 5000. + int? get fieldLimit => + followUp != null ? storyPollCommentMaxLength : poll.maxLength; /// Кнопка отправки доступна. - bool get canSubmit => - !_sending && - switch (poll.kind) { - StoryMiniPollKind.multipleChoice => _selected.isNotEmpty, - StoryMiniPollKind.text => _text.trim().isNotEmpty, - _ => false, - }; + bool get canSubmit { + if (_sending) return false; + if (followUp != null) return _text.trim().isNotEmpty; + return switch (poll.kind) { + StoryMiniPollKind.multipleChoice => _selected.isNotEmpty, + StoryMiniPollKind.text => _text.trim().isNotEmpty, + _ => false, + }; + } /// Слайд держится. bool get holding => _held; - Set get _previousIds => {...?_answer?.optionIds}; + void _show(StoryPollState state) { + _answer = state.answer; + _results = state.results; + _answered = _store.sentOf(poll) || (_answer?.isAnswered ?? false); + _resetForm(); + } void _resetForm() { - final previous = _previousIds; + final previous = {...?_answer?.optionIds}; _selected = { for (final option in poll.options) if (previous.contains(option.id)) option.id, @@ -341,6 +461,7 @@ class StoryPollController extends ChangeNotifier { /// Выбор нескольких: отметить или снять вариант [id]. void toggle(int id) { if (_answered || _sending || _disposed) return; + _touched = true; _selected = {..._selected}; if (!_selected.remove(id)) _selected.add(id); notifyListeners(); @@ -369,6 +490,7 @@ class StoryPollController extends ChangeNotifier { /// Текст поля поменялся. set text(String value) { if (_text == value || _disposed) return; + _touched = true; _text = value; notifyListeners(); } @@ -386,22 +508,49 @@ class StoryPollController extends ChangeNotifier { ); } - /// Шкала: оценка [value] сразу подсвечена и отправлена. + /// Шкала: оценка [value] сразу подсвечена и отправлена — без комментария. void rate(int value) { if (_answered || _sending || _disposed || !poll.pollType.isScale) return; final previous = _rate; _rate = value; _send( - () => transport.review(poll.pollType, storyPollReviewBody(poll, value)), + () => transport.review( + poll.pollType, + storyPollReviewBody(poll, value, storyId: storyId, slideId: slideId), + ), sent: StoryPollAnswer(rate: value), scale: true, rollback: () => _rate = previous, ); } + /// Вопрос полосы: та же оценка ещё раз — с комментарием из поля без пробелов по краям. + void submitComment() { + final rate = _answer?.rate; + final value = _text.trim(); + if (followUp == null || rate == null || value.isEmpty || !canSubmit) { + return; + } + _send( + () => transport.review( + poll.pollType, + storyPollReviewBody( + poll, + rate, + comment: value, + storyId: storyId, + slideId: slideId, + ), + ), + sent: StoryPollAnswer(rate: rate, comment: value), + scale: true, + ); + } + /// «Ответить заново»: снова форма с прежним ответом. void reanswer() { if (!_answered || !poll.allowReanswer || _sending || _disposed) return; + _touched = true; _answered = false; _failed = false; _resetForm(); @@ -414,21 +563,23 @@ class StoryPollController extends ChangeNotifier { bool scale = false, VoidCallback? rollback, }) async { + _touched = true; _sending = true; _failed = false; _changed(); try { final reply = await request(); - // У шкалы ответ — сама оценка, итогов нет. + // У шкалы ответ — сама оценка (и комментарий), итогов нет. final StoryPollState state = scale ? (answer: sent, results: null) : (answer: reply.answer ?? sent, results: reply.results); - _store.write(shopId, poll, state); + _store.write(poll, _place, state); if (_disposed) return; _answer = state.answer; _results = state.results; _answered = true; _sending = false; + _text = ''; _changed(); } catch (_) { // Лог ошибки — забота транспорта. diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index 30528bb..2937c7b 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -78,6 +78,7 @@ class StorySlideView extends StatelessWidget { this.pollsTransport, this.pollTexts = const StoryPollTexts(), this.pollShopId = '', + this.pollDid = '', this.onPollHold, }); @@ -125,8 +126,9 @@ class StorySlideView extends StatelessWidget { /// Тексты карточки опроса от хоста. final StoryPollTexts pollTexts; - /// Магазин — ключ хранилища ответов опросов сессии. + /// Магазин и устройство (`did`) — ключ сохранённых ответов опросов. final String pollShopId; + final String pollDid; /// Опрос держит слайд (`true`) или отпускает. final ValueChanged? onPollHold; @@ -643,6 +645,7 @@ class StorySlideView extends StatelessWidget { slideId: slide.id, transport: transport, shopId: pollShopId, + did: pollDid, texts: pollTexts, live: live, onHold: onPollHold, @@ -684,10 +687,12 @@ class StorySlideView extends StatelessWidget { /// слайда (зажато 0…100, не число — 0), потом сдвиг, чтобы блок целиком был между [top] /// и местом нижних кнопок [bottom]; выше этого места — от его верха. /// -/// Карточка опроса ([poll]) — по центру, шириной [PersonalizationStoryPoll.widthFor]; -/// не влезает — ниже высотой, прокрутка внутри. Клавиатура перекрывает слайд снизу на -/// [keyboard] — карточка поднимается над ней на 16. Текстовый блок — во всю ширину с -/// полями 16, своей высоты. +/// Карточка опроса ([poll]) — как в вебе: по центру, шириной +/// [PersonalizationStoryPoll.widthFor], верх на [yOffset]%, а не влезает — поднимается, +/// чтобы низ был на 16 выше низа слайда, но не выше его верха; шапку и нижние кнопки +/// она может накрыть. Выше слайда — ниже высотой, прокрутка внутри. Клавиатура +/// перекрывает слайд снизу на [keyboard] — карточка поднимается над ней на 16. +/// Текстовый блок — во всю ширину с полями 16, своей высоты. /// /// Раскладка — в области SafeArea: [above] и [below] — отступы её от краёв слайда. class _SlideBlockLayout extends SingleChildLayoutDelegate { @@ -711,16 +716,22 @@ class _SlideBlockLayout extends SingleChildLayoutDelegate { static const double _aboveKeyboard = 16; + /// Зазор карточки опроса до низа слайда. + static const double _pollMargin = 16; + /// Поля текстового блока слева и справа. static const double _textEdge = 16; + /// Выше этого верх блока не поднимается: у опроса — верх слайда. + double get _top => poll ? 0 : top; + /// Ниже этого низ блока не опускается. double _limit(Size size) { - var limit = size.height - bottom; + var limit = poll ? size.height - _pollMargin : size.height - bottom; if (keyboard > 0) { limit = math.min(limit, size.height - keyboard - _aboveKeyboard); } - return math.max(top, limit); + return math.max(_top, limit); } @override @@ -735,7 +746,7 @@ class _SlideBlockLayout extends SingleChildLayoutDelegate { return BoxConstraints( minWidth: width, maxWidth: width, - maxHeight: math.max(0, _limit(size) - top), + maxHeight: math.max(0, _limit(size) - _top), ); } @@ -744,7 +755,7 @@ class _SlideBlockLayout extends SingleChildLayoutDelegate { final slide = above + size.height + below; final percent = yOffset.isFinite ? yOffset.clamp(0, 100) : 0; final wanted = slide * percent / 100 - above; - final y = math.max(top, math.min(wanted, _limit(size) - childSize.height)); + final y = math.max(_top, math.min(wanted, _limit(size) - childSize.height)); return Offset((size.width - childSize.width) / 2, y); } diff --git a/lib/src/ui/widgets/stories_v3_scope.dart b/lib/src/ui/widgets/stories_v3_scope.dart index 436fee4..c769897 100644 --- a/lib/src/ui/widgets/stories_v3_scope.dart +++ b/lib/src/ui/widgets/stories_v3_scope.dart @@ -47,9 +47,7 @@ class StoriesV3Options { other.shareLabel == shareLabel && other.shareUrlTransform == shareUrlTransform && other.pollsTransport == pollsTransport && - other.pollTexts.reanswer == pollTexts.reanswer && - other.pollTexts.error == pollTexts.error && - other.pollTexts.submit == pollTexts.submit; + other.pollTexts == pollTexts; @override int get hashCode => Object.hash( @@ -57,9 +55,7 @@ class StoriesV3Options { shareLabel, shareUrlTransform, pollsTransport, - pollTexts.reanswer, - pollTexts.error, - pollTexts.submit, + pollTexts, ); } diff --git a/test/stories/stories_poll_response_test.dart b/test/stories/stories_poll_response_test.dart index 17dea81..bec84b4 100644 --- a/test/stories/stories_poll_response_test.dart +++ b/test/stories/stories_poll_response_test.dart @@ -129,6 +129,50 @@ void main() { expect(const StoryPollAnswer(text: ' ').isAnswered, isTrue); }); + test('a band question and a comment of the answer; JSON both ways', () { + final scale = _poll( + _slide(>[ + { + 'type': 'poll', + 'poll_type': 'csat', + 'poll': { + 'code': 'support', + 'bands': [ + { + 'from': 1, + 'to': 3, + 'question': 'Что не так?', + 'success': 'Жаль', + }, + {'from': 4, 'to': 5, 'question': null}, + ], + }, + 'answer': {'rate': 2, 'comment': 'Долго'}, + }, + ]), + )!; + expect(scale.bands.first.question, 'Что не так?'); + expect(scale.bands.last.question, isNull); + expect(scale.answer!.comment, 'Долго'); + expect(scale.answer!.toJson(), { + 'rate': 2, + 'comment': 'Долго', + }); + final answer = StoryPollAnswer.tryParse( + const StoryPollAnswer(id: 7, optionIds: [1, 2], text: 'a').toJson(), + )!; + expect((answer.id, answer.text), (7, 'a')); + expect(answer.optionIds, [1, 2]); + final results = StoryPollResults.tryParse( + const StoryPollResults( + total: 3, + options: <({int id, double percent})>[(id: 1, percent: 33.3)], + ).toJson(), + )!; + expect((results.total, results.percentOf(1)), (3, 33)); + expect(const StoryPollResults().toJson(), {'total': 0}); + }); + test('any numeric rate is an answer, a fractional one too', () { StoryPollAnswer? rate(Object? value) => StoryPollAnswer.tryParse({'rate': value}); diff --git a/test/ui/stories_poll_test.dart b/test/ui/stories_poll_test.dart index 1fed776..2b561db 100644 --- a/test/ui/stories_poll_test.dart +++ b/test/ui/stories_poll_test.dart @@ -1,8 +1,9 @@ import 'dart:async'; +import 'dart:convert'; import 'package:flutter/foundation.dart'; -import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:rees46_sdk/src/stories/stories_response.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_playback.dart'; @@ -106,6 +107,7 @@ void main() { late List holds; setUp(() { + SharedPreferences.setMockInitialValues({}); StoryPollStore.instance = StoryPollStore(); transport = _Transport(); holds = []; @@ -229,11 +231,7 @@ void main() { expect(poll.failed, isTrue, reason: 'the server rejects it'); poll.choose(2); await reply(1); - expect( - mount(_mini(StoryMiniPollKind.singleChoice, code: '')).answered, - isTrue, - reason: 'stored under the empty code', - ); + expect(poll.answered, isTrue, reason: 'the empty code is a code'); }, ); @@ -321,6 +319,125 @@ void main() { }); }); + group('follow-up question of a band', () { + const bands = [ + StoryPollBand( + from: 0, + to: 6, + question: ' Что пошло не так? ', + success: 'Спасибо, мы станем лучше', + ), + StoryPollBand(from: 7, to: 10, question: ' ', success: 'Спасибо!'), + ]; + + test( + 'the question, then the same rate with the comment, then success', + () async { + final poll = mount(_scale(StoryPollType.nps, bands: bands))..rate(3); + expect(poll.followUp, isNull, reason: 'not before the rate is sent'); + await reply(0); + expect(poll.followUp, 'Что пошло не так?'); + expect(poll.showsField, isTrue); + expect(poll.fieldLimit, storyPollCommentMaxLength); + expect(storyPollCommentMaxLength, 5000); + expect(poll.canSubmit, isFalse); + poll + ..text = ' Долго ' + ..submitComment(); + expect(transport.calls.last.$3, { + 'channel': 'stories', + 'category': 'delivery', + 'rate': 3, + 'comment': 'Долго', + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '101', + }); + expect(poll.sending, isTrue); + await reply(1); + expect(poll.answer!.rate, 3); + expect(poll.answer!.comment, 'Долго'); + expect(poll.followUp, isNull); + expect(poll.showsField, isFalse); + expect( + storyPollBandText(poll.poll, poll.answer!.rate), + 'Спасибо, мы станем лучше', + ); + }, + ); + + test('a blank question — success at once', () async { + final poll = mount(_scale(StoryPollType.nps, bands: bands))..rate(9); + await reply(0); + expect(poll.followUp, isNull); + expect(storyPollBandQuestion(poll.poll, 9), isNull); + }); + + test('an answer without a comment asks again on the next show', () { + final poll = mount( + _scale( + StoryPollType.nps, + bands: bands, + answer: const StoryPollAnswer(rate: 2), + ), + ); + expect(poll.answered, isTrue); + expect(poll.followUp, 'Что пошло не так?'); + expect( + mount( + _scale( + StoryPollType.nps, + bands: bands, + answer: const StoryPollAnswer(rate: 2, comment: 'Курьер'), + ), + ).followUp, + isNull, + ); + }); + + test( + 'a re-answer sends the new rate without a comment, asks again', + () async { + final poll = mount( + _scale( + StoryPollType.nps, + bands: bands, + allowReanswer: true, + answer: const StoryPollAnswer(rate: 2, comment: 'Курьер'), + ), + )..reanswer(); + expect(poll.followUp, isNull); + poll.rate(5); + expect(transport.calls.single.$3.containsKey('comment'), isFalse); + await reply(0); + expect(poll.followUp, 'Что пошло не так?'); + expect(poll.text, isEmpty); + }, + ); + + test('a failed comment keeps the field and the text', () async { + final poll = mount(_scale(StoryPollType.nps, bands: bands))..rate(1); + await reply(0); + poll + ..text = 'Долго' + ..submitComment(); + await fail(1); + expect(poll.failed, isTrue); + expect(poll.followUp, isNotNull); + expect(poll.text, 'Долго'); + }); + + test('the slide holds while the comment field is focused', () async { + final poll = mount(_scale(StoryPollType.nps, bands: bands))..rate(1); + await reply(0); + holds.clear(); + poll.focused = true; + expect(holds, [true]); + poll.focused = false; + expect(holds, [true, false]); + }); + }); + group('scales', () { test('NPS 0..10 sends the rate on tap with its category', () async { final poll = mount(_scale(StoryPollType.nps)); @@ -334,6 +451,9 @@ void main() { 'channel': 'stories', 'category': 'delivery', 'rate': 9, + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '101', }); await reply(0); expect(poll.answered, isTrue); @@ -362,6 +482,9 @@ void main() { 'channel': 'stories', 'campaign': 'delivery', 'rate': 1, + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '101', }); await reply(0); expect(storyPollBandText(csat.poll, csat.answer!.rate), 'Жаль'); @@ -373,6 +496,9 @@ void main() { 'channel': 'stories', 'campaign': 'delivery', 'rate': 7, + 'source_type': 'stories', + 'source_id': '5', + 'source_item_id': '101', }); }, ); @@ -440,36 +566,30 @@ void main() { expect(storyPollBandText(poll, null), isNull); }); - test('colours: NPS by groups, the rest by thirds', () { - Color nps(int value) => - storyPollScaleColor(StoryPollType.nps, value, 0, 10); + test('tones: NPS by groups, the rest by thirds', () { + const d = StoryPollScaleTone.danger; + const w = StoryPollScaleTone.warning; + const g = StoryPollScaleTone.success; expect( - [for (var i = 0; i <= 10; i++) nps(i)], - const [ - Color(0xFFFCA5A5), Color(0xFFFCA5A5), Color(0xFFFCA5A5), // - Color(0xFFFDBA74), Color(0xFFFDBA74), Color(0xFFFDBA74), // - Color(0xFFFCD34D), Color(0xFFFDE68A), Color(0xFFFDE68A), // - Color(0xFF86EFAC), Color(0xFF86EFAC), + [ + for (var i = 0; i <= 10; i++) + storyPollScaleTone(StoryPollType.nps, i, 0, 10), ], + [d, d, d, d, d, d, d, w, w, g, g], ); - Color csat(int value) => - storyPollScaleColor(StoryPollType.csat, value, 1, 5); expect( - [for (var i = 1; i <= 5; i++) csat(i)], - const [ - Color(0xFFFCA5A5), Color(0xFFFCA5A5), Color(0xFFFDE68A), // - Color(0xFF86EFAC), Color(0xFF86EFAC), + [ + for (var i = 1; i <= 5; i++) + storyPollScaleTone(StoryPollType.csat, i, 1, 5), ], + [d, d, w, g, g], ); expect( - storyPollScaleColor(StoryPollType.nps, 3, 1, 5), - const Color(0xFFFDE68A), + storyPollScaleTone(StoryPollType.nps, 3, 1, 5), + w, reason: 'NPS on its own range — by thirds', ); - expect( - storyPollScaleColor(StoryPollType.ces, 4, 4, 4), - const Color(0xFF86EFAC), - ); + expect(storyPollScaleTone(StoryPollType.ces, 4, 4, 4), g); }); test('a scale keeps only its rate, whatever the reply has', () async { @@ -641,7 +761,7 @@ void main() { }); group('texts', () { - test('labels of the element > texts of the host > defaults', () { + test('labels of the element > texts of the host > built-in', () { const host = StoryPollTexts( reanswer: 'Answer again', error: 'Ошибка', @@ -652,20 +772,41 @@ void main() { StoryMiniPollKind.singleChoice, labels: const StoryPollLabels(reanswer: 'Ещё раз'), ), + language: 'en', ); expect(texts.reanswer, 'Ещё раз'); expect(texts.error, 'Ошибка'); - expect(texts.submit, 'Send', reason: 'an empty host text — the default'); - final defaults = const StoryPollTexts().forPoll( + expect(texts.submit, 'Send', reason: 'an empty host text — built-in'); + final en = const StoryPollTexts().forPoll( + _scale(StoryPollType.nps), + language: 'de', + ); + expect(en, StoryPollTexts.en); + expect( + (en.reanswer, en.error, en.submit), + ('Answer again', 'Failed to send the answer. Please try again', 'Send'), + ); + final ru = const StoryPollTexts().forPoll( _scale(StoryPollType.nps), + language: 'ru', + ); + expect( + (ru.reanswer, ru.error, ru.submit), + ( + 'Ответить заново', + 'Не удалось отправить ответ. Попробуйте еще раз', + 'Отправить', + ), ); - expect(defaults.reanswer, 'Answer again'); - expect(defaults.error, 'Failed to send the answer. Please try again'); - expect(defaults.submit, 'Send'); expect( - mount(_mini(StoryMiniPollKind.text), texts: host).texts.error, + mount(_mini(StoryMiniPollKind.text), texts: host).textsFor('ru').error, 'Ошибка', ); + expect( + mount(_mini(StoryMiniPollKind.text), texts: host).textsFor('ru').submit, + 'Отправить', + reason: 'no untranslated fallback in a Russian UI', + ); }); test('labels: submit too; null or not an object — the host texts', () { @@ -699,126 +840,215 @@ void main() { ); } }); + }); - test('results texts by the language: ru for ru, English for the rest', () { - expect(StoryPollResultTexts.of('ru'), StoryPollResultTexts.ru); - for (final language in ['en', 'de', 'uk', '']) { - expect(StoryPollResultTexts.of(language), StoryPollResultTexts.en); - } - const ru = StoryPollResultTexts.ru; - const en = StoryPollResultTexts.en; + group('saved answers', () { + late DateTime now; + late StoryPollStore store; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + now = DateTime(2026, 11, 20); + store = StoryPollStore.instance = StoryPollStore(clock: () => now); + await store.load(); + }); + + const place = (shopId: 'shop', did: 'did-1', storyId: '5', slideId: '101'); + const key = + 'personalization.storiesPolls.shop.stories_poll_did-1_mini_poll_' + 'gift_recipient_5_101'; + + StoryPollController mountAt( + StoryPollElement poll, { + String did = 'did-1', + }) => StoryPollController( + poll: poll, + storyId: '5', + slideId: '101', + transport: transport, + shopId: 'shop', + did: did, + onHold: holds.add, + ); + + test('the key: did, kind, code, story and slide; no did — no key', () { + final poll = _mini(StoryMiniPollKind.singleChoice); + expect(StoryPollStore.keyOf(poll, place), key); expect( - (ru.results, ru.thanks, ru.counted), - ('Результаты', 'Спасибо!', 'Голос учтён'), + StoryPollStore.keyOf(_scale(StoryPollType.nps), ( + shopId: 'shop', + did: 'd', + storyId: '39', + slideId: '39_0', + )), + 'personalization.storiesPolls.shop.stories_poll_d_nps_delivery_39_39_0', ); expect( - (en.results, en.thanks, en.counted), - ('Results', 'Thank you!', 'Vote counted'), - ); - }); - - test('votes: Russian plural forms, English vote/votes, digit groups', () { - const ru = { - 1: '1 голос', - 2: '2 голоса', - 4: '4 голоса', - 5: '5 голосов', - 11: '11 голосов', - 12: '12 голосов', - 14: '14 голосов', - 21: '21 голос', - 22: '22 голоса', - 25: '25 голосов', - 101: '101 голос', - 111: '111 голосов', - 112: '112 голосов', - 122: '122 голоса', - 1000: '1 000 голосов', - 1248: '1 248 голосов', - 1000001: '1 000 001 голос', - }; - ru.forEach( - (count, text) => expect( - StoryPollResultTexts.ru.votes(count), - text, - reason: '$count', - ), - ); - const en = { - 1: '1 vote', - 2: '2 votes', - 11: '11 votes', - 21: '21 votes', - 999: '999 votes', - 1248: '1,248 votes', - 1234567: '1,234,567 votes', - }; - en.forEach( - (count, text) => expect( - StoryPollResultTexts.en.votes(count), - text, - reason: '$count', - ), + StoryPollStore.keyOf(poll, ( + shopId: 'shop', + did: '', + storyId: '5', + slideId: '101', + )), + isNull, ); }); - }); - group('session store', () { - test('a stored answer is answered even if it lights nothing', () { - StoryPollStore.instance.write( - 'shop', - _mini(StoryMiniPollKind.singleChoice), - (answer: const StoryPollAnswer(id: 77), results: null), + test('a sent answer is saved with its results and the time', () async { + mountAt(_mini(StoryMiniPollKind.singleChoice)).choose(2); + await reply( + 0, + const StoryPollReply( + answer: StoryPollAnswer(id: 77, optionIds: [2]), + results: _results, + ), ); - final poll = mount(_mini(StoryMiniPollKind.singleChoice)); - expect(poll.answered, isTrue); - expect(poll.answer!.optionIds, isNull); + final preferences = await SharedPreferences.getInstance(); + expect(jsonDecode(preferences.getString(key)!), { + 'answer': { + 'id': 77, + 'option_ids': [2], + }, + 'results': { + 'total': 120, + 'options': >[ + {'id': 1, 'percent': 40.0}, + {'id': 2, 'percent': 60.0}, + ], + }, + 'saved_at': now.millisecondsSinceEpoch, + }); + // A new feed without an answer — the saved one; another slide — none. + final again = mountAt(_mini(StoryMiniPollKind.singleChoice)); + expect(again.answered, isTrue); + expect(again.answer!.optionIds, [2]); + expect(again.results!.percentOf(2), 60); expect( - mount( - _mini(StoryMiniPollKind.singleChoice, answer: StoryPollAnswer(id: 1)), - shopId: 'other', + StoryPollController( + poll: _mini(StoryMiniPollKind.singleChoice), + storyId: '5', + slideId: '102', + transport: transport, + shopId: 'shop', + did: 'did-1', ).answered, isFalse, - reason: 'such an answer of the feed is no answer', + ); + expect( + mountAt(_mini(StoryMiniPollKind.singleChoice), did: 'did-2').answered, + isFalse, + reason: 'another device', ); }); + test('the answer of the feed wins over the saved one', () async { + SharedPreferences.setMockInitialValues({ + key: jsonEncode({ + 'answer': { + 'option_ids': [1], + }, + 'results': null, + 'saved_at': now.millisecondsSinceEpoch, + }), + }); + store = StoryPollStore.instance = StoryPollStore(clock: () => now); + await store.load(); + final feed = mountAt( + _mini(StoryMiniPollKind.singleChoice, answer: _answered), + ); + expect(feed.answer!.optionIds, [2]); + final saved = mountAt(_mini(StoryMiniPollKind.singleChoice)); + expect(saved.answer!.optionIds, [1]); + }); + test( - 'a sent answer is remembered by shop, kind and code over the feed', + 'after a send the element shows the sent answer, also over the feed', () async { - mount(_mini(StoryMiniPollKind.singleChoice)).choose(2); + final element = _mini( + StoryMiniPollKind.singleChoice, + allowReanswer: true, + answer: _answered, + ); + mountAt(element) + ..reanswer() + ..choose(3); await reply(0, const StoryPollReply(results: _results)); - final again = mount(_mini(StoryMiniPollKind.singleChoice)); - expect(again.answered, isTrue); - expect(again.answer!.optionIds, [2]); - expect(again.results!.percentOf(2), 60); + expect(mountAt(element).answer!.optionIds, [3]); + // A new feed with the answer — the feed's. expect( - mount( - _mini(StoryMiniPollKind.singleChoice), - shopId: 'other', - ).answered, - isFalse, + mountAt( + _mini(StoryMiniPollKind.singleChoice, answer: _answered), + ).answer!.optionIds, + [2], ); + }, + ); + + test( + 'without a did nothing is written, the element still shows it', + () async { + final element = _mini(StoryMiniPollKind.text); + mountAt(element, did: '') + ..text = 'Книга' + ..submitText(); + await reply(0); + final preferences = await SharedPreferences.getInstance(); + expect(preferences.getKeys(), isEmpty); + expect(mountAt(element, did: '').answer!.text, 'Книга'); expect( - mount(_mini(StoryMiniPollKind.singleChoice, code: 'other')).answered, + mountAt(_mini(StoryMiniPollKind.text), did: '').answered, isFalse, ); - // A re-answer replaces it, also over the answer of the feed. - final feed = mount( - _mini( - StoryMiniPollKind.singleChoice, - allowReanswer: true, - answer: _answered, - ), - ); - expect(feed.answer!.optionIds, [2]); + }, + ); + + test('90 days: older or undated records are deleted on read', () async { + Future withRecord(Object? savedAt) async { + SharedPreferences.setMockInitialValues({ + key: jsonEncode({ + 'answer': {'text': 'a'}, + 'saved_at': ?savedAt, + }), + }); + store = StoryPollStore.instance = StoryPollStore(clock: () => now); + await store.load(); + return mountAt(_mini(StoryMiniPollKind.text)); + } + + final fresh = now.subtract(const Duration(days: 90)); + expect((await withRecord(fresh.millisecondsSinceEpoch)).answered, isTrue); + expect( + (await withRecord(fresh.millisecondsSinceEpoch - 1)).answered, + isFalse, + ); + expect((await SharedPreferences.getInstance()).getKeys(), isEmpty); + expect((await withRecord(null)).answered, isFalse, reason: 'undated'); + expect((await SharedPreferences.getInstance()).getKeys(), isEmpty); + expect((await withRecord('1')).answered, isFalse); + }); + + test( + 'a store opened later shows the saved answer to a pristine card', + () async { + SharedPreferences.setMockInitialValues({ + key: jsonEncode({ + 'answer': {'text': 'a'}, + 'saved_at': now.millisecondsSinceEpoch, + }), + }); + StoryPollStore.instance = StoryPollStore(clock: () => now); + final poll = mountAt(_mini(StoryMiniPollKind.text)); + expect(poll.answered, isFalse); + await pumpEventQueue(); + expect(poll.answered, isTrue); + expect(poll.answer!.text, 'a'); }, ); test( 'a reply after the card is gone: only the store, no hold change', () async { - final poll = mount(_mini(StoryMiniPollKind.singleChoice)); + final poll = mountAt(_mini(StoryMiniPollKind.singleChoice)); var notified = 0; poll ..addListener(() => notified++) @@ -830,7 +1060,7 @@ void main() { await reply(0); expect(notified, 0); expect(holds, [true, false]); - expect(mount(_mini(StoryMiniPollKind.singleChoice)).answered, isTrue); + expect(mountAt(_mini(StoryMiniPollKind.singleChoice)).answered, isTrue); }, ); }); diff --git a/test/ui/stories_poll_widget_test.dart b/test/ui/stories_poll_widget_test.dart index 1598f6e..4cb6e2f 100644 --- a/test/ui/stories_poll_widget_test.dart +++ b/test/ui/stories_poll_widget_test.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; import 'package:rees46_sdk/src/ui/components/personalization_story_poll.dart'; @@ -137,6 +138,7 @@ void main() { late StreamController requests; setUp(() { + SharedPreferences.setMockInitialValues({}); StoryPollStore.instance = StoryPollStore(); transport = _Transport(); requests = StreamController.broadcast(); @@ -534,6 +536,9 @@ void main() { 'channel': 'stories', 'category': 'code_nps', 'rate': 9, + 'source_type': 'stories', + 'source_id': '1', + 'source_item_id': '39_0', }); transport.pending.single.complete(const StoryPollReply()); await _replied(tester); @@ -746,74 +751,58 @@ void main() { fields: {'thanks_text': thanks}, ); - testWidgets('an answered choice: the results header, my answer checked, ' - '«Thank you! Vote counted» and the votes', (tester) async { + testWidgets('an answered choice, as the web: my answer checked, ' + 'percents, then thanks_text only', (tester) async { await tester.pumpWidget(alone(answered())); await tester.pumpAndSettle(); - expect(find.text('RESULTS'), findsOneWidget); expect(find.text('A'), findsOneWidget); expect(find.text('B'), findsNothing, reason: 'a check instead'); expect(find.text('C'), findsOneWidget); - expect(find.text('Thank you! Vote counted'), findsOneWidget); - expect(find.text('1,248 votes'), findsOneWidget); - // The header is above the question, the votes on the right of the thanks. - final question = tester.getRect(find.text('Q mini_poll single_choice')); - expect( - tester.getRect(find.text('RESULTS')).bottom, - lessThan(question.top), - ); - expect( - tester.getRect(find.text('1,248 votes')).right, - tester.getRect(card).right - 20, - ); + expect(find.text('31%'), findsOneWidget); + expect(find.textContaining('RESULTS'), findsNothing); + expect(find.textContaining('Vote counted'), findsNothing); + expect(find.textContaining('vote'), findsNothing); - // Its own thanks replaces the pair; no total — no votes. - await tester.pumpWidget( - alone(answered(thanks: 'Спасибо за ответ!', total: 0)), - ); + await tester.pumpWidget(alone(answered(thanks: 'Спасибо за ответ!'))); await tester.pumpAndSettle(); expect(find.text('Спасибо за ответ!'), findsOneWidget); - expect(find.text('Thank you! Vote counted'), findsNothing); - expect(find.textContaining('vote'), findsNothing); + expect( + tester.getRect(find.text('Спасибо за ответ!')).top, + greaterThan(tester.getRect(find.text('31%')).bottom), + reason: 'below the rows', + ); await tester.pumpWidget(alone(answered(kind: 'multiple_choice'))); await tester.pumpAndSettle(); - expect(find.text('RESULTS'), findsOneWidget); + expect(find.text('31%'), findsOneWidget, reason: 'the same rows'); }); - testWidgets('the results texts follow the device language', (tester) async { + testWidgets('built-in texts follow the device language', (tester) async { tester.platformDispatcher.localeTestValue = const Locale('ru', 'RU'); addTearDown(tester.platformDispatcher.clearLocaleTestValue); - await tester.pumpWidget(alone(answered(total: 21))); - await tester.pumpAndSettle(); - expect(find.text('РЕЗУЛЬТАТЫ'), findsOneWidget); - expect(find.text('Спасибо! Голос учтён'), findsOneWidget); - expect(find.text('21 голос'), findsOneWidget); - }); - - testWidgets('no results header in a form, on a scale or a text', ( - tester, - ) async { - for (final json in >[ - _poll('mini_poll', kind: 'single_choice'), - _poll('mini_poll', kind: 'multiple_choice'), - _poll('nps', answer: {'rate': 9}), - _poll( - 'mini_poll', - kind: 'text', - answer: {'text': 'x'}, + await tester.pumpWidget( + alone( + _poll( + 'mini_poll', + kind: 'text', + fields: {'submit_label': ''}, + ), ), - ]) { - await tester.pumpWidget(alone(json)); - await tester.pumpAndSettle(); - expect(find.text('RESULTS'), findsNothing, reason: '$json'); - expect(find.textContaining('Vote counted'), findsNothing); - } - await tester.pumpWidget(alone(_poll('mini_poll', kind: 'single_choice'))); - expect( - ['A', 'B', 'C'].map((letter) => find.text(letter)), - everyElement(findsOneWidget), ); + expect(find.text('Отправить'), findsOneWidget); + await tester.pumpWidget( + alone( + _poll( + 'mini_poll', + kind: 'single_choice', + allowReanswer: true, + answer: { + 'option_ids': [2], + }, + ), + ), + ); + expect(find.text('Ответить заново'), findsOneWidget); }); testWidgets('sizes: left-aligned text, rows 56 and 8 apart, the track, ' @@ -921,11 +910,9 @@ void main() { expect(bar('Себе'), const Color(0x14000000)); }); - testWidgets('the scale: the chosen digit in a capsule of its band colour, ' - 'the accent without bands; the rest dimmed once answered', ( - tester, - ) async { - Color? capsule(String digit) { + testWidgets('the scale: digits in the kit tones, the chosen one filled; ' + 'the rest dimmed once answered', (tester) async { + Color? cell(String digit) { final decoration = tester .widget( @@ -949,11 +936,13 @@ void main() { ) .opacity; + const colors = PersonalizationColors.light; await tester.pumpWidget( alone(_poll('nps', answer: {'rate': 9})), ); - expect(capsule('9'), storyPollScaleColor(StoryPollType.nps, 9, 0, 10)); - expect(capsule('5'), isNull); + expect(cell('9'), const Color(0xFF22C55E), reason: 'green, filled'); + expect(cell('5'), colors.semanticDanger.withValues(alpha: 0.2)); + expect(cell('7'), colors.semanticWarning.withValues(alpha: 0.2)); expect((opacity('9'), opacity('5')), (1.0, 0.55)); expect( tester.widget(find.text('9')).style!.color, @@ -965,13 +954,72 @@ void main() { alone( _poll( 'csat', - answer: {'rate': 3}, + answer: {'rate': 1}, fields: {'bands': []}, ), ), ); - expect(capsule('3'), const Color(0xFF22C55E)); + expect(cell('1'), colors.semanticDanger, reason: 'tones without bands'); + }); + }); + + testWidgets('a band question after the rate: the comment with the same ' + 'rate, a counter to 5000, then success', (tester) async { + tester.platformDispatcher.localeTestValue = const Locale('ru', 'RU'); + addTearDown(tester.platformDispatcher.clearLocaleTestValue); + await open( + tester, + _stories(>>[ + >[ + _slide('1', >[ + _poll( + 'nps', + fields: { + 'bands': >[ + { + 'from': 0, + 'to': 10, + 'question': 'Что улучшить?', + 'success': 'Band thanks', + }, + ], + }, + ), + ]), + _slide('2'), + ], + ]), + ); + await tester.tap(find.descendant(of: card, matching: find.text('4'))); + await tester.pump(); + transport.pending.single.complete(const StoryPollReply()); + await _replied(tester); + expect(find.text('Что улучшить?'), findsOneWidget); + expect(find.byType(TextField), findsOneWidget); + expect(find.text('0/5000'), findsOneWidget); + expect(find.text('Отправить'), findsOneWidget, reason: 'localized'); + expect(find.text('Band thanks'), findsNothing); + await tester.enterText(find.byType(TextField), ' Быстрее '); + await tester.pump(); + expect(find.text('9/5000'), findsOneWidget); + // Focused: the slide waits. + await _wait(tester, const Duration(seconds: 12)); + expect(find.text('Slide 1'), findsOneWidget); + await tester.tap(find.text('Отправить')); + await tester.pump(); + expect(transport.bodies.last, { + 'channel': 'stories', + 'category': 'code_nps', + 'rate': 4, + 'comment': 'Быстрее', + 'source_type': 'stories', + 'source_id': '1', + 'source_item_id': '1', }); + transport.pending.last.complete(const StoryPollReply()); + await _replied(tester); + expect(find.text('Band thanks'), findsOneWidget); + expect(find.byType(TextField), findsNothing); }); testWidgets('text re-answer: an empty field in focus, the slide held', ( @@ -1039,13 +1087,24 @@ void main() { expect(find.text('Slide 2'), findsOneWidget); expect( tester.getRect(card).top, - greaterThan(50 + 16), - reason: 'moved under the header', + 50, + reason: + 'the top of the slide under the status bar, over the header, ' + 'as the web', + ); + // The close cross stays above the card and still closes. + await tester.pump(const Duration(milliseconds: 500)); + // The button around the icon takes the tap. + await tester.tap( + find.byKey(const ValueKey(PersonalizationIcons.cross)), + warnIfMissed: false, ); + await _settle(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); }); - testWidgets('y_offset: none, below 0 or not a number — right under the ' - 'header; over 100 — down to the bottom', (tester) async { + testWidgets('y_offset: none, below 0 or not a number — the top of the slide; ' + 'over 100 — 16 above its bottom, as the web', (tester) async { final offsets = [0, null, -20, 'NaN', 100, 150]; await open( tester, @@ -1068,7 +1127,7 @@ void main() { expect(find.text('Slide ${offsets[index]}'), findsOneWidget); rects.add(tester.getRect(card)); } - expect(rects.first.top, greaterThan(16), reason: 'under the header'); + expect(rects.first.top, 0, reason: 'the top of the slide'); expect( rects.sublist(1, 4).map((rect) => rect.top), everyElement(rects.first.top), @@ -1194,6 +1253,35 @@ void main() { await closeViewer(tester); }); + testWidgets('the answer is saved on the device by did and shown by a ' + 'new feed without one', (tester) async { + SharedPreferences.setMockInitialValues({}); + await StoryPollStore.instance.load(); + await openBlock(tester, apiV3Domain: 'app.example', own: false); + await tester.tap(find.text('Маме')); + for (var i = 0; i < 5; i++) { + await tester.pump(); + } + final preferences = await SharedPreferences.getInstance(); + const key = + 'personalization.storiesPolls.shop.stories_poll_did-1_mini_poll_' + 'code_mini_pollsingle_choice_1_1'; + expect(preferences.getKeys(), {key}); + expect( + (jsonDecode(preferences.getString(key)!) as Map)['answer'], + { + 'option_ids': [2], + }, + ); + await closeViewer(tester); + // A new block loads a new feed without an answer: the saved one is shown. + StoriesSeenStore.instance = StoriesSeenStore(); + await openBlock(tester, apiV3Domain: 'app.example', own: false); + expect(find.text('Slide 1'), findsOneWidget); + expect(find.text('Спасибо!'), findsOneWidget); + await closeViewer(tester); + }); + testWidgets('without its own transport — HTTP to the host of the block', ( tester, ) async { diff --git a/test/ui/stories_text_block_position_test.dart b/test/ui/stories_text_block_position_test.dart index 43b237c..f793a2c 100644 --- a/test/ui/stories_text_block_position_test.dart +++ b/test/ui/stories_text_block_position_test.dart @@ -161,7 +161,9 @@ void main() { testWidgets('a text block and a poll with one y_offset stand at one height', ( tester, ) async { - for (final offset in [5, 30, 50]) { + // Near the top they part: the card goes up to the top of the slide, as the web, + // the text block stays under the header. + for (final offset in [30, 50]) { await _open( tester, _stories(>[_text('text', offset), _poll(offset)]), From 38f8ef4302f2c6104614d189124e260c29f56a7f Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 20 Nov 2026 12:26:02 +0400 Subject: [PATCH 03/24] feat(stories): stories over API v3 behave as the web SDK does: a story opens at the feed's start_position and where it was left in the session, it is viewed by the feed's viewed or once left forward; media is decided by the slide type and a slide without media takes its background_color; a header is drawn with the kit's type and its tap sends click and opens its link; a text block without font_size takes the kit's body size, text_italic and monospace are read; a button without a link only sends click; copying a promo code sends no click; Share hands over the slide's link or the story's as it is, without r46_slide. The old feed keeps the kit's rules --- lib/src/stories/stories_header_v3.dart | 47 ++ lib/src/stories/stories_response.dart | 35 +- lib/src/stories/stories_share_v3.dart | 3 +- .../ui/widgets/personalization_stories.dart | 27 +- .../widgets/personalization_stories_v3.dart | 8 + .../widgets/personalization_story_viewer.dart | 43 +- lib/src/ui/widgets/stories_playback.dart | 47 ++ lib/src/ui/widgets/stories_share.dart | 45 +- lib/src/ui/widgets/stories_slide_view.dart | 137 ++++- lib/src/ui/widgets/stories_support.dart | 66 +- lib/src/v3/personalization_v3.dart | 4 +- test/stories/stories_response_test.dart | 7 +- test/ui/stories_poll_widget_test.dart | 7 +- test/ui/stories_share_test.dart | 57 +- test/ui/stories_share_widget_test.dart | 10 +- test/ui/stories_v3_rules_test.dart | 562 ++++++++++++++++++ test/v3_gate_test.dart | 2 + 17 files changed, 964 insertions(+), 143 deletions(-) create mode 100644 lib/src/stories/stories_header_v3.dart create mode 100644 test/ui/stories_v3_rules_test.dart diff --git a/lib/src/stories/stories_header_v3.dart b/lib/src/stories/stories_header_v3.dart new file mode 100644 index 0000000..50413a6 --- /dev/null +++ b/lib/src/stories/stories_header_v3.dart @@ -0,0 +1,47 @@ +part of 'stories_response.dart'; + +/// `header` of a slide (API v3): the icon, the title and the subtitle of the shop or the +/// campaign over the slide, with a link. Behind the v3 gate (`src/v3/personalization_v3.dart`), +/// not the kit's; the old feed draws none. +class StoryHeaderElement extends StoryElement { + const StoryHeaderElement({ + this.icon = '', + this.title = '', + this.subtitle = '', + this.link = '', + this.linkAndroid = '', + this.linkIos = '', + }); + + /// Icon URL; empty when not sent. + final String icon; + final String title; + final String subtitle; + + /// Where a tap leads; the platform's own link wins over it, as with buttons. + final String link; + final String linkAndroid; + final String linkIos; + + /// The header shows something: an icon, a title or a subtitle. + bool get isNotEmpty => + icon.trim().isNotEmpty || + title.trim().isNotEmpty || + subtitle.trim().isNotEmpty; + + factory StoryHeaderElement.fromJson(Map json) => + StoryHeaderElement( + icon: _text(json['icon']), + title: _text(json['title']), + subtitle: _text(json['subtitle']), + link: _text(json['link']), + linkAndroid: _text(json['link_android']), + linkIos: _text(json['link_ios']), + ); +} + +/// Text blocks over API v3. Behind the v3 gate, not the kit's. +extension StoryTextBlockV3 on StoryTextBlockElement { + /// The server sent `font_size`; without it API v3 takes the kit's body text size. + bool get hasFontSize => _hasFontSize; +} diff --git a/lib/src/stories/stories_response.dart b/lib/src/stories/stories_response.dart index 53ae60b..9f78939 100644 --- a/lib/src/stories/stories_response.dart +++ b/lib/src/stories/stories_response.dart @@ -4,6 +4,7 @@ import '../json_number.dart'; part 'stories_poll.dart'; part 'stories_share_v3.dart'; +part 'stories_header_v3.dart'; // The `payload` of API v3 (`/api/v3/storefront/stories/{code}`) has the same keys and // is parsed here too. @@ -182,8 +183,8 @@ class StorySlide { } } -/// An element placed on a slide. Unknown types and `header` (not drawn by the kit) are -/// dropped while parsing, and so is a `poll` of a kind the kit does not draw. +/// An element placed on a slide. Unknown types are dropped while parsing, and so is a +/// `poll` of a kind the kit does not draw. sealed class StoryElement { const StoryElement(); @@ -195,6 +196,7 @@ sealed class StoryElement { 'products' => StoryProductsElement.fromJson(json), 'text_block' => StoryTextBlockElement.fromJson(json), 'poll' => StoryPollElement.tryParse(json), + 'header' => StoryHeaderElement.fromJson(json), _ => null, }; } @@ -287,7 +289,7 @@ class StoryTextBlockElement extends StoryElement { /// Font size in logical pixels; 14 when not set, as in the native SDKs. final double fontSize; - /// `serif`, `sans-serif`, `monospaced` or empty. + /// `serif`, `sans-serif`, `monospace` (or `monospaced`) or empty. final String fontType; final bool bold; final bool italic; @@ -315,6 +317,9 @@ class StoryTextBlockElement extends StoryElement { static const double defaultFontSize = 14; + // The server sent `font_size`: behind the v3 gate, read through [StoryTextBlockV3]. + final bool _hasFontSize; + const StoryTextBlockElement({ required this.text, this.fontSize = defaultFontSize, @@ -328,16 +333,34 @@ class StoryTextBlockElement extends StoryElement { this.lineSpacing = 0, this.yOffset = 0, this.promocode, + }) : _hasFontSize = true; + + const StoryTextBlockElement._json( + this._hasFontSize, { + required this.text, + required this.fontSize, + required this.fontType, + required this.bold, + required this.italic, + required this.textAlign, + required this.textColor, + required this.backgroundColor, + required this.backgroundOpacity, + required this.lineSpacing, + required this.yOffset, + required this.promocode, }); factory StoryTextBlockElement.fromJson(Map json) { final promocode = json['promocode']; - return StoryTextBlockElement( + final fontSize = toDoubleOrNull(json['font_size']); + return StoryTextBlockElement._json( + fontSize != null, text: json['text_input'] as String? ?? '', - fontSize: toDoubleOrNull(json['font_size']) ?? defaultFontSize, + fontSize: fontSize ?? defaultFontSize, fontType: json['font_type'] as String? ?? '', bold: json['bold'] == true || json['text_bold'] == true, - italic: json['italic'] == true, + italic: json['italic'] == true || json['text_italic'] == true, textAlign: json['text_align'] as String? ?? '', textColor: json['text_color'] as String? ?? '', backgroundColor: json['text_background_color'] as String? ?? '', diff --git a/lib/src/stories/stories_share_v3.dart b/lib/src/stories/stories_share_v3.dart index 8fe9c89..7b759e4 100644 --- a/lib/src/stories/stories_share_v3.dart +++ b/lib/src/stories/stories_share_v3.dart @@ -8,8 +8,7 @@ extension StoryShareV3 on Story { bool get shareable => _shareable; /// "Share" link of the campaign (`share_url`, API v3); empty when not sent. Product - /// campaigns have only this one, their slides have none: a slide shares it with its - /// id in `r46_slide`. + /// campaigns have only this one, their slides have none: they share it as it is. String get shareUrl => _shareUrl; } diff --git a/lib/src/ui/widgets/personalization_stories.dart b/lib/src/ui/widgets/personalization_stories.dart index a5e0825..1b50981 100644 --- a/lib/src/ui/widgets/personalization_stories.dart +++ b/lib/src/ui/widgets/personalization_stories.dart @@ -669,6 +669,9 @@ class _PersonalizationStoriesState extends State { ); } finally { _presenting = false; + // Кольца — по тому, чем просмотр кончился (у новой ленты сторис просмотрена, когда + // её досмотрели). + if (mounted) setState(() {}); } } @@ -681,11 +684,14 @@ class _PersonalizationStoriesState extends State { final sdk = _sdk; if (stories.isEmpty || sdk == null) return const SizedBox.shrink(); final seen = StoriesSeenStore.instance.seen(sdk); + final server = StoriesApiV3.host(_v3?.apiV3Domain) != null; return PersonalizationStoriesBar( padding: widget.padding, items: [ for (final story in stories) - _item(story, seen[story.id] ?? const {}), + server + ? _serverItem(story) + : _item(story, seen[story.id] ?? const {}), ], onItemTap: (item) => _open(stories.indexWhere((story) => story.id == item.id)), @@ -693,6 +699,25 @@ class _PersonalizationStoriesState extends State { ); } + /// Сторис новой ленты: просмотрена, как в вебе, по `viewed` сервера или когда с неё + /// ушли вперёд; дуги горят до слайда, с которого она откроется. + PersonalizationStoryItem _serverItem(Story story) { + final viewed = StoriesServerProgress.viewedOf(story); + final start = StoriesServerProgress.startOf(story); + return PersonalizationStoryItem( + id: story.id, + label: story.name, + image: storyImage(story.avatar, widget.imageProvider), + pinned: story.pinned, + viewed: viewed, + segments: story.slides.length, + seenSegments: { + for (var i = 0; i < story.slides.length; i++) + if (viewed || i < start) i, + }, + ); + } + PersonalizationStoryItem _item(Story story, Set seen) => PersonalizationStoryItem( id: story.id, diff --git a/lib/src/ui/widgets/personalization_stories_v3.dart b/lib/src/ui/widgets/personalization_stories_v3.dart index 9e88143..e690c23 100644 --- a/lib/src/ui/widgets/personalization_stories_v3.dart +++ b/lib/src/ui/widgets/personalization_stories_v3.dart @@ -14,6 +14,14 @@ part of 'personalization_stories.dart'; /// Сменился хост — блок грузится заново. Открыт один просмотр V2 из блока, `show` или /// [handleLink]: ссылка закрывает прежний перед показом своего. /// +/// Сторис с API v3 ведут себя, как в веб-SDK: открываются со слайда `start_position` +/// сервера (за сессию — где остановились), просмотренной сторис становится по `viewed` +/// сервера или когда с неё ушли вперёд; медиа решает тип слайда, слайд без медиа — цвета +/// `background_color`; шапка `header` рисуется, её нажатие — `click` и её ссылка; кнопка +/// без ссылки — только `click`; копирование промокода `click` не шлёт; кнопка звука — +/// только у видео со звуком, выбор звука помнится на устройстве; «Поделиться» отдаёт +/// ссылку слайда, без неё — ссылку кампании как есть. +/// /// Опросы слайдов — тоже только с API v3: ответы уходят на хост блока, а /// [pollsTransport] их подменяет (тесты, офлайн-демо). Просмотр под /// [PersonalizationStoriesV3] со своим [pollsTransport] рисует опросы и без API v3. Ответ diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index fc8a925..bb5f3a9 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -213,6 +213,10 @@ class _PersonalizationStoryViewerState extends State initialStory: widget.initialStory, initialSlide: widget.initialSlide, seen: _initialSeen(), + // Новая лента — стартовый слайд и просмотренность по серверу, как в вебе. Режим — + // без подписки: создаётся до didChangeDependencies. + serverStart: + StoriesApiV3.host(StoriesV3Scope.peek(context)?.apiV3Domain) != null, ); late final PageController _pages = PageController( initialPage: _playback.storyIndex, @@ -481,7 +485,10 @@ class _PersonalizationStoryViewerState extends State _load(generation); final sdk = widget.sdk; if (sdk != null) { - StoriesSeenStore.instance.mark(sdk, story.id, slide.id); + // Новой ленте просмотренное устройства не нужно: её ведёт сервер. + if (!_playback.serverStart) { + StoriesSeenStore.instance.mark(sdk, story.id, slide.id); + } if (_v3Code != null) { _trackV3(StoriesV3Event.view, story, slide); } else if (storyTrackableId(story.id) && storyTrackableId(slide.id)) { @@ -523,6 +530,12 @@ class _PersonalizationStoryViewerState extends State // Хост API v3 просмотра: режима над ним, без него — глобальный; `null` — старый API. String? get _v3Host => StoriesApiV3.host(_v3?.apiV3Domain); + // Сторис новой ленты: правила веба — медиа по типу слайда, кнопка без ссылки ничего не + // открывает, копирование промокода без `click`, шапка `header`. + bool get _byType => _v3Host != null; + + StoryMedia _mediaOf(StorySlide slide) => storyMediaOf(slide, byType: _byType); + // Код блока для событий v3: у просмотра есть хост API v3, SDK и код; иначе `null` — // старый трекинг через мост. String? get _v3Code { @@ -607,7 +620,9 @@ class _PersonalizationStoryViewerState extends State _disposeGif(); _sync(); final slide = _playback.slide; - switch (storyMediaOf(slide)) { + // Новая лента решает медиа по типу: у слайда без адреса грузить нечего. + if (slide.background.trim().isEmpty) return _ready(generation); + switch (_mediaOf(slide)) { case StoryMedia.none: _ready(generation); case StoryMedia.image: @@ -715,7 +730,7 @@ class _PersonalizationStoryViewerState extends State _timeout?.cancel(); _playback.mediaFailed(generation); _sync(); - if (storyMediaOf(_playback.slide) == StoryMedia.video) { + if (_mediaOf(_playback.slide) == StoryMedia.video) { // Видео повторяет загрузку и само. _autoRetry?.cancel(); _autoRetry = _timer(_videoRetry, _retry); @@ -725,7 +740,7 @@ class _PersonalizationStoryViewerState extends State void _retry() { final slide = _playback.slide; - if (storyMediaOf(slide) == StoryMedia.image) { + if (_mediaOf(slide) == StoryMedia.image) { storyImage(slide.background, widget.imageProvider)?.evict(); StoriesImageBytes.instance.evict(slide.background); } @@ -778,7 +793,8 @@ class _PersonalizationStoryViewerState extends State } else { return; } - switch (storyMediaOf(next)) { + if (next.background.trim().isEmpty) return; + switch (_mediaOf(next)) { case StoryMedia.none: break; case StoryMedia.image: @@ -818,13 +834,21 @@ class _PersonalizationStoryViewerState extends State } /// Кнопка слайда: своя ссылка, у товарного слайда без неё — товар. Кнопка без ссылки на - /// медиа-слайде — только `click`: просмотр остаётся открытым. + /// медиа-слайде — только `click`: просмотр остаётся открытым. У новой ленты, как в + /// вебе, кнопка без ссылки — только `click` и на товарном слайде. void _button(StoryButtonElement button) { _clicked(); final product = storyProductElement(_playback.slide)?.item; final own = storyButtonLink(button); if (own.isNotEmpty) return _closeThen(() => _openLink(own)); - if (product != null) _closeThen(() => _goTo(product)); + if (product != null && !_byType) _closeThen(() => _goTo(product)); + } + + /// Шапка слайда новой ленты: `click`, потом её ссылка, если она есть. + void _header(StoryHeaderElement header) { + _clicked(); + final link = storyHeaderLink(header); + if (link.isNotEmpty) _closeThen(() => _openLink(link)); } void _product(StoryProduct product) { @@ -832,8 +856,9 @@ class _PersonalizationStoryViewerState extends State _closeThen(() => _goTo(product)); } + /// Промокод скопирован: хосту; старая лента ещё и шлёт `click`, новая, как веб, — нет. void _promo(String code) { - _clicked(); + if (!_byType) _clicked(); widget.onPromoCopied?.call(code); } @@ -966,6 +991,8 @@ class _PersonalizationStoryViewerState extends State onPollHold: (held) { if (mounted) _setPaused(StoriesPauseReason.poll, held); }, + v3: _byType, + onHeader: _header, ); } } diff --git a/lib/src/ui/widgets/stories_playback.dart b/lib/src/ui/widgets/stories_playback.dart index 96eccca..6ecb38b 100644 --- a/lib/src/ui/widgets/stories_playback.dart +++ b/lib/src/ui/widgets/stories_playback.dart @@ -56,6 +56,37 @@ enum StoriesStep { close, } +/// Сторис новой ленты за жизнь её объектов в процессе — как в вебе: с какого слайда +/// открыть (`start_position` сервера, дальше — где остановились) и ушли ли с неё вперёд +/// (тогда она просмотрена, как при `viewed` сервера). Новая лента — новые объекты сторис +/// и снова то, что считает сервер. +abstract final class StoriesServerProgress { + static final Expando _positions = Expando('storiesPosition'); + static final Expando _left = Expando('storiesLeftForward'); + + /// С какого слайда открыть [story]: где остановились, иначе `start_position`. + static int startOf(Story story) { + if (story.slides.isEmpty) return 0; + return (_positions[story] ?? story.startPosition).clamp( + 0, + story.slides.length - 1, + ); + } + + /// Сторис просмотрена: так говорит сервер или с неё ушли вперёд. + static bool viewedOf(Story story) => story.viewed || (_left[story] ?? false); + + /// Показан слайд [slide] сторис [story]. + static void showed(Story story, int slide) => _positions[story] = slide; + + /// С [story] ушли вперёд: просмотрена; [finished] — досмотрели до конца, в следующий + /// раз — с начала. + static void leftForward(Story story, {bool finished = false}) { + _left[story] = true; + if (finished) _positions[story] = 0; + } +} + /// Логика просмотра сторис без UI: какая сторис и какой слайд текущие, с какого слайда /// открывать сторис, почему слайд стоит, открыта ли шторка, сколько прошло времени. /// @@ -74,6 +105,11 @@ enum StoriesStep { /// - время слайда копится только из реально прошедших промежутков и только пока ничто /// его не держит — от масштаба анимаций системы оно не зависит. /// +/// Новая лента ([serverStart]), как в вебе: сторис открывается со слайда +/// [StoriesServerProgress.startOf], просмотренной становится, когда с неё ушли вперёд +/// (досмотрели последний слайд или перелистнули на следующую); просмотренное устройства не +/// решает. +/// /// Сторис без слайдов отбрасываются при создании. class StoriesPlayback { /// [initialSlide] — слайд начальной сторис в обход правил стартового слайда (ссылка @@ -83,6 +119,7 @@ class StoriesPlayback { int initialStory = 0, int? initialSlide, Map> seen = const >{}, + this.serverStart = false, }) : stories = List.unmodifiable( stories.where((story) => story.slides.isNotEmpty), ), @@ -101,6 +138,9 @@ class StoriesPlayback { /// Сторис со слайдами в порядке ленты. final List stories; + /// Новая лента: стартовый слайд и просмотренность — [StoriesServerProgress]. + final bool serverStart; + final Map> _seen; final Set _reasons = {}; late int _story; @@ -188,6 +228,7 @@ class StoriesPlayback { if (initial != null && index == _story && !_entered) { return initial.clamp(0, story.slides.length - 1); } + if (serverStart) return StoriesServerProgress.startOf(story); return startSlideOf(story, _seen[story.id] ?? const {}); } @@ -200,6 +241,10 @@ class StoriesPlayback { if (stories.isEmpty) return false; final target = index.clamp(0, stories.length - 1); if (_entered && target == _story) return false; + // Перелистнули вперёд — с прежней ушли вперёд. + if (serverStart && _entered && target > _story) { + StoriesServerProgress.leftForward(story); + } _story = target; _slide = startSlideFor(target); _initialSlide = null; @@ -215,6 +260,7 @@ class StoriesPlayback { _enter(); return StoriesStep.slide; } + if (serverStart) StoriesServerProgress.leftForward(story, finished: true); if (_story < stories.length - 1) { _turnTo(_story + 1); return StoriesStep.turn; @@ -357,6 +403,7 @@ class StoriesPlayback { ..remove(StoriesPauseReason.poll) ..add(StoriesPauseReason.loading); (_seen[story.id] ??= {}).add(slide.id); + if (serverStart) StoriesServerProgress.showed(story, _slide); } } diff --git a/lib/src/ui/widgets/stories_share.dart b/lib/src/ui/widgets/stories_share.dart index aafa212..deecba4 100644 --- a/lib/src/ui/widgets/stories_share.dart +++ b/lib/src/ui/widgets/stories_share.dart @@ -83,46 +83,13 @@ StoriesShareLink? parseStoriesShareLink(String url) { ); } -/// Ссылка «Поделиться» слайда [slide] кампании [story]: кампания запрещает делиться -/// (`shareable: false`) — нет; иначе своя ссылка слайда, без неё — ссылка кампании с id -/// слайда в `r46_slide` ([storyCampaignSlideUrl]). У слайдов товарных кампаний (`39_2`) -/// своих ссылок нет, и без id слайда ссылка открыла бы кампанию не с того слайда, -/// которым поделились. Только `http://` и `https://`; иначе нет. Нет ссылки — нет и -/// кнопки на слайде. +/// Ссылка «Поделиться» слайда [slide] кампании [story], как `slideShareUrl` веба: +/// кампания запрещает делиться (`shareable: false`) — нет; иначе своя ссылка слайда, без +/// неё — ссылка кампании как есть (у слайдов товарных кампаний своих ссылок нет — они +/// делятся ссылкой кампании, и она открывает кампанию с её `start_position`). Только +/// `http://` и `https://`; иначе нет. Нет ссылки — нет и кнопки на слайде. String? storySlideShareUrl(Story story, StorySlide slide) { if (!story.shareable) return null; - final url = slide.shareUrl.isNotEmpty - ? slide.shareUrl - : storyCampaignSlideUrl(story.shareUrl, slide.id); + final url = slide.shareUrl.isNotEmpty ? slide.shareUrl : story.shareUrl; return _httpLink.hasMatch(url) ? url : null; } - -/// Ссылка кампании [campaign] с `r46_slide=` в конце запроса, перед `#`. Пустая -/// ссылка, id слайда, который ссылка не несёт (не число и не `число_индекс`), или -/// `r46_slide` уже есть — как есть. Остальной адрес не перекодируется. -String storyCampaignSlideUrl(String campaign, String slideId) { - if (campaign.isEmpty || !_slideIdFormat.hasMatch(slideId)) return campaign; - final hash = campaign.indexOf('#'); - final base = hash < 0 ? campaign : campaign.substring(0, hash); - final fragment = hash < 0 ? '' : campaign.substring(hash); - final mark = base.indexOf('?'); - final query = mark < 0 ? '' : base.substring(mark + 1); - String name(String pair) { - final raw = pair.split('=').first; - try { - return Uri.decodeQueryComponent(raw); - } on FormatException { - return raw; - } - } - - if (query.split('&').map(name).contains(storiesShareParamSlide)) { - return campaign; - } - final separator = mark < 0 - ? '?' - : query.isEmpty || query.endsWith('&') - ? '' - : '&'; - return '$base$separator$storiesShareParamSlide=$slideId$fragment'; -} diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index 2937c7b..c13ff11 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -16,6 +16,7 @@ import '../components/personalization_story_sound_button.dart'; import '../components/personalization_story_used_products.dart'; import '../components/personalization_toast.dart'; import '../personalization_theme.dart'; +import '../personalization_typography.dart'; import 'personalization_story_viewer.dart'; import 'stories_gif_player.dart'; import 'stories_poll.dart'; @@ -48,6 +49,12 @@ import 'stories_support.dart'; /// Открыта клавиатура — карточка над ней (+16), слайд не сжимается, тап мимо /// карточки только прячет клавиатуру. /// +/// Новая лента ([v3]), как в вебе: медиа решает тип слайда; слайд без медиа — цвета +/// `background_color` (без него — Background/Card), токены — по его яркости; текстовый +/// блок без `font_size` — кеглем основного текста кита; шапка `header` (иконка, заголовок, +/// подзаголовок) под шапкой просмотра, нажатие — [onHeader]; кнопка звука — только у +/// видео со звуком ([hasAudio]). +/// /// Живой ([live]) — только текущий слайд осевшей страницы: у него часы, видео, касания и /// шторка. Соседние страницы показывают свой стартовый слайд неподвижно. class StorySlideView extends StatelessWidget { @@ -80,6 +87,9 @@ class StorySlideView extends StatelessWidget { this.pollShopId = '', this.pollDid = '', this.onPollHold, + this.v3 = false, + this.hasAudio = true, + this.onHeader, }); final Story story; @@ -133,20 +143,46 @@ class StorySlideView extends StatelessWidget { /// Опрос держит слайд (`true`) или отпускает. final ValueChanged? onPollHold; + /// Слайд новой ленты (API v3): правила веба, см. описание класса. + final bool v3; + + /// У видео слайда есть звук: без него у новой ленты нет кнопки звука. + final bool hasAudio; + + /// Нажата шапка `header` слайда новой ленты. + final ValueChanged? onHeader; + /// Удержание дольше этого — пауза, а не касание. static const Duration holdDelay = Duration(milliseconds: 200); StorySlide get slide => story.slides[slideIndex]; + StoryMedia _media(StorySlide slide) => storyMediaOf(slide, byType: v3); + + /// Свой цвет слайда без медиа (новая лента); нет — `null`. + Color? _slideColor(StorySlide slide) => v3 ? storySlideColor(slide) : null; + @override Widget build(BuildContext context) { final slide = this.slide; - final media = storyMediaOf(slide) != StoryMedia.none; + final media = _media(slide) != StoryMedia.none; final body = Builder(builder: (context) => _body(context, slide, media)); - // Слайды с медиа — тёмные токены кита: текст и кнопки лежат на фото или видео. - return media - ? PersonalizationBrightness(brightness: Brightness.dark, child: body) - : body; + // Слайды с медиа — тёмные токены кита: текст и кнопки лежат на фото или видео. Свой + // цвет слайда без медиа — токены по его яркости. + final color = media ? null : _slideColor(slide); + if (media) { + return PersonalizationBrightness( + brightness: Brightness.dark, + child: body, + ); + } + if (color == null) return body; + return PersonalizationBrightness( + brightness: color.computeLuminance() > 0.5 + ? Brightness.light + : Brightness.dark, + child: body, + ); } Widget _body(BuildContext context, StorySlide slide, bool media) { @@ -166,7 +202,9 @@ class StorySlideView extends StatelessWidget { builder: (context, constraints) => _gestures( width: constraints.maxWidth, child: ColoredBox( - color: media ? storyLetterbox(slide) : colors.backgroundCard, + color: media + ? storyLetterbox(slide) + : _slideColor(slide) ?? colors.backgroundCard, child: Stack( fit: StackFit.expand, children: [ @@ -230,7 +268,7 @@ class StorySlideView extends StatelessWidget { RawImage(image: gif.frame, fit: BoxFit.contain), ); } - final url = storyMediaOf(slide) == StoryMedia.video + final url = _media(slide) == StoryMedia.video ? slide.preview : slide.background; final image = storyImage(url, config.imageProvider); @@ -248,7 +286,7 @@ class StorySlideView extends StatelessWidget { Widget _scrim(StorySlide slide) { final shade = const Color( 0xFF000000, - ).withValues(alpha: storyScrimOpacity(slide)); + ).withValues(alpha: storyScrimOpacity(slide, byType: v3)); const clear = Color(0x00000000); return IgnorePointer( child: DecoratedBox( @@ -306,9 +344,9 @@ class StorySlideView extends StatelessWidget { child: _keyboardShield(_navigation()), ); - /// Кнопка звука — только у видео. + /// Кнопка звука — только у видео, у новой ленты — только со звуком. Widget? _sound(StorySlide slide) { - if (storyMediaOf(slide) != StoryMedia.video) return null; + if (_media(slide) != StoryMedia.video || (v3 && !hasAudio)) return null; return PersonalizationStorySoundButton( muted: muted, onPressed: onToggleMute, @@ -419,6 +457,8 @@ class StorySlideView extends StatelessWidget { bottom: _hasRow(slide) ? 64 : 16, child: _primaryButtons(buttons), ), + if (_storyHeader(context, slide) case final header?) + Positioned(left: 16, right: 16, top: _blockTop, child: header), ..._poll(context, slide, bottom: bottom), ..._bottomRow(slide), _header(), @@ -426,8 +466,79 @@ class StorySlideView extends StatelessWidget { ); } + /// Шапка `header` слайда новой ленты: иконка в круге, заголовок и подзаголовок кита; + /// нажатие — [onHeader]. Нечего показать или не новая лента — `null`. + Widget? _storyHeader(BuildContext context, StorySlide slide) { + final header = v3 ? storyHeaderOf(slide) : null; + if (header == null) return null; + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + TextStyle style(TextStyle token, Color color) => token.copyWith( + color: color, + decoration: TextDecoration.none, + fontFamily: theme.fontFamily.familyFor(token.fontWeight!), + package: theme.fontFamily.package, + ); + final icon = storyImage(header.icon, config.imageProvider); + final title = header.title.trim(); + final subtitle = header.subtitle.trim(); + return Semantics( + button: true, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: live ? () => onHeader?.call(header) : null, + child: Row( + children: [ + if (icon != null) ...[ + ClipOval( + child: SizedBox.square( + dimension: 32, + child: Image( + image: icon, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) => + ColoredBox(color: colors.neutral50), + ), + ), + ), + const SizedBox(width: 8), + ], + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (title.isNotEmpty) + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: style( + PersonalizationTypography.smEmphasized, + colors.textPrimary, + ), + ), + if (subtitle.isNotEmpty) + Text( + subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: style( + PersonalizationTypography.xsDefault, + colors.textSecondary, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + Widget _textBlock(BuildContext context, StoryTextBlockElement element) { - final block = storyTextBlock(element); + final block = storyTextBlock(element, bodySize: v3); final code = element.promocode; if (code == null || !live) return block; // Блок с промокодом копирует его: тост сверху и `click` в трекинг. @@ -482,6 +593,10 @@ class StorySlideView extends StatelessWidget { // Место шапки: сама она поверх всего ([_header]). const SizedBox(height: PersonalizationStoryNavigation.height), const SizedBox(height: 16), + if (_storyHeader(context, slide) case final header?) ...[ + header, + const SizedBox(height: 16), + ], if (product.brand.isNotEmpty) ...[ Text( product.brand, diff --git a/lib/src/ui/widgets/stories_support.dart b/lib/src/ui/widgets/stories_support.dart index 4d56365..d8f1992 100644 --- a/lib/src/ui/widgets/stories_support.dart +++ b/lib/src/ui/widgets/stories_support.dart @@ -5,6 +5,7 @@ import '../../stories/stories_response.dart'; import '../components/personalization_product.dart'; import '../components/personalization_story_price.dart'; import '../components/personalization_story_text_block.dart'; +import '../personalization_typography.dart'; import 'stories_image.dart'; /// Как получить картинку по адресу из данных сторис. Не задан — свой загрузчик SDK: качает @@ -49,15 +50,28 @@ enum StoryMedia { video, } -/// Медиа слайда решает непустой `background`, а не тип слайда: товарный слайд с фото — -/// тоже медиа-слайд, а `image` без адреса — нет. -StoryMedia storyMediaOf(StorySlide slide) { +/// Медиа слайда. Старая лента: решает непустой `background`, а не тип слайда — товарный +/// слайд с фото тоже медиа-слайд, а `image` без адреса — нет. Новая лента ([byType]): как +/// в вебе, решает тип — `image` и `video` медиа, товарный слайд — нет. +StoryMedia storyMediaOf(StorySlide slide, {bool byType = false}) { + if (byType) { + return switch (slide.type) { + StorySlideType.image => StoryMedia.image, + StorySlideType.video => StoryMedia.video, + StorySlideType.product => StoryMedia.none, + }; + } if (slide.background.trim().isEmpty) return StoryMedia.none; return slide.type == StorySlideType.video ? StoryMedia.video : StoryMedia.image; } +/// Цвет слайда новой ленты без медиа: `background_color`, как в вебе; не задан — `null`, +/// слайд на Background/Card кита. +Color? storySlideColor(StorySlide slide) => + parseStoryColor(slide.backgroundColor); + /// Цвет полей вокруг вписанного медиа: `background_color` слайда, без него чёрный. Это /// единственное место, где цвет админки идёт в дело: слайд без медиа всегда на /// Background/Card. @@ -99,8 +113,8 @@ StoryProductsElement? storyProducts(StorySlide slide) { /// Плотность затемнения сверху и снизу. Оно есть на каждом слайде: 50% — только у /// медиа без товара и без непустых текстов (голое фото или видео), иначе 30%. -double storyScrimOpacity(StorySlide slide) => - storyMediaOf(slide) != StoryMedia.none && +double storyScrimOpacity(StorySlide slide, {bool byType = false}) => + storyMediaOf(slide, byType: byType) != StoryMedia.none && storyProductElement(slide) == null && storyTextBlocks(slide).isEmpty ? 0.5 @@ -258,6 +272,24 @@ String storyProductLink(StoryProduct product) { return own.isNotEmpty ? own : product.url; } +/// Ссылка шапки слайда для текущей платформы: своя, иначе общая `link`. +String storyHeaderLink(StoryHeaderElement header) { + final own = switch (defaultTargetPlatform) { + TargetPlatform.android => header.linkAndroid, + TargetPlatform.iOS => header.linkIos, + _ => '', + }; + return own.isNotEmpty ? own : header.link; +} + +/// Шапка слайда новой ленты (`header`), если ей есть что показать; нет — `null`. +StoryHeaderElement? storyHeaderOf(StorySlide slide) { + for (final element in slide.elements) { + if (element is StoryHeaderElement && element.isNotEmpty) return element; + } + return null; +} + /// Куда ведёт кнопка товарного слайда: своя ссылка кнопки (платформенная, затем общая), /// без неё — товар слайда (диплинк, затем `url`). String storySlideButtonLink(StoryButtonElement button, StoryProduct? product) { @@ -276,21 +308,31 @@ TextAlign storyTextAlign(String value) => switch (value.trim().toLowerCase()) { /// Текстовый блок сервера → [PersonalizationStoryTextBlock]. /// -/// Шрифт `serif` / `monospaced` — системные семейства с запасными для iOS, где имён -/// `serif` и `monospace` нет; `sans-serif` и пусто — шрифт темы. Межстрочный не задан — -/// заготовка макета для этого кегля ([PersonalizationStoryTextBlock.presetLineHeight]). -PersonalizationStoryTextBlock storyTextBlock(StoryTextBlockElement element) { - final (family, fallback) = switch (element.fontType) { +/// Шрифт `serif` / `monospace` (и `monospaced`) — системные семейства с запасными для +/// iOS, где имён `serif` и `monospace` нет; `sans-serif` и пусто — шрифт темы. +/// Межстрочный не задан — заготовка макета для этого кегля +/// ([PersonalizationStoryTextBlock.presetLineHeight]). С [bodySize] (новая лента) без +/// `font_size` — кегль основного текста кита ([PersonalizationTypography.baseDefault]), а +/// не 14. +PersonalizationStoryTextBlock storyTextBlock( + StoryTextBlockElement element, { + bool bodySize = false, +}) { + final (family, fallback) = switch (element.fontType.trim().toLowerCase()) { 'serif' => ('serif', const ['Georgia', 'Times New Roman']), + 'monospace' || 'monospaced' => ('monospace', const ['Menlo', 'Courier']), _ => (null, null), }; + final fontSize = bodySize && !element.hasFontSize + ? PersonalizationTypography.baseDefault.fontSize! + : element.fontSize; return PersonalizationStoryTextBlock( text: element.text, - fontSize: element.fontSize, + fontSize: fontSize, lineHeight: element.lineSpacing > 0 ? element.lineSpacing - : PersonalizationStoryTextBlock.presetLineHeight(element.fontSize), + : PersonalizationStoryTextBlock.presetLineHeight(fontSize), color: parseStoryColor(element.textColor), background: element.backgroundOpacity > 0 ? parseStoryColor( diff --git a/lib/src/v3/personalization_v3.dart b/lib/src/v3/personalization_v3.dart index eeddc93..ab19eb3 100644 --- a/lib/src/v3/personalization_v3.dart +++ b/lib/src/v3/personalization_v3.dart @@ -36,7 +36,9 @@ export '../stories/stories_response.dart' StoryPollAnswer, StoryPollResults, StoryPollLabels, - StoryPollElement; + StoryPollElement, + StoryHeaderElement, + StoryTextBlockV3; // Опросы слайдов: шов транспорта ответов (тесты, офлайн-демо). Карточка и её логика — // внутренности просмотра. export '../ui/widgets/stories_polls_api.dart' diff --git a/test/stories/stories_response_test.dart b/test/stories/stories_response_test.dart index e98c06d..8fa26b9 100644 --- a/test/stories/stories_response_test.dart +++ b/test/stories/stories_response_test.dart @@ -231,9 +231,12 @@ void main() { expect(product.image, 'https://pictures.example/180/135478.jpg'); }); - test('products, text block; header dropped', () { + test('products, text block; header parsed for the new feed', () { final elements = block.stories[1].slides[1].elements; - expect(elements, hasLength(3), reason: 'header is not drawn by the kit'); + expect(elements, hasLength(4)); + final header = elements.whereType().single; + expect(header.title, 'dropped'); + expect((header.icon, header.subtitle, header.link), ('', '', '')); final products = elements.whereType().single; expect(products.showLabel, 'Товары для геймеров'); diff --git a/test/ui/stories_poll_widget_test.dart b/test/ui/stories_poll_widget_test.dart index 4cb6e2f..1a836cf 100644 --- a/test/ui/stories_poll_widget_test.dart +++ b/test/ui/stories_poll_widget_test.dart @@ -312,7 +312,8 @@ void main() { group('text', () { final text = _poll('mini_poll', kind: 'text', maxLength: 10); - final stories = _stories(>>[ + // New story objects for each test: the session of the new feed is theirs. + List stories() => _stories(>>[ >[ _slide('1', >[text]), _slide('2'), @@ -329,7 +330,7 @@ void main() { testWidgets( 'keyboard: the card above it, the slide stays; limit, error, retry', (tester) async { - await open(tester, stories); + await open(tester, stories()); final slideText = tester.getRect(find.text('Slide 1')); final down = tester.getRect(card); await tester.tap(find.byType(TextField)); @@ -382,7 +383,7 @@ void main() { testWidgets('a tap past the card with the keyboard only hides it', ( tester, ) async { - await open(tester, stories); + await open(tester, stories()); await tester.tap(find.byType(TextField)); await tester.pump(); await showKeyboard(tester); diff --git a/test/ui/stories_share_test.dart b/test/ui/stories_share_test.dart index 7d2b8ac..dad8065 100644 --- a/test/ui/stories_share_test.dart +++ b/test/ui/stories_share_test.dart @@ -133,66 +133,19 @@ void main() { ], }); - test('prefers the slide link, falls back to the campaign link with the ' - 'slide in it', () { + test('prefers the slide link, falls back to the campaign link as it is, ' + 'as the web', () { expect( storySlideShareUrl(story, story.slides[0]), 'https://shop.test/?r46_slide=1', ); expect( storySlideShareUrl(story, story.slides[1]), - 'https://shop.test/?r46_story=5&r46_slide=5_0', - reason: 'a product slide has no link of its own', + 'https://shop.test/?r46_story=5', + reason: 'a product slide has no link of its own; no r46_slide added', ); }); - test( - 'the campaign link takes r46_slide once, the rest stays as it was', - () { - const campaign = 'https://shop.test/?r46_story=5'; - expect( - storyCampaignSlideUrl(campaign, '37'), - 'https://shop.test/?r46_story=5&r46_slide=37', - ); - expect( - storyCampaignSlideUrl( - 'https://shop.test/p?q=a%20b&r46_story=5#top', - '5_2', - ), - 'https://shop.test/p?q=a%20b&r46_story=5&r46_slide=5_2#top', - reason: 'before the fragment, nothing re-encoded', - ); - expect( - storyCampaignSlideUrl('https://shop.test/promo', '5_2'), - 'https://shop.test/promo?r46_slide=5_2', - ); - expect( - storyCampaignSlideUrl('https://shop.test/?', '7'), - 'https://shop.test/?r46_slide=7', - ); - expect( - storyCampaignSlideUrl('$campaign&r46_slide=7', '5_2'), - '$campaign&r46_slide=7', - reason: 'r46_slide is there already', - ); - for (final id in [ - 'x', - '', - '1_', - '12345678901', - '1_12345', - '1;2', - ]) { - expect( - storyCampaignSlideUrl(campaign, id), - campaign, - reason: 'a link does not carry "$id"', - ); - } - expect(storyCampaignSlideUrl('', '37'), ''); - }, - ); - test('nothing when sharing is off or the link is not http(s)', () { Story make(Map json) => Story.fromJson({ ...json, @@ -214,7 +167,7 @@ void main() { final upper = make({'share_url': 'HTTPS://shop.test/'}); expect( storySlideShareUrl(upper, upper.slides.single), - 'HTTPS://shop.test/?r46_slide=1', + 'HTTPS://shop.test/', ); }); }); diff --git a/test/ui/stories_share_widget_test.dart b/test/ui/stories_share_widget_test.dart index 5a21d8a..67e1c50 100644 --- a/test/ui/stories_share_widget_test.dart +++ b/test/ui/stories_share_widget_test.dart @@ -303,7 +303,7 @@ void main() { await tester.tap(_share); await tester.pump(); - expect(api.shared, ['$_link39&r46_slide=39_0']); + expect(api.shared, [_link39]); expect(api.anchors.single, share); expect(server.events, ['view 39/39_0', 'share 39/39_0']); await tester.tap(_share); @@ -337,9 +337,7 @@ void main() { await open(tester, 'Products'); await tester.tap(_share); await tester.pump(); - expect(api.shared, [ - 'demoapp://shop.example/?r46_story=39&r46_slide=39_0', - ]); + expect(api.shared, ['demoapp://shop.example/?r46_story=39']); expect(server.events, ['view 39/39_0', 'share 39/39_0']); }); @@ -352,7 +350,7 @@ void main() { await gesture.up(); await tester.pump(); expect(api.shared, [ - '$_link39&r46_slide=39_1', + _link39, ], reason: 'a long press is a press, on the slide it is on'); }); @@ -593,7 +591,7 @@ void main() { // Its "Share" carries the slide again. await tester.tap(_share); await tester.pump(); - expect(api.shared, ['$_link39&r46_slide=39_1']); + expect(api.shared, [_link39]); }); testWidgets('a link slide missing from the answer — start_position', ( diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart new file mode 100644 index 0000000..4572c2c --- /dev/null +++ b/test/ui/stories_v3_rules_test.dart @@ -0,0 +1,562 @@ +// Stories over API v3 behave as the web SDK does (start slide, viewed, media by type, +// the slide colour, text blocks, header, buttons without a link, promo codes), drawn by +// the kit; the old feed keeps the kit's rules. + +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_slide_view.dart'; + +const String _code = 'block'; + +class _FakeHostApi extends pigeon.PersonalizationHostApi { + /// What the old feed through the bridge answers. + String? bridgeFeed; + final List bridge = []; + Map> seen = >{}; + + @override + Future getDid(String? shopId) async => 'did-1'; + + @override + Future getSid(String? shopId) async => 'sid-1'; + + @override + Future legacyGetStories(String code, String? shopId) async => + bridgeFeed!; + + @override + Future>> getStoriesSeen(String shop) async => seen; + + @override + Future setStorySlideSeen( + String shop, + String story, + String slide, + ) async {} + + @override + Future trackStoryView( + String storyId, + String slideId, + String? code, + String? shopId, + ) async => bridge.add('view $storyId/$slideId'); + + @override + Future trackStoryClick( + String storyId, + String slideId, + String? code, + String? shopId, + ) async => bridge.add('click $storyId/$slideId'); + + @override + Future trackSetSource( + pigeon.TrackingSourceWire source, + String? shopId, + ) async {} +} + +Widget _icon(BuildContext context, String asset, double size, Color color) => + SizedBox.square(key: ValueKey(asset), dimension: size); + +Map _story( + int id, + List> slides, { + int start = 0, + bool viewed = false, +}) => { + 'id': id, + 'name': 'Story $id', + 'avatar': '', + 'viewed': viewed, + 'start_position': start, + 'slides': slides, +}; + +/// A slide that runs at once: no media URL, a text naming it. +Map _slide( + String id, { + String type = 'image', + String background = '', + String? color, + int duration = 1, + List> elements = const >[], +}) => { + 'id': id, + 'type': type, + 'background': background, + 'background_color': ?color, + 'duration': duration, + 'elements': >[ + { + 'type': 'text_block', + 'text_input': 'Slide $id', + 'font_size': 20, + 'y_offset': 60, + }, + ...elements, + ], +}; + +Map _product(String id) => { + 'type': 'product', + 'item': {'id': id, 'name': 'Product $id', 'price': 1}, +}; + +void main() { + late _FakeHostApi api; + late PersonalizationSdk sdk; + late List> events; + late List> stories; + late List links; + late List products; + late List promos; + + setUp(() { + StoriesSeenStore.instance = StoriesSeenStore(); + api = _FakeHostApi(); + sdk = PersonalizationSdk(api: api, shopId: 'shop'); + events = >[]; + links = []; + products = []; + promos = []; + stories = >[]; + StoriesApiV3.domain = 'app.example'; + StoriesApiV3.send = (method, uri, body) async { + if (method == 'POST') { + events.add(jsonDecode(body!) as Map); + return (status: 200, body: '{"status":"success"}'); + } + return ( + status: 200, + body: jsonEncode({ + 'status': 'success', + 'payload': {'id': 35, 'stories': stories}, + }), + ); + }; + }); + + tearDown(() => StoriesApiV3.domain = null); + + List sent() => [ + for (final event in events) + '${event['event']} ${event['story_id']}/${event['slide_id']}', + ]; + + Future bar(WidgetTester tester, {bool v3 = true}) async { + if (!v3) { + StoriesApiV3.domain = null; + api.bridgeFeed = jsonEncode({ + 'id': 35, + 'stories': stories, + }); + } + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: PersonalizationStories( + code: _code, + sdk: sdk, + iconBuilder: _icon, + onLinkClick: links.add, + onProductClick: (product) => products.add(product.id), + onPromoCopied: promos.add, + ), + ), + ), + ), + ), + ); + await tester.pump(); + await tester.pump(); + } + + Future settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pump(); + } + + Future open(WidgetTester tester, String name) async { + await tester.tap(find.text(name)); + await settle(tester); + } + + Future close(WidgetTester tester) async { + Navigator.of(tester.element(find.byType(PersonalizationStoryViewer))).pop(); + await settle(tester); + } + + PersonalizationStoryCoverState cover(WidgetTester tester, int index) => tester + .widgetList( + find.byType(PersonalizationStoryPreview), + ) + .elementAt(index) + .state; + + group('start slide and viewed, as the web', () { + testWidgets('a story opens at start_position, not at the first unseen ' + 'slide of the device', (tester) async { + api.seen = >{ + '1': ['11'], + }; + stories.add( + _story(1, >[ + _slide('10', duration: 30), + _slide('11', duration: 30), + _slide('12', duration: 30), + ], start: 2), + ); + await bar(tester); + await open(tester, 'Story 1'); + expect(find.text('Slide 12'), findsOneWidget); + expect(sent(), ['view 1/12']); + }); + + testWidgets('a story left in the middle opens there again; finished — it ' + 'is viewed and starts over', (tester) async { + stories.add( + _story(1, >[ + _slide('10', duration: 30), + _slide('11', duration: 30), + ]), + ); + await bar(tester); + expect(cover(tester, 0), PersonalizationStoryCoverState.unviewed); + await open(tester, 'Story 1'); + final viewer = tester.getRect(find.byType(PersonalizationStoryViewer)); + final right = Offset(viewer.right - 10, viewer.center.dy); + await tester.tapAt(right); + await tester.pump(); + expect(find.text('Slide 11'), findsOneWidget); + await close(tester); + expect( + cover(tester, 0), + PersonalizationStoryCoverState.unviewed, + reason: 'left in the middle', + ); + await open(tester, 'Story 1'); + expect(find.text('Slide 11'), findsOneWidget, reason: 'where it was'); + await tester.tapAt(right); + await settle(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(cover(tester, 0), PersonalizationStoryCoverState.viewed); + await open(tester, 'Story 1'); + expect(find.text('Slide 10'), findsOneWidget, reason: 'starts over'); + }); + + testWidgets('a swipe to the next story marks the one left viewed', ( + tester, + ) async { + stories.addAll(>[ + _story(1, >[ + _slide('10', duration: 30), + _slide('11', duration: 30), + ]), + _story(2, >[_slide('20', duration: 30)]), + _story(3, >[ + _slide('30', duration: 30), + ], viewed: true), + ]); + await bar(tester); + expect(cover(tester, 2), PersonalizationStoryCoverState.viewed); + await open(tester, 'Story 1'); + await tester.fling( + find.byType(PersonalizationStoryViewer), + const Offset(-500, 0), + 1500, + ); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.text('Slide 20'), findsOneWidget); + expect(sent(), ['view 1/10', 'view 2/20']); + await close(tester); + expect(cover(tester, 0), PersonalizationStoryCoverState.viewed); + expect(cover(tester, 1), PersonalizationStoryCoverState.unviewed); + await open(tester, 'Story 1'); + expect(find.text('Slide 10'), findsOneWidget, reason: 'its slide'); + }); + + testWidgets('the old feed keeps the first unseen slide', (tester) async { + api.seen = >{ + '1': ['10'], + }; + stories.add( + _story(1, >[ + _slide('10', duration: 30), + _slide('11', duration: 30), + ]), + ); + await bar(tester, v3: false); + await open(tester, 'Story 1'); + expect(find.text('Slide 11'), findsOneWidget); + }); + }); + + group('slides', () { + // The slide's own box: the nearest coloured box around its text. + Color? slideColor(WidgetTester tester) => tester + .widget( + find + .ancestor( + of: find.textContaining('Slide '), + matching: find.byType(ColoredBox), + ) + .first, + ) + .color; + + testWidgets('media by type; a slide without media takes background_color', ( + tester, + ) async { + stories.addAll(>[ + _story(1, >[ + _slide( + '10', + type: '', + background: 'https://cdn.example/a.jpg', + color: '#112233', + ), + ]), + _story(2, >[_slide('20', color: '#445566')]), + ]); + await bar(tester); + await open(tester, 'Story 1'); + expect(slideColor(tester), const Color(0xFF112233)); + expect( + find.descendant( + of: find.byType(PersonalizationStoryViewer), + matching: find.byType(Image), + ), + findsNothing, + reason: 'a product type is no media whatever the background', + ); + expect(find.text('Retry'), findsNothing); + await close(tester); + await open(tester, 'Story 2'); + // An image slide with no URL: media (its letterbox colour), nothing to load. + expect(slideColor(tester), const Color(0xFF445566)); + expect(find.text('Retry'), findsNothing); + }); + + testWidgets('the old feed keeps the kit card colour', (tester) async { + stories.add( + _story(1, >[ + _slide('10', type: '', color: '#112233'), + ]), + ); + await bar(tester, v3: false); + await open(tester, 'Story 1'); + expect(slideColor(tester), PersonalizationColors.light.backgroundCard); + }); + + testWidgets('text blocks: the kit body size without font_size, ' + 'text_italic and monospace', (tester) async { + stories.add( + _story(1, >[ + _slide( + '10', + elements: >[ + { + 'type': 'text_block', + 'text_input': 'Plain', + 'text_italic': true, + 'font_type': 'monospace', + 'y_offset': 20, + }, + ], + ), + ]), + ); + await bar(tester); + await open(tester, 'Story 1'); + final style = tester.widget(find.text('Plain')).style!; + expect(style.fontSize, PersonalizationTypography.baseDefault.fontSize); + expect(style.fontStyle, FontStyle.italic); + expect(style.fontFamily, 'monospace'); + await close(tester); + + await bar(tester, v3: false); + await open(tester, 'Story 1'); + expect( + tester.widget(find.text('Plain')).style!.fontSize, + StoryTextBlockElement.defaultFontSize, + reason: 'the old feed keeps 14', + ); + }); + }); + + group('the sound button', () { + Future slide( + WidgetTester tester, { + required bool v3, + required bool hasAudio, + }) async { + final story = Story.fromJson({ + 'id': 1, + 'name': 'Video', + 'avatar': '', + 'slides': >[ + { + 'id': '10', + 'type': 'video', + 'background': 'https://cdn.example/v.mp4', + }, + ], + }); + await tester.pumpWidget( + MaterialApp( + home: StorySlideView( + story: story, + slideIndex: 0, + config: PersonalizationStoryViewer( + stories: [story], + iconBuilder: _icon, + ), + live: true, + v3: v3, + hasAudio: hasAudio, + ), + ), + ); + } + + final Finder button = find.byType(PersonalizationStorySoundButton); + + testWidgets('the new feed: only for a video with sound', (tester) async { + await slide(tester, v3: true, hasAudio: false); + expect(button, findsNothing); + await slide(tester, v3: true, hasAudio: true); + expect(button, findsOneWidget); + }); + + testWidgets('the old feed: for every video', (tester) async { + await slide(tester, v3: false, hasAudio: false); + expect(button, findsOneWidget); + }); + }); + + group('taps and events', () { + testWidgets('the header: drawn, a tap sends click and opens its link', ( + tester, + ) async { + stories.add( + _story(1, >[ + _slide( + '10', + elements: >[ + { + 'type': 'header', + 'icon': '', + 'title': 'Brand', + 'subtitle': 'Since 1990', + 'link': 'https://shop.example/brand', + }, + ], + ), + ]), + ); + await bar(tester); + await open(tester, 'Story 1'); + expect(find.text('Since 1990'), findsOneWidget); + await tester.tap(find.text('Brand')); + await settle(tester); + expect(sent(), ['view 1/10', 'click 1/10']); + expect(links, ['https://shop.example/brand']); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + }); + + testWidgets('the old feed draws no header', (tester) async { + stories.add( + _story(1, >[ + _slide( + '10', + elements: >[ + {'type': 'header', 'title': 'Brand'}, + ], + ), + ]), + ); + await bar(tester, v3: false); + await open(tester, 'Story 1'); + expect(find.text('Brand'), findsNothing); + }); + + testWidgets( + 'a button without a link: click only, also on a product slide', + (tester) async { + stories.add( + _story(1, >[ + _slide( + '10', + type: '', + duration: 30, + elements: >[ + _product('p1'), + {'type': 'button', 'title': 'Buy'}, + ], + ), + ]), + ); + await bar(tester); + await open(tester, 'Story 1'); + await tester.tap(find.text('Buy')); + await settle(tester); + expect(sent(), ['view 1/10', 'click 1/10']); + expect(products, isEmpty); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + await close(tester); + + await bar(tester, v3: false); + await open(tester, 'Story 1'); + await tester.tap(find.text('Buy')); + await settle(tester); + expect(products, ['p1'], reason: 'the old feed opens it'); + }, + ); + + testWidgets('copying a promo code sends no click', (tester) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async => null, + ); + stories.add( + _story(1, >[ + _slide( + '10', + duration: 30, + elements: >[ + { + 'type': 'text_block', + 'text_input': 'Code', + 'promocode': 'SALE10', + 'y_offset': 20, + }, + ], + ), + ]), + ); + await bar(tester); + await open(tester, 'Story 1'); + await tester.tap(find.text('Code')); + await tester.pump(); + expect(promos, ['SALE10']); + expect(sent(), ['view 1/10']); + await tester.pump(const Duration(seconds: 3)); + }); + }); +} diff --git a/test/v3_gate_test.dart b/test/v3_gate_test.dart index ae20edf..037bca4 100644 --- a/test/v3_gate_test.dart +++ b/test/v3_gate_test.dart @@ -30,6 +30,8 @@ const Set _v3Names = { 'StoryPollResults', 'StoryPollLabels', 'StoryPollElement', + 'StoryHeaderElement', + 'StoryTextBlockV3', 'StoryPollsTransport', 'StoryPollReply', }; From 353af8e48d138e79093173d1ebebb7784ffe3bd7 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 20 Nov 2026 12:29:34 +0400 Subject: [PATCH 04/24] =?UTF-8?q?docs(readme):=20how=20an=20app=20opens=20?= =?UTF-8?q?the=20shared=20links=20of=20stories=20over=20API=20v3=20?= =?UTF-8?q?=E2=80=94=20Universal=20Links=20and=20App=20Links=20on=20the=20?= =?UTF-8?q?shop's=20domain,=20then=20PersonalizationStoriesV3.handleLink?= =?UTF-8?q?=20=E2=80=94=20with=20the=20link=20format,=20marked=20as=20behi?= =?UTF-8?q?nd=20the=20v3=20gate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/README.md b/README.md index 2be83b6..2efbe90 100644 --- a/README.md +++ b/README.md @@ -938,6 +938,38 @@ same values, and fails with the released error codes. Their replacements: | `getStoredPushToken`, `setPushNotificationCallbacks` | `notifications.getPushToken`, `notifications.setCallbacks` | | `trackEvent`, `trackPurchase` | `tracking.custom`, `tracking.purchase` | +## Stories over API v3: shared links + +Stories over API v3 are behind the v3 gate: not part of the public API yet, reached +only through `package:rees46_sdk/src/v3/personalization_v3.dart`. + +The "Share" button of a slide shares a link to the shop's site: + +``` +https:///?r46_stories=&r46_story=[&r46_slide=] +``` + +To open such a link in the app instead of the browser, the app claims the shop's domain: + +- iOS — Universal Links: the `Associated Domains` capability with + `applinks:`, and `https:///.well-known/apple-app-site-association` + listing the app (`.`) and the paths of the links. +- Android — App Links: an `intent-filter` with `android:autoVerify="true"` for + `https://` on the activity that opens links, and + `https:///.well-known/assetlinks.json` with the app's package name and the + SHA-256 fingerprint of its signing certificate. + +The app gets the URL as any deep link (for example through its router or an app-links +plugin) and hands it over: + +```dart +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; + +final handled = PersonalizationStoriesV3.handleLink(context, url); +// false — not a stories link (or no apiV3Domain): open it as usual. +``` + ## Example app A full demo — tracking, recommendations, search, catalog, loyalty, popups, push From 50e1da8b169ca480026283919258016b44746a66 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 20 Nov 2026 12:30:20 +0400 Subject: [PATCH 05/24] feat(stories): the viewer of stories over API v3 keeps the sound button's choice on the device and shows the button only for a video with an audio track, as the web SDK does; the bridges read the track list off the main thread (Android MediaMetadataRetriever, iOS AVURLAsset) through storiesVideoHasAudio, and a video whose tracks cannot be read keeps the button --- .../Rees46FlutterSdkPlugin.kt | 6 ++ .../rees46_flutter_sdk/StoriesVideoAudio.kt | 65 +++++++++++++ .../pigeon/PersonalizationApi.g.kt | 28 ++++++ .../StoriesVideoAudioTest.kt | 81 ++++++++++++++++ example/ios/RunnerTests/RootBridgeTests.swift | 93 +++++++++++++++++++ .../rees46_sdk/Rees46FlutterSdkPlugin.swift | 4 + .../Sources/rees46_sdk/StoriesSupport.swift | 37 ++++++++ .../pigeon/PersonalizationApi.g.swift | 28 ++++++ lib/src/pigeon/personalization_api.g.dart | 32 +++++++ .../widgets/personalization_story_viewer.dart | 18 +++- lib/src/ui/widgets/stories_sound.dart | 43 ++++++++- pigeons/personalization_api.dart | 8 ++ test/ui/stories_runtime_test.dart | 49 ++++++++++ 13 files changed, 489 insertions(+), 3 deletions(-) create mode 100644 android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudio.kt create mode 100644 android/src/test/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudioTest.kt diff --git a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/Rees46FlutterSdkPlugin.kt b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/Rees46FlutterSdkPlugin.kt index d3a2162..1bbdbe3 100644 --- a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/Rees46FlutterSdkPlugin.kt +++ b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/Rees46FlutterSdkPlugin.kt @@ -103,6 +103,9 @@ class Rees46FlutterSdkPlugin : /** Which tokens Dart's `onToken` hears. */ private val tokenReports = TokenReports() + /** Whether a stories video has sound: the viewer's sound button. */ + internal var storiesVideoAudio = StoriesVideoAudio() + /** This engine's Dart side of the native log, while Dart has a log handler. */ private val logSink: (SdkLogMessage) -> Unit = { message -> onMain { runCatching { stateApi?.onLog(message.toWire()) { } } } @@ -1016,6 +1019,9 @@ class Rees46FlutterSdkPlugin : override fun endStoriesAudio() = Unit + override fun storiesVideoHasAudio(source: String, callback: (Result) -> Unit) = + storiesVideoAudio.hasAudio(source, callback) + // endregion // endregion diff --git a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudio.kt b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudio.kt new file mode 100644 index 0000000..1e26a9e --- /dev/null +++ b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudio.kt @@ -0,0 +1,65 @@ +package com.rees46.rees46_flutter_sdk + +import android.media.MediaMetadataRetriever +import android.os.Handler +import android.os.Looper +import java.util.concurrent.Executor +import java.util.concurrent.Executors + +/** + * Whether a stories video has an audio track: the viewer shows its sound button only then, as + * the web SDK does. The container is read off the main thread (a network video reads its + * header over the network) and the answer goes back on the main thread, where Pigeon replies. + */ +internal class StoriesVideoAudio( + private val probe: (String) -> Boolean? = ::readHasAudio, + private val worker: Executor = defaultWorker, + private val main: (Runnable) -> Unit = { mainHandler.post(it) }, +) { + + /** Answers [callback] with the audio of [source]: null when it cannot be read. */ + fun hasAudio(source: String, callback: (Result) -> Unit) { + worker.execute { + val answer = try { + probe(source) + } catch (e: Exception) { + null + } + main(Runnable { callback(Result.success(answer)) }) + } + } + + companion object { + private val defaultWorker: Executor by lazy { Executors.newSingleThreadExecutor() } + private val mainHandler: Handler by lazy { Handler(Looper.getMainLooper()) } + + /** `http(s)` addresses are read over the network, anything else is a file path. */ + fun isRemote(source: String): Boolean = + source.startsWith("http://", ignoreCase = true) || + source.startsWith("https://", ignoreCase = true) + + /** + * `METADATA_KEY_HAS_AUDIO` is there only when the container has an audio track; null + * when the source cannot be opened. + */ + fun readHasAudio(source: String): Boolean? { + val retriever = MediaMetadataRetriever() + return try { + if (isRemote(source)) { + retriever.setDataSource(source, emptyMap()) + } else { + retriever.setDataSource(source) + } + retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO) != null + } catch (e: Exception) { + null + } finally { + try { + retriever.release() + } catch (e: Exception) { + // Nothing was opened. + } + } + } + } +} diff --git a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/pigeon/PersonalizationApi.g.kt b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/pigeon/PersonalizationApi.g.kt index c6736f7..25ea794 100644 --- a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/pigeon/PersonalizationApi.g.kt +++ b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/pigeon/PersonalizationApi.g.kt @@ -4913,6 +4913,14 @@ interface PersonalizationHostApi { * watching the volume. iOS only; a no-op on Android. */ fun endStoriesAudio() + /** + * Whether the video at [source] — an `http(s)` URL or a file path of the stories' + * video cache — has an audio track: the stories viewer shows its sound button only + * then, as the web SDK does. Read off the main thread from the container's track + * list (Android `MediaMetadataRetriever`, iOS `AVURLAsset`); null when it cannot be + * read. + */ + fun storiesVideoHasAudio(source: String, callback: (Result) -> Unit) /** * Opens the system settings where the user turns notifications on for the app: the * app's notification settings on Android, the app's page in Settings on iOS. What the @@ -7063,6 +7071,26 @@ interface PersonalizationHostApi { channel.setMessageHandler(null) } } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.storiesVideoHasAudio$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val sourceArg = args[0] as String + api.storiesVideoHasAudio(sourceArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(PersonalizationApiPigeonUtils.wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } run { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openNotificationSettings$separatedMessageChannelSuffix", codec) if (api != null) { diff --git a/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudioTest.kt b/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudioTest.kt new file mode 100644 index 0000000..7dffefe --- /dev/null +++ b/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudioTest.kt @@ -0,0 +1,81 @@ +package com.rees46.rees46_flutter_sdk + +import java.util.concurrent.Executor +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +internal class StoriesVideoAudioTest { + /** Runs the work when asked, so the order of the threads is visible. */ + private class Queue : Executor { + val tasks = mutableListOf() + override fun execute(command: Runnable) { + tasks += command + } + + fun run() { + val pending = tasks.toList() + tasks.clear() + pending.forEach { it.run() } + } + } + + @Test + fun theProbeRunsOffTheCallerAndTheAnswerComesOnTheMainThread() { + val worker = Queue() + val main = Queue() + val probed = mutableListOf() + val audio = StoriesVideoAudio( + probe = { probed += it; true }, + worker = worker, + main = { main.execute(it) }, + ) + val answers = mutableListOf>() + audio.hasAudio("https://cdn.example/v.mp4") { answers += it } + assertTrue(probed.isEmpty(), "not on the caller's thread") + worker.run() + assertEquals(listOf("https://cdn.example/v.mp4"), probed) + assertTrue(answers.isEmpty(), "the reply waits for the main thread") + main.run() + assertEquals(true, answers.single().getOrNull()) + } + + @Test + fun noAudioIsFalseAndAFailedReadIsNull() { + val direct = Executor { it.run() } + val answers = mutableListOf() + StoriesVideoAudio(probe = { false }, worker = direct, main = { it.run() }) + .hasAudio("/cache/v.mp4") { answers += it.getOrThrow() } + StoriesVideoAudio( + probe = { throw IllegalStateException("broken") }, + worker = direct, + main = { it.run() }, + ).hasAudio("/cache/v.mp4") { answers += it.getOrThrow() } + StoriesVideoAudio(probe = { null }, worker = direct, main = { it.run() }) + .hasAudio("x") { answers += it.getOrThrow() } + assertEquals(listOf(false, null, null), answers) + } + + @Test + fun httpAddressesAreRemoteTheRestAreFiles() { + assertTrue(StoriesVideoAudio.isRemote("https://cdn.example/v.mp4")) + assertTrue(StoriesVideoAudio.isRemote("HTTP://cdn.example/v.mp4")) + assertFalse(StoriesVideoAudio.isRemote("/data/user/0/app/cache/stories/v.mp4")) + assertFalse(StoriesVideoAudio.isRemote("file:///cache/v.mp4")) + } + + @Test + fun thePluginAnswersThroughIt() { + val plugin = Rees46FlutterSdkPlugin() + plugin.storiesVideoAudio = StoriesVideoAudio( + probe = { it.endsWith("sound.mp4") }, + worker = { it.run() }, + main = { it.run() }, + ) + val answers = mutableListOf() + plugin.storiesVideoHasAudio("https://cdn.example/sound.mp4") { answers += it.getOrThrow() } + plugin.storiesVideoHasAudio("https://cdn.example/mute.mp4") { answers += it.getOrThrow() } + assertEquals(listOf(true, false), answers) + } +} diff --git a/example/ios/RunnerTests/RootBridgeTests.swift b/example/ios/RunnerTests/RootBridgeTests.swift index 524778e..6f351f9 100644 --- a/example/ios/RunnerTests/RootBridgeTests.swift +++ b/example/ios/RunnerTests/RootBridgeTests.swift @@ -218,3 +218,96 @@ final class PendingPushesTests: XCTestCase { XCTAssertEqual(pending.count("shop-a"), PendingPushes.limit) } } + +/// Whether a stories video has sound: read off the main thread, answered on it; a source that +/// cannot be read is `nil`. +final class StoriesVideoAudioTests: XCTestCase { + + private var original: ((URL) async throws -> Bool)! + + override func setUp() { + super.setUp() + original = StoriesVideoAudio.loader + } + + override func tearDown() { + StoriesVideoAudio.loader = original + super.tearDown() + } + + private func answer(_ source: String, through plugin: Bool = false) -> Bool?? { + let done = expectation(description: "answer") + var result: Bool?? + let reply: (Bool?) -> Void = { value in + XCTAssertTrue(Thread.isMainThread) + result = .some(value) + done.fulfill() + } + if plugin { + let impl = PersonalizationHostApiImpl( + popupApi: PersonalizationPopupFlutterApi(binaryMessenger: SilentMessenger()), + stateApi: PersonalizationStateFlutterApi(binaryMessenger: SilentMessenger()) + ) + impl.storiesVideoHasAudio(source: source) { reply(try? $0.get()) } + wait(for: [done], timeout: 5) + impl.stop() + } else { + StoriesVideoAudio.hasAudio(source: source, completion: reply) + wait(for: [done], timeout: 5) + } + return result + } + + func test_urls_http_andFile_asTheyAre_aPath_asAFile() { + XCTAssertEqual(StoriesVideoAudio.url(for: "https://cdn.example/v.mp4")?.absoluteString, + "https://cdn.example/v.mp4") + XCTAssertEqual(StoriesVideoAudio.url(for: "file:///tmp/v.mp4")?.path, "/tmp/v.mp4") + let path = StoriesVideoAudio.url(for: "/var/cache/stories/v.mp4") + XCTAssertTrue(path?.isFileURL ?? false) + XCTAssertEqual(path?.path, "/var/cache/stories/v.mp4") + XCTAssertNil(StoriesVideoAudio.url(for: "")) + } + + func test_theLoaderDecides_aFailureIsNil() { + var loaded: [String] = [] + StoriesVideoAudio.loader = { url in + loaded.append(url.absoluteString) + if url.absoluteString.hasSuffix("broken.mp4") { throw URLError(.badServerResponse) } + return url.absoluteString.hasSuffix("sound.mp4") + } + XCTAssertEqual(answer("https://cdn.example/sound.mp4"), .some(true)) + XCTAssertEqual(answer("https://cdn.example/mute.mp4", through: true), .some(false)) + XCTAssertEqual(answer("https://cdn.example/broken.mp4"), .some(nil)) + XCTAssertEqual(answer(""), .some(nil)) + XCTAssertEqual(loaded.count, 3) + } + + func test_aRealFile_audioIsSeen_aNonMediaFileHasNone() throws { + // A one-second silent WAV: an audio track AVFoundation reads. + let rate = 8000 + var wav = Data() + func append(_ value: T) { + var little = value.littleEndian + wav.append(Data(bytes: &little, count: MemoryLayout.size)) + } + wav.append("RIFF".data(using: .ascii)!) + append(UInt32(36 + rate * 2)) + wav.append("WAVEfmt ".data(using: .ascii)!) + append(UInt32(16)); append(UInt16(1)); append(UInt16(1)) + append(UInt32(rate)); append(UInt32(rate * 2)); append(UInt16(2)); append(UInt16(16)) + wav.append("data".data(using: .ascii)!) + append(UInt32(rate * 2)) + wav.append(Data(count: rate * 2)) + let directory = FileManager.default.temporaryDirectory + let sound = directory.appendingPathComponent("stories-audio-test.wav") + let text = directory.appendingPathComponent("stories-audio-test.txt") + try wav.write(to: sound) + try Data("not a video".utf8).write(to: text) + defer { + try? FileManager.default.removeItem(at: sound) + try? FileManager.default.removeItem(at: text) + } + XCTAssertEqual(answer(sound.path), .some(true)) + XCTAssertNotEqual(answer(text.path), .some(true)) + } +} diff --git a/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift b/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift index a1933f7..1843b32 100644 --- a/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift +++ b/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift @@ -1148,6 +1148,10 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { StoriesAudio.shared.update(muted: muted) } + func storiesVideoHasAudio(source: String, completion: @escaping (Result) -> Void) { + StoriesVideoAudio.hasAudio(source: source) { completion(.success($0)) } + } + func endStoriesAudio() throws { StoriesAudio.shared.end() } diff --git a/ios/rees46_sdk/Sources/rees46_sdk/StoriesSupport.swift b/ios/rees46_sdk/Sources/rees46_sdk/StoriesSupport.swift index 4789c3b..1322944 100644 --- a/ios/rees46_sdk/Sources/rees46_sdk/StoriesSupport.swift +++ b/ios/rees46_sdk/Sources/rees46_sdk/StoriesSupport.swift @@ -30,6 +30,43 @@ enum StoriesSeenStore { } } +/// Whether a stories video has an audio track: the viewer shows its sound button only then, as +/// the web SDK does. The asset's tracks load off the main thread (a network video reads its +/// header over the network); the answer comes on the main queue, where Pigeon replies. +enum StoriesVideoAudio { + /// Reads whether the asset at the URL has an audio track. Tests replace it. + static var loader: (URL) async throws -> Bool = { url in + !(try await AVURLAsset(url: url).loadTracks(withMediaType: .audio)).isEmpty + } + + /// `http(s)` and `file` addresses as they are; anything else is a file path. + static func url(for source: String) -> URL? { + let lower = source.lowercased() + if lower.hasPrefix("http://") || lower.hasPrefix("https://") || lower.hasPrefix("file://") { + return URL(string: source) + } + return source.isEmpty ? nil : URL(fileURLWithPath: source) + } + + /// Answers `completion` on the main queue: `nil` when the source cannot be read. + static func hasAudio(source: String, completion: @escaping (Bool?) -> Void) { + guard let url = url(for: source) else { + DispatchQueue.main.async { completion(nil) } + return + } + let load = loader + Task.detached { + let answer: Bool? + do { + answer = try await load(url) + } catch { + answer = nil + } + DispatchQueue.main.async { completion(answer) } + } + } +} + /// The audio session while the stories viewer plays video. /// /// - `begin` saves the app's session before the first video, `end` puts it back when the diff --git a/ios/rees46_sdk/Sources/rees46_sdk/pigeon/PersonalizationApi.g.swift b/ios/rees46_sdk/Sources/rees46_sdk/pigeon/PersonalizationApi.g.swift index ac95163..61bdba6 100644 --- a/ios/rees46_sdk/Sources/rees46_sdk/pigeon/PersonalizationApi.g.swift +++ b/ios/rees46_sdk/Sources/rees46_sdk/pigeon/PersonalizationApi.g.swift @@ -4728,6 +4728,12 @@ protocol PersonalizationHostApi { /// The viewer closed: restores the session saved by [beginStoriesAudio] and stops /// watching the volume. iOS only; a no-op on Android. func endStoriesAudio() throws + /// Whether the video at [source] — an `http(s)` URL or a file path of the stories' + /// video cache — has an audio track: the stories viewer shows its sound button only + /// then, as the web SDK does. Read off the main thread from the container's track + /// list (Android `MediaMetadataRetriever`, iOS `AVURLAsset`); null when it cannot be + /// read. + func storiesVideoHasAudio(source: String, completion: @escaping (Result) -> Void) /// Opens the system settings where the user turns notifications on for the app: the /// app's notification settings on Android, the app's page in Settings on iOS. What the /// native popups do for their push-subscription button. @@ -6676,6 +6682,28 @@ class PersonalizationHostApiSetup { } else { endStoriesAudioChannel.setMessageHandler(nil) } + /// Whether the video at [source] — an `http(s)` URL or a file path of the stories' + /// video cache — has an audio track: the stories viewer shows its sound button only + /// then, as the web SDK does. Read off the main thread from the container's track + /// list (Android `MediaMetadataRetriever`, iOS `AVURLAsset`); null when it cannot be + /// read. + let storiesVideoHasAudioChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.storiesVideoHasAudio\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + storiesVideoHasAudioChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let sourceArg = args[0] as! String + api.storiesVideoHasAudio(source: sourceArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + storiesVideoHasAudioChannel.setMessageHandler(nil) + } /// Opens the system settings where the user turns notifications on for the app: the /// app's notification settings on Android, the app's page in Settings on iOS. What the /// native popups do for their push-subscription button. diff --git a/lib/src/pigeon/personalization_api.g.dart b/lib/src/pigeon/personalization_api.g.dart index 2d88389..36a9ae7 100644 --- a/lib/src/pigeon/personalization_api.g.dart +++ b/lib/src/pigeon/personalization_api.g.dart @@ -9250,6 +9250,38 @@ class PersonalizationHostApi { } } + /// Whether the video at [source] — an `http(s)` URL or a file path of the stories' + /// video cache — has an audio track: the stories viewer shows its sound button only + /// then, as the web SDK does. Read off the main thread from the container's track + /// list (Android `MediaMetadataRetriever`, iOS `AVURLAsset`); null when it cannot be + /// read. + Future storiesVideoHasAudio(String source) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.storiesVideoHasAudio$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [source], + ); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return (pigeonVar_replyList[0] as bool?); + } + } + /// Opens the system settings where the user turns notifications on for the app: the /// app's notification settings on Android, the app's page in Settings on iOS. What the /// native popups do for their push-subscription button. diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index bb5f3a9..61ddac4 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -272,6 +272,8 @@ class _PersonalizationStoryViewerState extends State super.initState(); WidgetsBinding.instance.addObserver(this); StoriesSound.instance.attach(); + // Новая лента, как веб, берёт выбор кнопки звука с устройства. + if (_playback.serverStart) unawaited(StoriesSound.instance.restore()); StoriesSound.instance.muted.addListener(_onMuted); widget.paused?.addListener(_onHostPause); _onHostPause(); @@ -679,6 +681,17 @@ class _PersonalizationStoryViewerState extends State /// Видео из кэша, а нет файла — сразу по сети, пока кэш заполняется в фоне: загрузка /// целиком не ждётся. Готово — когда плеер готов играть. + /// Новая лента: у видео живого слайда есть звук (или его не прочитать) — кнопка звука. + bool _videoSound = false; + + /// Звук видео захода [generation] из файла кэша [file] или по адресу [url]: кнопка + /// звука новой ленты — только у видео со звуком, как в вебе; не прочитать — есть. + Future _probeSound(String url, String? file, int generation) async { + final sound = await StoriesSound.instance.hasAudio(file ?? url); + if (!_current(generation) || _videoSound == (sound ?? true)) return; + setState(() => _videoSound = sound ?? true); + } + Future _loadVideo(String url, int generation) async { try { await StoriesSound.instance.beforeVideo(); @@ -704,6 +717,7 @@ class _PersonalizationStoryViewerState extends State _playback.useVideoDuration(video.value.duration); _videoReady = true; _videoPlaying = false; + if (_byType) unawaited(_probeSound(url, file?.path, generation)); _ready(generation); } catch (error) { debugPrint('PersonalizationStoryViewer: video $url — $error'); @@ -771,6 +785,7 @@ class _PersonalizationStoryViewerState extends State _video = null; _videoReady = false; _videoPlaying = false; + _videoSound = false; if (video == null) return; video.removeListener(_onVideo); video.dispose(); @@ -976,7 +991,7 @@ class _PersonalizationStoryViewerState extends State onClose: _close, onShare: _v3Code == null ? null : _share, shareLabel: _v3?.shareLabel ?? 'Share', - onToggleMute: StoriesSound.instance.toggle, + onToggleMute: () => StoriesSound.instance.toggle(remember: _byType), onSheet: _sheet, onButton: _button, onProduct: _product, @@ -992,6 +1007,7 @@ class _PersonalizationStoryViewerState extends State if (mounted) _setPaused(StoriesPauseReason.poll, held); }, v3: _byType, + hasAudio: live && _videoSound, onHeader: _header, ); } diff --git a/lib/src/ui/widgets/stories_sound.dart b/lib/src/ui/widgets/stories_sound.dart index d8367bb..e6b1a4b 100644 --- a/lib/src/ui/widgets/stories_sound.dart +++ b/lib/src/ui/widgets/stories_sound.dart @@ -1,12 +1,16 @@ +import 'dart:async'; + import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '../../pigeon/personalization_api.g.dart' as pigeon; /// Звук сторис на весь процесс. /// /// - При первом открытии звук выключен; выбор пользователя помнится до конца процесса и -/// переходит на следующие открытия ([muted]). +/// переходит на следующие открытия ([muted]). Просмотр новой ленты, как веб, ещё и +/// хранит выбор кнопки звука на устройстве ([restore], [toggle] с `remember`). /// - Кнопка громкости «вверх» включает звук: на Android клавиша сама доходит до /// Flutter ([HardwareKeyboard]), на iOS плагин следит за громкостью аудиосессии и /// сообщает о росте через `PersonalizationStoriesFlutterApi`. @@ -61,7 +65,42 @@ class StoriesSound implements pigeon.PersonalizationStoriesFlutterApi { ? _call(() => api.updateStoriesAudio(muted.value)) : Future.value(); - void toggle() => muted.value = !muted.value; + /// Ключ выбора кнопки звука на устройстве. + static const String mutedKey = 'personalization.stories.muted'; + + /// Кнопка звука: переключить; [remember] — сохранить выбор на устройстве. + void toggle({bool remember = false}) { + muted.value = !muted.value; + if (remember) unawaited(_remember(muted.value)); + } + + /// Взять выбор кнопки звука с устройства; его нет — звук как был. + Future restore() async { + try { + final stored = (await SharedPreferences.getInstance()).getBool(mutedKey); + if (stored != null) muted.value = stored; + } catch (error) { + debugPrint('PersonalizationStories: sound choice unavailable — $error'); + } + } + + static Future _remember(bool value) async { + try { + await (await SharedPreferences.getInstance()).setBool(mutedKey, value); + } catch (error) { + debugPrint('PersonalizationStories: sound choice not saved — $error'); + } + } + + /// Есть ли звук у видео [source] (адрес или файл кэша); не прочитать — `null`. + Future hasAudio(String source) async { + try { + return await api.storiesVideoHasAudio(source); + } catch (error) { + debugPrint('PersonalizationStories: audio of $source — $error'); + return null; + } + } @override void onStoriesVolumeUp() => muted.value = false; diff --git a/pigeons/personalization_api.dart b/pigeons/personalization_api.dart index d5fa646..1e066d9 100644 --- a/pigeons/personalization_api.dart +++ b/pigeons/personalization_api.dart @@ -2232,6 +2232,14 @@ abstract class PersonalizationHostApi { /// watching the volume. iOS only; a no-op on Android. void endStoriesAudio(); + /// Whether the video at [source] — an `http(s)` URL or a file path of the stories' + /// video cache — has an audio track: the stories viewer shows its sound button only + /// then, as the web SDK does. Read off the main thread from the container's track + /// list (Android `MediaMetadataRetriever`, iOS `AVURLAsset`); null when it cannot be + /// read. + @async + bool? storiesVideoHasAudio(String source); + /// Opens the system settings where the user turns notifications on for the app: the /// app's notification settings on Android, the app's page in Settings on iOS. What the /// native popups do for their push-subscription button. diff --git a/test/ui/stories_runtime_test.dart b/test/ui/stories_runtime_test.dart index 66e7f30..26b4d0a 100644 --- a/test/ui/stories_runtime_test.dart +++ b/test/ui/stories_runtime_test.dart @@ -1,5 +1,6 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; import 'package:rees46_sdk/src/personalization_sdk.dart' show PersonalizationStoryViewerBridge; @@ -38,6 +39,15 @@ class _FakeHostApi extends pigeon.PersonalizationHostApi { @override Future endStoriesAudio() async => audio.add('end'); + final List probed = []; + + @override + Future storiesVideoHasAudio(String source) async { + probed.add(source); + if (source.endsWith('broken.mp4')) throw PlatformException(code: 'x'); + return source.endsWith('sound.mp4'); + } + final List shares = []; @override @@ -102,6 +112,45 @@ void main() { expect(sound.muted.value, isTrue, reason: 'the choice outlives a viewer'); }); + test('the new feed keeps the sound button choice on the device', () async { + SharedPreferences.setMockInitialValues({}); + final sound = StoriesSound.instance; + addTearDown(() => sound.muted.value = true); + await sound.restore(); + expect(sound.muted.value, isTrue, reason: 'muted by default'); + sound.toggle(remember: true); + await Future.delayed(Duration.zero); + final preferences = await SharedPreferences.getInstance(); + expect(preferences.getBool(StoriesSound.mutedKey), isFalse); + sound.muted.value = true; + await sound.restore(); + expect(sound.muted.value, isFalse, reason: 'the stored choice'); + sound.toggle(); + await Future.delayed(Duration.zero); + expect( + preferences.getBool(StoriesSound.mutedKey), + isFalse, + reason: 'the old feed does not store it', + ); + }); + + test( + 'the audio of a video: the platform answers, a failure is unknown', + () async { + final api = _FakeHostApi(); + StoriesSound.api = api; + final sound = StoriesSound.instance; + expect(await sound.hasAudio('/cache/sound.mp4'), isTrue); + expect(await sound.hasAudio('https://cdn.example/mute.mp4'), isFalse); + expect(await sound.hasAudio('https://cdn.example/broken.mp4'), isNull); + expect(api.probed, [ + '/cache/sound.mp4', + 'https://cdn.example/mute.mp4', + 'https://cdn.example/broken.mp4', + ]); + }, + ); + test('share hands the link and the button frame to the platform', () async { final api = _FakeHostApi(); final sdk = PersonalizationSdk(api: api, shopId: 'shop-a'); From 2e5468b0de415abe2065adf27873a320ed8c7693 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 20 Nov 2026 13:32:06 +0400 Subject: [PATCH 06/24] fix(stories): the sound button's choice of stories over API v3 is kept on the device per shop, as the web SDK keeps it per site; a shop with no saved choice starts muted --- .../widgets/personalization_story_viewer.dart | 15 +++-- lib/src/ui/widgets/stories_sound.dart | 31 ++++++---- test/ui/stories_runtime_test.dart | 59 ++++++++++++------- test/ui/stories_v3_rules_test.dart | 28 +++++++++ 4 files changed, 95 insertions(+), 38 deletions(-) diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index 61ddac4..f1a85b6 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -273,7 +273,9 @@ class _PersonalizationStoryViewerState extends State WidgetsBinding.instance.addObserver(this); StoriesSound.instance.attach(); // Новая лента, как веб, берёт выбор кнопки звука с устройства. - if (_playback.serverStart) unawaited(StoriesSound.instance.restore()); + if (_playback.serverStart) { + unawaited(StoriesSound.instance.restore(_shopId)); + } StoriesSound.instance.muted.addListener(_onMuted); widget.paused?.addListener(_onHostPause); _onHostPause(); @@ -970,6 +972,10 @@ class _PersonalizationStoryViewerState extends State ); } + /// Магазин просмотра (`''` — без SDK): его ответы опросов и выбор кнопки звука. + String get _shopId => + widget.sdk == null ? '' : StoriesSeenStore.shopOf(widget.sdk!); + Widget _page(BuildContext context, int index) { final story = _playback.stories[index]; final live = _playback.entered && index == _playback.storyIndex; @@ -991,7 +997,8 @@ class _PersonalizationStoryViewerState extends State onClose: _close, onShare: _v3Code == null ? null : _share, shareLabel: _v3?.shareLabel ?? 'Share', - onToggleMute: () => StoriesSound.instance.toggle(remember: _byType), + onToggleMute: () => + StoriesSound.instance.toggle(rememberFor: _byType ? _shopId : null), onSheet: _sheet, onButton: _button, onProduct: _product, @@ -999,9 +1006,7 @@ class _PersonalizationStoryViewerState extends State onRetry: _retry, pollsTransport: _polls, pollTexts: _v3?.pollTexts ?? const StoryPollTexts(), - pollShopId: widget.sdk == null - ? '' - : StoriesSeenStore.shopOf(widget.sdk!), + pollShopId: _shopId, pollDid: widget.sdk == null ? '' : StoriesApiV3.knownDid(widget.sdk!), onPollHold: (held) { if (mounted) _setPaused(StoriesPauseReason.poll, held); diff --git a/lib/src/ui/widgets/stories_sound.dart b/lib/src/ui/widgets/stories_sound.dart index e6b1a4b..c4e2147 100644 --- a/lib/src/ui/widgets/stories_sound.dart +++ b/lib/src/ui/widgets/stories_sound.dart @@ -10,7 +10,8 @@ import '../../pigeon/personalization_api.g.dart' as pigeon; /// /// - При первом открытии звук выключен; выбор пользователя помнится до конца процесса и /// переходит на следующие открытия ([muted]). Просмотр новой ленты, как веб, ещё и -/// хранит выбор кнопки звука на устройстве ([restore], [toggle] с `remember`). +/// хранит выбор кнопки звука на устройстве — у каждого магазина свой, как у веба у +/// каждого сайта ([restore], [toggle] с `rememberFor`). /// - Кнопка громкости «вверх» включает звук: на Android клавиша сама доходит до /// Flutter ([HardwareKeyboard]), на iOS плагин следит за громкостью аудиосессии и /// сообщает о росте через `PersonalizationStoriesFlutterApi`. @@ -65,28 +66,34 @@ class StoriesSound implements pigeon.PersonalizationStoriesFlutterApi { ? _call(() => api.updateStoriesAudio(muted.value)) : Future.value(); - /// Ключ выбора кнопки звука на устройстве. - static const String mutedKey = 'personalization.stories.muted'; + /// Ключ выбора кнопки звука магазина [shopId] на устройстве. + static String mutedKey(String shopId) => + 'personalization.stories.muted.$shopId'; - /// Кнопка звука: переключить; [remember] — сохранить выбор на устройстве. - void toggle({bool remember = false}) { + /// Кнопка звука: переключить; [rememberFor] — магазин, для которого сохранить выбор на + /// устройстве (`null` — не сохранять). + void toggle({String? rememberFor}) { muted.value = !muted.value; - if (remember) unawaited(_remember(muted.value)); + if (rememberFor != null) unawaited(_remember(rememberFor, muted.value)); } - /// Взять выбор кнопки звука с устройства; его нет — звук как был. - Future restore() async { + /// Взять выбор кнопки звука магазина [shopId] с устройства; его нет — звук выключен, + /// как у веба. Устройство не ответило — звук как был. + Future restore(String shopId) async { try { - final stored = (await SharedPreferences.getInstance()).getBool(mutedKey); - if (stored != null) muted.value = stored; + final preferences = await SharedPreferences.getInstance(); + muted.value = preferences.getBool(mutedKey(shopId)) ?? true; } catch (error) { debugPrint('PersonalizationStories: sound choice unavailable — $error'); } } - static Future _remember(bool value) async { + static Future _remember(String shopId, bool value) async { try { - await (await SharedPreferences.getInstance()).setBool(mutedKey, value); + await (await SharedPreferences.getInstance()).setBool( + mutedKey(shopId), + value, + ); } catch (error) { debugPrint('PersonalizationStories: sound choice not saved — $error'); } diff --git a/test/ui/stories_runtime_test.dart b/test/ui/stories_runtime_test.dart index 26b4d0a..6f49e51 100644 --- a/test/ui/stories_runtime_test.dart +++ b/test/ui/stories_runtime_test.dart @@ -112,27 +112,44 @@ void main() { expect(sound.muted.value, isTrue, reason: 'the choice outlives a viewer'); }); - test('the new feed keeps the sound button choice on the device', () async { - SharedPreferences.setMockInitialValues({}); - final sound = StoriesSound.instance; - addTearDown(() => sound.muted.value = true); - await sound.restore(); - expect(sound.muted.value, isTrue, reason: 'muted by default'); - sound.toggle(remember: true); - await Future.delayed(Duration.zero); - final preferences = await SharedPreferences.getInstance(); - expect(preferences.getBool(StoriesSound.mutedKey), isFalse); - sound.muted.value = true; - await sound.restore(); - expect(sound.muted.value, isFalse, reason: 'the stored choice'); - sound.toggle(); - await Future.delayed(Duration.zero); - expect( - preferences.getBool(StoriesSound.mutedKey), - isFalse, - reason: 'the old feed does not store it', - ); - }); + test( + 'the new feed keeps the sound button choice on the device per shop', + () async { + SharedPreferences.setMockInitialValues({}); + final sound = StoriesSound.instance; + addTearDown(() => sound.muted.value = true); + await sound.restore('shop-a'); + expect(sound.muted.value, isTrue, reason: 'muted by default'); + sound.toggle(rememberFor: 'shop-a'); + await Future.delayed(Duration.zero); + final preferences = await SharedPreferences.getInstance(); + expect( + StoriesSound.mutedKey('shop-a'), + 'personalization.stories.muted.shop-a', + ); + expect(preferences.getBool(StoriesSound.mutedKey('shop-a')), isFalse); + sound.muted.value = true; + await sound.restore('shop-a'); + expect(sound.muted.value, isFalse, reason: 'the stored choice'); + + await sound.restore('shop-b'); + expect( + sound.muted.value, + isTrue, + reason: 'another shop has its own choice: none — muted, as the web', + ); + expect(preferences.getBool(StoriesSound.mutedKey('shop-b')), isNull); + + sound.toggle(); + await Future.delayed(Duration.zero); + expect( + preferences.getBool(StoriesSound.mutedKey('shop-b')), + isNull, + reason: 'the old feed does not store it', + ); + expect(preferences.getBool(StoriesSound.mutedKey('shop-a')), isFalse); + }, + ); test( 'the audio of a video: the platform answers, a failure is unknown', diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index 4572c2c..1fa63df 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -12,6 +12,8 @@ import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_slide_view.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_sound.dart'; +import 'package:shared_preferences/shared_preferences.dart'; const String _code = 'block'; @@ -448,6 +450,32 @@ void main() { await slide(tester, v3: false, hasAudio: false); expect(button, findsOneWidget); }); + + testWidgets('the new feed takes the choice saved for its own shop', ( + tester, + ) async { + final sound = StoriesSound.instance; + addTearDown(() => sound.muted.value = true); + stories.add(_story(1, >[_slide('10')])); + + SharedPreferences.setMockInitialValues({ + StoriesSound.mutedKey('shop'): false, + }); + await bar(tester); + await open(tester, 'Story 1'); + expect(sound.muted.value, isFalse, reason: 'saved for this shop'); + await close(tester); + + SharedPreferences.setMockInitialValues({ + StoriesSound.mutedKey('other'): false, + }); + await open(tester, 'Story 1'); + expect( + sound.muted.value, + isTrue, + reason: 'nothing saved for this shop: muted, as the web', + ); + }); }); group('taps and events', () { From b9abd335c89400f774943aa36b9448253cc1ccc7 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 20 Nov 2026 13:36:38 +0400 Subject: [PATCH 07/24] docs(readme): the shared links of stories over API v3 leave the README, as v3 stays behind its gate; the text lives in the pull request --- README.md | 32 -------------------------------- 1 file changed, 32 deletions(-) diff --git a/README.md b/README.md index 2efbe90..2be83b6 100644 --- a/README.md +++ b/README.md @@ -938,38 +938,6 @@ same values, and fails with the released error codes. Their replacements: | `getStoredPushToken`, `setPushNotificationCallbacks` | `notifications.getPushToken`, `notifications.setCallbacks` | | `trackEvent`, `trackPurchase` | `tracking.custom`, `tracking.purchase` | -## Stories over API v3: shared links - -Stories over API v3 are behind the v3 gate: not part of the public API yet, reached -only through `package:rees46_sdk/src/v3/personalization_v3.dart`. - -The "Share" button of a slide shares a link to the shop's site: - -``` -https:///?r46_stories=&r46_story=[&r46_slide=] -``` - -To open such a link in the app instead of the browser, the app claims the shop's domain: - -- iOS — Universal Links: the `Associated Domains` capability with - `applinks:`, and `https:///.well-known/apple-app-site-association` - listing the app (`.`) and the paths of the links. -- Android — App Links: an `intent-filter` with `android:autoVerify="true"` for - `https://` on the activity that opens links, and - `https:///.well-known/assetlinks.json` with the app's package name and the - SHA-256 fingerprint of its signing certificate. - -The app gets the URL as any deep link (for example through its router or an app-links -plugin) and hands it over: - -```dart -// ignore: implementation_imports -import 'package:rees46_sdk/src/v3/personalization_v3.dart'; - -final handled = PersonalizationStoriesV3.handleLink(context, url); -// false — not a stories link (or no apiV3Domain): open it as usual. -``` - ## Example app A full demo — tracking, recommendations, search, catalog, loyalty, popups, push From 6046900727cfb5a0a8faf0c09227280ba0742808 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Fri, 20 Nov 2026 13:40:25 +0400 Subject: [PATCH 08/24] feat(stories): stories over API v3 skip a slide that is neither image nor video and has no product element, as the web SDK does (no view, going forward and back passes it, a story of such slides only is not shown), and a product slide without buttons has no More info button, as the web; the old feed keeps both --- .../widgets/personalization_story_viewer.dart | 3 +- lib/src/ui/widgets/stories_playback.dart | 52 +++++++-- lib/src/ui/widgets/stories_slide_view.dart | 13 ++- test/ui/stories_v3_rules_test.dart | 100 +++++++++++++++++- 4 files changed, 147 insertions(+), 21 deletions(-) diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index f1a85b6..80fa68d 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -138,7 +138,8 @@ class PersonalizationStoryViewer extends StatefulWidget { /// Промокод скопирован. final ValueChanged? onPromoCopied; - /// Подпись кнопки товарного слайда, когда у слайда своих кнопок нет. + /// Подпись кнопки товарного слайда старой ленты, когда у слайда своих кнопок нет; у + /// новой ленты, как в вебе, такой кнопки нет. final String productButtonText; /// Подпись над промокодом, когда в админке у товара нет своей. diff --git a/lib/src/ui/widgets/stories_playback.dart b/lib/src/ui/widgets/stories_playback.dart index 6ecb38b..c6c0807 100644 --- a/lib/src/ui/widgets/stories_playback.dart +++ b/lib/src/ui/widgets/stories_playback.dart @@ -87,6 +87,12 @@ abstract final class StoriesServerProgress { } } +/// Слайд новой ленты, который не показывается, как в вебе: не фото и не видео, и без +/// элемента товара (`product`) — его пропускают по ходу листания, без `view`. +bool storySlideSkipped(StorySlide slide) => + slide.type == StorySlideType.product && + !slide.elements.any((element) => element is StoryProductElement); + /// Логика просмотра сторис без UI: какая сторис и какой слайд текущие, с какого слайда /// открывать сторис, почему слайд стоит, открыта ли шторка, сколько прошло времени. /// @@ -108,9 +114,11 @@ abstract final class StoriesServerProgress { /// Новая лента ([serverStart]), как в вебе: сторис открывается со слайда /// [StoriesServerProgress.startOf], просмотренной становится, когда с неё ушли вперёд /// (досмотрели последний слайд или перелистнули на следующую); просмотренное устройства не -/// решает. +/// решает. Слайды без медиа и без товара пропускаются ([storySlideSkipped]): листание +/// идёт мимо них в свою сторону, сторис открывается с ближайшего показываемого слайда +/// после стартового (после него нет — с первого показываемого). /// -/// Сторис без слайдов отбрасываются при создании. +/// Сторис без слайдов (у новой ленты — без показываемых) отбрасываются при создании. class StoriesPlayback { /// [initialSlide] — слайд начальной сторис в обход правил стартового слайда (ссылка /// «Поделиться» открывает слайд ссылки); действует до первого захода на неё. @@ -121,7 +129,7 @@ class StoriesPlayback { Map> seen = const >{}, this.serverStart = false, }) : stories = List.unmodifiable( - stories.where((story) => story.slides.isNotEmpty), + stories.where((story) => _playable(story, serverStart)), ), _seen = >{ for (final entry in seen.entries) entry.key: {...entry.value}, @@ -129,12 +137,30 @@ class StoriesPlayback { // Начальный индекс дан по исходному списку: сторис без слайдов перед ним выпали. var kept = 0; for (var i = 0; i < stories.length && i < initialStory; i++) { - if (stories[i].slides.isNotEmpty) kept++; + if (_playable(stories[i], serverStart)) kept++; } _story = this.stories.isEmpty ? 0 : kept.clamp(0, this.stories.length - 1); _initialSlide = this.stories.isEmpty ? null : initialSlide; } + /// Сторис есть что показать: у новой ленты — хоть один не пропускаемый слайд. + static bool _playable(Story story, bool serverStart) => serverStart + ? story.slides.any((slide) => !storySlideSkipped(slide)) + : story.slides.isNotEmpty; + + /// Слайд [index] сторис [story] показывается (у новой ленты — не пропускается). + bool _shown(Story story, int index) => + !serverStart || !storySlideSkipped(story.slides[index]); + + /// Ближайший показываемый слайд [story] от [from] в сторону [step] (+1 / −1); нет — + /// `null`. + int? _nearest(Story story, int from, int step) { + for (var i = from; i >= 0 && i < story.slides.length; i += step) { + if (_shown(story, i)) return i; + } + return null; + } + /// Сторис со слайдами в порядке ленты. final List stories; @@ -225,11 +251,15 @@ class StoriesPlayback { int startSlideFor(int index) { final story = stories[index]; final initial = _initialSlide; + final int start; if (initial != null && index == _story && !_entered) { - return initial.clamp(0, story.slides.length - 1); + start = initial.clamp(0, story.slides.length - 1); + } else if (serverStart) { + start = StoriesServerProgress.startOf(story); + } else { + return startSlideOf(story, _seen[story.id] ?? const {}); } - if (serverStart) return StoriesServerProgress.startOf(story); - return startSlideOf(story, _seen[story.id] ?? const {}); + return _nearest(story, start, 1) ?? _nearest(story, 0, 1) ?? start; } /// Страница осела на сторис [index] (листанием, программно или при открытии). @@ -255,8 +285,8 @@ class StoriesPlayback { /// Вперёд: следующий слайд, следующая сторис или закрыть. StoriesStep next() { if (!_entered || _sheet || _turnTarget != null) return StoriesStep.none; - if (_slide < story.slides.length - 1) { - _slide++; + if (_nearest(story, _slide + 1, 1) case final following?) { + _slide = following; _enter(); return StoriesStep.slide; } @@ -271,8 +301,8 @@ class StoriesPlayback { /// Назад: предыдущий слайд, предыдущая сторис или перезапуск первого слайда. StoriesStep previous() { if (!_entered || _sheet || _turnTarget != null) return StoriesStep.none; - if (_slide > 0) { - _slide--; + if (_nearest(story, _slide - 1, -1) case final before?) { + _slide = before; _enter(); return StoriesStep.slide; } diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index c13ff11..7e2646d 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -559,9 +559,10 @@ class StorySlideView extends StatelessWidget { /// Товарный слайд: шапка (бренд SemiBold 20, название SemiBold 16, межстрочный 140%, /// шаг 8), белая карточка картинки (скругление 12, поля 16, квадрат по ширине — на - /// низком экране ужимается), цена, кнопки слайда; без своих кнопок — одна - /// [PersonalizationStoryViewer.productButtonText], ведёт к товару. Товар открывают - /// только кнопки: шапка и картинка не нажимаются, касание по ним листает, как по слайду. + /// низком экране ужимается), цена, кнопки слайда; без своих кнопок у старой ленты — одна + /// [PersonalizationStoryViewer.productButtonText], ведёт к товару, у новой, как в вебе, + /// — никакой. Товар открывают только кнопки: шапка и картинка не нажимаются, касание по + /// ним листает, как по слайду. Widget _productContent( BuildContext context, StorySlide slide, @@ -574,6 +575,8 @@ class StorySlideView extends StatelessWidget { final price = storyPriceOf(product, slidePromo: storySlidePromocode(slide)); final image = storyImage(product.image, config.imageProvider); final buttons = storyButtons(slide); + // Кнопка кита «к товару» вместо своих — только у старой ленты: в вебе её нет. + final more = buttons.isEmpty && !v3; TextStyle header(double size) => TextStyle( fontSize: size, @@ -649,7 +652,7 @@ class StorySlideView extends StatelessWidget { ), if (buttons.isNotEmpty) _primaryButtons(buttons) - else + else if (more) Padding( padding: const EdgeInsets.only(top: 16), child: PersonalizationButton( @@ -666,7 +669,7 @@ class StorySlideView extends StatelessWidget { slide, bottom: (_hasRow(slide) ? 64 : 16) + - math.max(1, buttons.length) * _buttonSpace(context), + (more ? 1 : buttons.length) * _buttonSpace(context), ); return Stack( fit: StackFit.expand, diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index 1fa63df..7162ef3 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -310,12 +310,12 @@ void main() { }); group('slides', () { - // The slide's own box: the nearest coloured box around its text. - Color? slideColor(WidgetTester tester) => tester + // The slide's own box: the nearest coloured box around its [text]. + Color? slideColor(WidgetTester tester, [String text = 'Slide ']) => tester .widget( find .ancestor( - of: find.textContaining('Slide '), + of: find.textContaining(text), matching: find.byType(ColoredBox), ) .first, @@ -332,13 +332,14 @@ void main() { type: '', background: 'https://cdn.example/a.jpg', color: '#112233', + elements: >[_product('p1')], ), ]), _story(2, >[_slide('20', color: '#445566')]), ]); await bar(tester); await open(tester, 'Story 1'); - expect(slideColor(tester), const Color(0xFF112233)); + expect(slideColor(tester, 'Product p1'), const Color(0xFF112233)); expect( find.descendant( of: find.byType(PersonalizationStoryViewer), @@ -557,6 +558,37 @@ void main() { }, ); + testWidgets('a product slide without buttons: no More info, as the web', ( + tester, + ) async { + stories.add( + _story(1, >[ + _slide( + '10', + type: '', + duration: 30, + elements: >[_product('p1')], + ), + ]), + ); + await bar(tester); + await open(tester, 'Story 1'); + expect(find.text('Product p1'), findsOneWidget); + expect(find.text('More info'), findsNothing); + await close(tester); + + await bar(tester, v3: false); + await open(tester, 'Story 1'); + expect( + find.text('More info'), + findsOneWidget, + reason: 'the old feed keeps the kit button', + ); + await tester.tap(find.text('More info')); + await settle(tester); + expect(products, ['p1']); + }); + testWidgets('copying a promo code sends no click', (tester) async { tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, @@ -587,4 +619,64 @@ void main() { await tester.pump(const Duration(seconds: 3)); }); }); + group('a slide with no media and no product is skipped, as the web', () { + Map skipped(String id) => + _slide(id, type: '', duration: 30, color: '#112233'); + + testWidgets('going forward and back passes it, with no view', ( + tester, + ) async { + stories.add( + _story(1, >[ + _slide('10', duration: 30), + skipped('11'), + _slide('12', duration: 30), + ]), + ); + await bar(tester); + await open(tester, 'Story 1'); + final viewer = tester.getRect(find.byType(PersonalizationStoryViewer)); + await tester.tapAt(Offset(viewer.right - 10, viewer.center.dy)); + await settle(tester); + expect(find.text('Slide 12'), findsOneWidget); + await tester.tapAt(Offset(viewer.left + 10, viewer.center.dy)); + await settle(tester); + expect(find.text('Slide 10'), findsOneWidget); + expect(sent(), ['view 1/10', 'view 1/12', 'view 1/10']); + }); + + testWidgets('a story opens past it; a story of such slides only is not ' + 'shown', (tester) async { + stories.addAll(>[ + _story(1, >[skipped('10')]), + _story(2, >[ + _slide('20', duration: 30), + skipped('21'), + _slide('22', duration: 30), + ], start: 1), + ]); + await bar(tester); + await open(tester, 'Story 2'); + expect(find.text('Slide 22'), findsOneWidget); + await close(tester); + await open(tester, 'Story 1'); + expect(find.text('Slide 22'), findsOneWidget, reason: 'the next story'); + expect(sent(), ['view 2/22', 'view 2/22']); + }); + + testWidgets('the old feed shows it', (tester) async { + stories.add( + _story(1, >[ + _slide('10', duration: 30), + skipped('11'), + ]), + ); + await bar(tester, v3: false); + await open(tester, 'Story 1'); + final viewer = tester.getRect(find.byType(PersonalizationStoryViewer)); + await tester.tapAt(Offset(viewer.right - 10, viewer.center.dy)); + await settle(tester); + expect(find.text('Slide 11'), findsOneWidget); + }); + }); } From ee378c3fbef179d2161b99c6844ef7fcb90b6866 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 13:39:43 +0400 Subject: [PATCH 09/24] =?UTF-8?q?fix(stories):=20a=20story=20over=20API=20?= =?UTF-8?q?v3=20with=20nothing=20to=20show=20from=20its=20start=20is=20fin?= =?UTF-8?q?ished=20as=20the=20web=20SDK=20finishes=20it=20=E2=80=94=20view?= =?UTF-8?q?ed,=20the=20next=20story=20opens,=20after=20the=20last=20one=20?= =?UTF-8?q?the=20viewer=20closes;=20a=20story=20of=20skipped=20slides=20on?= =?UTF-8?q?ly=20stays=20in=20the=20bar,=20opening=20it=20passes=20on,=20an?= =?UTF-8?q?d=20an=20empty=20viewer=20is=20never=20shown=20(show,=20handleL?= =?UTF-8?q?ink=20and=20a=20swipe=20onto=20it=20too);=20a=20link's=20slide?= =?UTF-8?q?=20only=20sets=20the=20first=20open,=20then=20the=20story=20sta?= =?UTF-8?q?rts=20where=20it=20was=20left,=20and=20shared=5Fopen=20carries?= =?UTF-8?q?=20the=20slide=20it=20opened=20at?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ui/widgets/personalization_stories.dart | 78 ++++++--- .../widgets/personalization_stories_v3.dart | 14 +- .../widgets/personalization_story_viewer.dart | 28 ++- lib/src/ui/widgets/stories_playback.dart | 165 ++++++++++++++---- test/ui/stories_playback_test.dart | 128 +++++++++++++- test/ui/stories_v3_rules_test.dart | 142 ++++++++++++++- 6 files changed, 476 insertions(+), 79 deletions(-) diff --git a/lib/src/ui/widgets/personalization_stories.dart b/lib/src/ui/widgets/personalization_stories.dart index 1b50981..a0a8ce5 100644 --- a/lib/src/ui/widgets/personalization_stories.dart +++ b/lib/src/ui/widgets/personalization_stories.dart @@ -380,49 +380,57 @@ Future _openLink( } if (!context.mounted) return; final story = stories.first; - // Слайд ссылки, если он есть в ответе: `start_position` сервер ставит только по своим - // слайдам, виртуальные слайды товарных кампаний (`39_2`) он не знает. + // Слайд ссылки, если он есть в ответе, — слайд первого открытия: `start_position` + // сервер ставит только по своим слайдам, виртуальные слайды товарных кампаний (`39_2`) + // он не знает. Дальше, как у любой сторис, — где остановились. final linked = link.slideId == null ? -1 : story.slides.indexWhere((slide) => slide.id == link.slideId); - final start = linked >= 0 - ? linked - : story.startPosition.clamp(0, story.slides.length - 1); var opened = false; + // `shared_open` — один раз, после показа, как в вебе: кампания ссылки и слайд, с + // которого её открыли (досмотрена сразу — с начала). + void sharedOpen([StorySlide? shown]) { + if (opened) return; + opened = true; + unawaited( + StoriesApiV3.track( + resolved, + v3.apiV3Domain!, + code: link.code, + event: StoriesV3Event.sharedOpen, + storyId: story.id, + slideId: + (shown ?? story.slides[StoriesServerProgress.startOf(story)]).id, + ), + ); + } + _closeOpenViewer(); - await _present( + final shown = await _present( context, config: config, v3: v3, sdk: resolved, stories: stories, index: 0, - initialSlide: start, + initialSlide: linked >= 0 ? linked : null, controller: controller, onRoute: (route) => _openLinks[link.key] = route, - onSlideShown: (_, _) { - // `shared_open` — один раз, после показа: кампания и слайд, с которого начали. - if (opened) return; - opened = true; - unawaited( - StoriesApiV3.track( - resolved, - v3.apiV3Domain!, - code: link.code, - event: StoriesV3Event.sharedOpen, - storyId: story.id, - slideId: story.slides[start].id, - ), - ); - }, + onSlideShown: (shownStory, slide) => sharedOpen( + identical(shownStory, story) ? shownStory.slides[slide] : null, + ), ); + // Показать было нечего — просмотр не открывался, а кампанию всё равно открыли. + if (!shown) sharedOpen(); } // Открыть просмотр [stories] со сторис [index] поверх корневого навигатора; тексты и // колбэки — из [config], режим API v3 — из [v3] (`null` — его нет). Пока просмотр // открыт, [controller] ставит его на паузу и листает. Завершается, когда просмотр -// закроют. -Future _present( +// закроют: `true`. Новая лента открывает сторис по правилам веба +// ([StoriesServerProgress.open]): [initialSlide] — слайд её первого открытия; открыть +// нечего (сторис с [index] досмотрены) — просмотр не открывается, `false`. +Future _present( BuildContext context, { required PersonalizationStories config, required StoriesV3Options? v3, @@ -434,11 +442,28 @@ Future _present( void Function(Story story, int slideIndex)? onSlideShown, ValueChanged>? onRoute, }) async { + var start = index; + var slide = initialSlide; + if (StoriesApiV3.host(v3?.apiV3Domain) != null) { + // Как в вебе: сторис, которую показать нечем, досмотрена — просмотрена, открывается + // следующая; после последней пустой просмотр не открывается. + final story = stories[index]; + if (slide != null) { + StoriesServerProgress.showed( + story, + slide.clamp(0, story.slides.length - 1), + ); + slide = null; + } + final opened = StoriesServerProgress.open(stories, index); + if (opened == null) return false; + start = opened; + } final session = controller?._begin(stories); Widget viewer = PersonalizationStoryViewer( stories: stories, - initialStory: index, - initialSlide: initialSlide, + initialStory: start, + initialSlide: slide, seen: sdk == null ? const >{} : StoriesSeenStore.instance.seen(sdk), @@ -485,6 +510,7 @@ Future _present( if (_openViewer == route) _openViewer = null; if (session != null) controller?._end(session); } + return true; } /// SDK по [sdk] или [shopId]. Магазин ещё не зарегистрирован — ждём регистрации до diff --git a/lib/src/ui/widgets/personalization_stories_v3.dart b/lib/src/ui/widgets/personalization_stories_v3.dart index e690c23..2594048 100644 --- a/lib/src/ui/widgets/personalization_stories_v3.dart +++ b/lib/src/ui/widgets/personalization_stories_v3.dart @@ -16,7 +16,9 @@ part of 'personalization_stories.dart'; /// /// Сторис с API v3 ведут себя, как в веб-SDK: открываются со слайда `start_position` /// сервера (за сессию — где остановились), просмотренной сторис становится по `viewed` -/// сервера или когда с неё ушли вперёд; медиа решает тип слайда, слайд без медиа — цвета +/// сервера или когда с неё ушли вперёд; слайд не фото, не видео и без товара +/// пропускается, сторис из таких слайдов остаётся в ленте, а открыть её — досмотреть: +/// она просмотрена и открывается следующая; медиа решает тип слайда, слайд без медиа — цвета /// `background_color`; шапка `header` рисуется, её нажатие — `click` и её ссылка; кнопка /// без ссылки — только `click`; копирование промокода `click` не шлёт; кнопка звука — /// только у видео со звуком, выбор звука помнится на устройстве; «Поделиться» отдаёт @@ -105,10 +107,12 @@ class PersonalizationStoriesV3 extends StatelessWidget { /// `false` — не ссылка сторис или API v3 выключен (нет ни `apiV3Domain`, ни /// глобального [apiV3Domain]): ничего не делает. `true` — дальше асинхронно: дождаться /// SDK (как [PersonalizationStories.show]), загрузить кампанию ссылки (`/story/{id}` - /// API v3), закрыть открытый просмотр V2 и открыть свой — с первой сторис ответа, со - /// слайда ссылки (`r46_slide`), если он есть в ответе, иначе со слайда - /// `start_position`; в обход правила «первый непросмотренный». После показа один раз — - /// событие `shared_open` со слайдом, с которого начали. Ошибка, 404, пустой ответ или + /// API v3), закрыть открытый просмотр V2 и открыть свой — с первой сторис ответа. + /// Слайд ссылки (`r46_slide`), если он есть в ответе, иначе `start_position`, — только + /// слайд её первого открытия: дальше она открывается, как любая сторис API v3, — где + /// остановились; показать с него нечего — она досмотрена и открывается следующая, а + /// пустой просмотр не открывается. Один раз — событие `shared_open` со слайдом, с + /// которого её открыли (досмотрена сразу — с первым). Ошибка, 404, пустой ответ или /// дольше 15 с — [onError], ничего не показывается, событий нет. Та же ссылка, пока /// прежняя грузится или её просмотр открыт, — ничего, но `true`. Тексты, колбэки и /// [controller] — как у [PersonalizationStories.show], остальное — как у diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index 80fa68d..581e379 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -102,7 +102,8 @@ class PersonalizationStoryViewer extends StatefulWidget { final int initialStory; /// Слайд начальной сторис в обход правила «первый непросмотренный»; `null` — по - /// правилам. Так ссылка «Поделиться» открывает свой слайд. + /// правилам. Так ссылка «Поделиться» открывает свой слайд. У новой ленты — только слайд + /// первого открытия: дальше сторис открывается по её правилам. final int? initialSlide; /// Уже просмотренные слайды: id слайдов по id сторис. По ним выбирается стартовый слайд @@ -283,8 +284,11 @@ class _PersonalizationStoryViewerState extends State _requests = widget.storyRequests?.listen(_onStoryRequest); _onLifecycle(WidgetsBinding.instance.lifecycleState); // Первая страница осела сразу: заход после кадра — загрузка картинки читает контекст. + // Показать нечего (у новой ленты все сторис с начальной досмотрены) — просмотр + // закрывается, пустым он не стоит. WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted && !_playback.isEmpty) _settled(_playback.storyIndex); + if (!mounted) return; + _playback.isEmpty ? _close() : _settled(_playback.storyIndex); }); } @@ -406,12 +410,19 @@ class _PersonalizationStoryViewerState extends State // --- Навигация ---------------------------------------------------------------------- - /// Страница осела на [index]: заход на сторис или просто конец листания. + /// Страница осела на [index]: заход на сторис, просто конец листания или — у новой + /// ленты на сторис, которую не открыть, — листание дальше или закрытие. void _settled(int index) { - if (_playback.settle(index)) { - _entered(); - } else { - _sync(); + switch (_playback.settle(index)) { + case StoriesStep.slide: + _entered(); + case StoriesStep.none: + _sync(); + case final step: + // Не посреди уведомления прокрутки: листание и закрытие — следом. + scheduleMicrotask(() { + if (mounted) _step(step); + }); } setState(() {}); } @@ -925,7 +936,8 @@ class _PersonalizationStoryViewerState extends State @override Widget build(BuildContext context) { - if (_playback.isEmpty) return const ColoredBox(color: Color(0xFF000000)); + // Показать нечего — просмотр закрывается после кадра; пустого экрана нет. + if (_playback.isEmpty) return const SizedBox.shrink(); final sheet = _playback.sheetOpen; return PopScope( // Системное «назад» сперва сворачивает шторку товаров. diff --git a/lib/src/ui/widgets/stories_playback.dart b/lib/src/ui/widgets/stories_playback.dart index c6c0807..734823e 100644 --- a/lib/src/ui/widgets/stories_playback.dart +++ b/lib/src/ui/widgets/stories_playback.dart @@ -76,7 +76,8 @@ abstract final class StoriesServerProgress { /// Сторис просмотрена: так говорит сервер или с неё ушли вперёд. static bool viewedOf(Story story) => story.viewed || (_left[story] ?? false); - /// Показан слайд [slide] сторис [story]. + /// Показан слайд [slide] сторис [story]; так же ставится и слайд, с которого её + /// откроют в первый раз (ссылка «Поделиться»). static void showed(Story story, int slide) => _positions[story] = slide; /// С [story] ушли вперёд: просмотрена; [finished] — досмотрели до конца, в следующий @@ -85,6 +86,28 @@ abstract final class StoriesServerProgress { _left[story] = true; if (finished) _positions[story] = 0; } + + /// Слайд, с которого [story] откроется: показываемый ([storySlideSkipped]) с её + /// стартового ([startOf]) и дальше; после стартового показывать нечего — `null`, + /// открыть её — значит досмотреть. + static int? openingSlideOf(Story story) { + for (var i = startOf(story); i < story.slides.length; i++) { + if (!storySlideSkipped(story.slides[i])) return i; + } + return null; + } + + /// Открыть сторис [index] из [stories], как в вебе: сторис, у которой с её стартового + /// слайда показывать нечего, досмотрена — просмотрена, в следующий раз с начала, — и + /// открывается следующая, и так далее. Сторис, которую откроют, — её индекс; дошли до + /// конца ленты — `null`, просмотр закрывается (или не открывается). + static int? open(List stories, int index) { + for (var i = index < 0 ? 0 : index; i < stories.length; i++) { + if (openingSlideOf(stories[i]) != null) return i; + leftForward(stories[i], finished: true); + } + return null; + } } /// Слайд новой ленты, который не показывается, как в вебе: не фото и не видео, и без @@ -114,11 +137,19 @@ bool storySlideSkipped(StorySlide slide) => /// Новая лента ([serverStart]), как в вебе: сторис открывается со слайда /// [StoriesServerProgress.startOf], просмотренной становится, когда с неё ушли вперёд /// (досмотрели последний слайд или перелистнули на следующую); просмотренное устройства не -/// решает. Слайды без медиа и без товара пропускаются ([storySlideSkipped]): листание -/// идёт мимо них в свою сторону, сторис открывается с ближайшего показываемого слайда -/// после стартового (после него нет — с первого показываемого). +/// решает. Слайды без медиа и без товара пропускаются ([storySlideSkipped]): их дуга +/// прогресса остаётся и заполняется сразу; вперёд листание идёт мимо них, назад — +/// перешагивает их (в вебе назад на такой слайд отбрасывает вперёд снова). Сторис +/// открывается с ближайшего показываемого слайда от стартового; после него показывать +/// нечего — сторис досмотрена: просмотрена и открывается следующая, а после последней +/// просмотр закрывается ([StoriesServerProgress.open]). Сторис, где не показывается ни +/// один слайд, остаётся в ленте: открыть её — то же самое. Пустого просмотра нет: +/// открывать нечего — [isEmpty]. Назад на первом показываемом слайде первой сторис, как в +/// вебе, закрывает просмотр; назад в сторис, которую не открыть, перешагивает её. +/// [initialSlide] у новой ленты не обходит правила, а только ставит слайд первого +/// открытия начальной сторис — дальше, как у любой, где остановились. /// -/// Сторис без слайдов (у новой ленты — без показываемых) отбрасываются при создании. +/// Сторис без слайдов отбрасываются при создании. class StoriesPlayback { /// [initialSlide] — слайд начальной сторис в обход правил стартового слайда (ссылка /// «Поделиться» открывает слайд ссылки); действует до первого захода на неё. @@ -129,7 +160,7 @@ class StoriesPlayback { Map> seen = const >{}, this.serverStart = false, }) : stories = List.unmodifiable( - stories.where((story) => _playable(story, serverStart)), + stories.where((story) => story.slides.isNotEmpty), ), _seen = >{ for (final entry in seen.entries) entry.key: {...entry.value}, @@ -137,16 +168,35 @@ class StoriesPlayback { // Начальный индекс дан по исходному списку: сторис без слайдов перед ним выпали. var kept = 0; for (var i = 0; i < stories.length && i < initialStory; i++) { - if (_playable(stories[i], serverStart)) kept++; + if (stories[i].slides.isNotEmpty) kept++; } _story = this.stories.isEmpty ? 0 : kept.clamp(0, this.stories.length - 1); - _initialSlide = this.stories.isEmpty ? null : initialSlide; + if (this.stories.isEmpty) return; + if (!serverStart) { + _initialSlide = initialSlide; + return; + } + // Новая лента: слайд ссылки — только слайд первого открытия, сама сторис — по общим + // правилам; открывать нечего — сторис досмотрены, просмотр пустой. + if (initialSlide != null) { + final story = this.stories[_story]; + StoriesServerProgress.showed( + story, + initialSlide.clamp(0, story.slides.length - 1), + ); + } + final opened = StoriesServerProgress.open(this.stories, _story); + if (opened == null) { + _nothing = true; + } else { + _story = opened; + } } - /// Сторис есть что показать: у новой ленты — хоть один не пропускаемый слайд. - static bool _playable(Story story, bool serverStart) => serverStart - ? story.slides.any((slide) => !storySlideSkipped(slide)) - : story.slides.isNotEmpty; + /// Сторис показывается с её стартового слайда (у новой ленты — есть показываемый). + bool _openable(int index) => + !serverStart || + StoriesServerProgress.openingSlideOf(stories[index]) != null; /// Слайд [index] сторис [story] показывается (у новой ленты — не пропускается). bool _shown(Story story, int index) => @@ -161,6 +211,14 @@ class StoriesPlayback { return null; } + /// Ближайшая сторис от [from] назад, которую можно открыть; нет — `null`. + int? _openableBefore(int from) { + for (var i = from; i >= 0; i--) { + if (_openable(i)) return i; + } + return null; + } + /// Сторис со слайдами в порядке ленты. final List stories; @@ -176,8 +234,11 @@ class StoriesPlayback { bool _sheet = false; int? _turnTarget; - /// Слайд начальной сторис в обход правил, пока на неё не зашли. + /// Слайд начальной сторис в обход правил, пока на неё не зашли (старая лента). int? _initialSlide; + + /// Новая лента: открыть нечего — все сторис с начальной досмотрены. + bool _nothing = false; Duration _elapsed = Duration.zero; Duration _duration = Duration.zero; bool _byVideo = false; @@ -186,7 +247,9 @@ class StoriesPlayback { /// зависание), слайд не проскакивает. static const Duration maxTick = Duration(seconds: 1); - bool get isEmpty => stories.isEmpty; + /// Показать нечего: сторис со слайдами нет, а у новой ленты — открыть нечего + /// ([StoriesServerProgress.open]). Такой просмотр закрывается сразу. + bool get isEmpty => stories.isEmpty || _nothing; int get storyIndex => _story; int get slideIndex => _slide; Story get story => stories[_story]; @@ -247,42 +310,57 @@ class StoriesPlayback { } /// Стартовый слайд сторис [index] по текущему состоянию просмотренного; у начальной - /// сторис до первого захода — заданный при создании, если он был. + /// сторис до первого захода — заданный при создании, если он был. У новой ленты — + /// показываемый со стартового ([StoriesServerProgress.openingSlideOf]); у сторис, + /// которую не открыть, — для страницы-соседки её первый показываемый или первый. int startSlideFor(int index) { final story = stories[index]; final initial = _initialSlide; - final int start; if (initial != null && index == _story && !_entered) { - start = initial.clamp(0, story.slides.length - 1); - } else if (serverStart) { - start = StoriesServerProgress.startOf(story); - } else { + return initial.clamp(0, story.slides.length - 1); + } + if (!serverStart) { return startSlideOf(story, _seen[story.id] ?? const {}); } - return _nearest(story, start, 1) ?? _nearest(story, 0, 1) ?? start; + return StoriesServerProgress.openingSlideOf(story) ?? + _nearest(story, 0, 1) ?? + 0; } /// Страница осела на сторис [index] (листанием, программно или при открытии). - /// `true` — начался заход на её стартовый слайд; та же сторис — `false`, только - /// снимается пауза листания. - bool settle(int index) { + /// [StoriesStep.slide] — начался заход на её стартовый слайд; та же сторис — + /// [StoriesStep.none], только снимается пауза листания. Новая лента: сторис, которую не + /// открыть, пропускается — вперёд с отметкой «просмотрена» ([StoriesServerProgress.open]), + /// назад без неё: [StoriesStep.turn] к той, что откроется, или [StoriesStep.close], + /// если такой нет. + StoriesStep settle(int index) { _reasons.remove(StoriesPauseReason.drag); _turnTarget = null; - if (stories.isEmpty) return false; + if (isEmpty) return StoriesStep.none; final target = index.clamp(0, stories.length - 1); - if (_entered && target == _story) return false; + if (_entered && target == _story) return StoriesStep.none; + final forward = !_entered || target > _story; // Перелистнули вперёд — с прежней ушли вперёд. - if (serverStart && _entered && target > _story) { + if (serverStart && _entered && forward) { StoriesServerProgress.leftForward(story); } + if (!_openable(target)) { + final other = forward + ? StoriesServerProgress.open(stories, target) + : _openableBefore(target); + if (other == null) return StoriesStep.close; + _turnTo(other); + return StoriesStep.turn; + } _story = target; _slide = startSlideFor(target); _initialSlide = null; _enter(); - return true; + return StoriesStep.slide; } - /// Вперёд: следующий слайд, следующая сторис или закрыть. + /// Вперёд: следующий слайд, следующая сторис или закрыть. Новая лента: следующая + /// сторис — та, что откроется ([StoriesServerProgress.open]); нет такой — закрыть. StoriesStep next() { if (!_entered || _sheet || _turnTarget != null) return StoriesStep.none; if (_nearest(story, _slide + 1, 1) case final following?) { @@ -290,7 +368,13 @@ class StoriesPlayback { _enter(); return StoriesStep.slide; } - if (serverStart) StoriesServerProgress.leftForward(story, finished: true); + if (serverStart) { + StoriesServerProgress.leftForward(story, finished: true); + final following = StoriesServerProgress.open(stories, _story + 1); + if (following == null) return StoriesStep.close; + _turnTo(following); + return StoriesStep.turn; + } if (_story < stories.length - 1) { _turnTo(_story + 1); return StoriesStep.turn; @@ -298,7 +382,8 @@ class StoriesPlayback { return StoriesStep.close; } - /// Назад: предыдущий слайд, предыдущая сторис или перезапуск первого слайда. + /// Назад: предыдущий слайд, предыдущая сторис или перезапуск первого слайда. Новая + /// лента перешагивает сторис, которую не открыть. StoriesStep previous() { if (!_entered || _sheet || _turnTarget != null) return StoriesStep.none; if (_nearest(story, _slide - 1, -1) case final before?) { @@ -306,19 +391,27 @@ class StoriesPlayback { _enter(); return StoriesStep.slide; } - if (_story > 0) { - _turnTo(_story - 1); + if (_openableBefore(_story - 1) case final before?) { + _turnTo(before); return StoriesStep.turn; } _elapsed = Duration.zero; return StoriesStep.restart; } - /// Перелистнуть на сторис [index] программно (по id из хоста). Та же — `none`. + /// Перелистнуть на сторис [index] программно (по id из хоста). Та же — `none`. Новая + /// лента открывает её по общим правилам: не открыть — следующую + /// ([StoriesServerProgress.open]), а нет такой — закрыть. StoriesStep turnTo(int index) { - if (stories.isEmpty) return StoriesStep.none; - final target = index.clamp(0, stories.length - 1); + if (isEmpty) return StoriesStep.none; + var target = index.clamp(0, stories.length - 1); if (_entered && target == _story) return StoriesStep.none; + if (!_openable(target)) { + final opened = StoriesServerProgress.open(stories, target); + if (opened == null) return StoriesStep.close; + target = opened; + if (_entered && target == _story) return StoriesStep.none; + } _sheet = false; _reasons.remove(StoriesPauseReason.sheet); _turnTo(target); diff --git a/test/ui/stories_playback_test.dart b/test/ui/stories_playback_test.dart index 86cf5bf..10085b3 100644 --- a/test/ui/stories_playback_test.dart +++ b/test/ui/stories_playback_test.dart @@ -20,6 +20,23 @@ Story _story(String id, int count, {bool viewed = false, int start = 0}) => ], ); +/// A story of the new feed: `m` — a media slide, `s` — a skipped one (no media, no +/// product), in [kinds] order; ids `0`, `1`, … +Story _feedStory(String id, String kinds, {int start = 0}) => Story( + id: id, + name: id, + avatar: '', + startPosition: start, + slides: [ + for (var i = 0; i < kinds.length; i++) + StorySlide( + id: '$id$i', + type: kinds[i] == 'm' ? StorySlideType.image : StorySlideType.product, + duration: const Duration(seconds: 5), + ), + ], +); + /// Opens [playback] the way the viewer does: the first page settles, media is ready. StoriesPlayback _open(StoriesPlayback playback) { playback.settle(playback.storyIndex); @@ -73,7 +90,7 @@ void main() { reason: 'not entered before settle', ); - expect(playback.settle(1), isTrue); + expect(playback.settle(1), StoriesStep.slide); expect(playback.slide.id, 'b0'); expect(playback.seenOf('b'), {'b0'}); playback.mediaReady(playback.generation); @@ -116,7 +133,7 @@ void main() { StoriesPlayback(stories: [_story('a', 1), _story('b', 1)]), ); playback.pause(StoriesPauseReason.drag); - expect(playback.settle(0), isFalse); + expect(playback.settle(0), StoriesStep.none); expect(playback.running, isTrue); expect(playback.seenOf('b'), isEmpty); }); @@ -132,6 +149,113 @@ void main() { }); }); + group('the new feed: slides with nothing to show are skipped', () { + StoriesPlayback feed(List stories, {int initial = 0, int? slide}) => + StoriesPlayback( + stories: stories, + initialStory: initial, + initialSlide: slide, + serverStart: true, + ); + + test('forward passes them, back steps over them', () { + final playback = _open(feed([_feedStory('a', 'msm')])); + expect(playback.slide.id, 'a0'); + expect(playback.next(), StoriesStep.slide); + expect(playback.slide.id, 'a2'); + playback.mediaReady(playback.generation); + expect(playback.previous(), StoriesStep.slide); + expect(playback.slide.id, 'a0', reason: 'not bounced forward'); + expect(playback.seenOf('a'), {'a0', 'a2'}, reason: 'no entry on a1'); + }); + + test('start_position on a skipped slide opens the next shown one', () { + final playback = _open(feed([_feedStory('a', 'msm', start: 1)])); + expect(playback.slide.id, 'a2'); + }); + + test('nothing shown after the start: finished, viewed, the next story', () { + final a = _feedStory('a', 'ms', start: 1); + final b = _feedStory('b', 'm'); + final playback = _open(feed([a, b])); + expect(playback.storyIndex, 1); + expect(playback.slide.id, 'b0'); + expect(StoriesServerProgress.viewedOf(a), isTrue); + expect(StoriesServerProgress.startOf(a), 0, reason: 'starts over'); + }); + + test('a story of skipped slides only stays in the feed; opening it opens ' + 'the next one and marks it viewed', () { + final a = _feedStory('a', 'ss'); + final b = _feedStory('b', 'm'); + final playback = feed([a, b]); + expect(playback.stories, [a, b]); + _open(playback); + expect(playback.story, b); + expect(StoriesServerProgress.viewedOf(a), isTrue); + expect(StoriesServerProgress.viewedOf(b), isFalse); + }); + + test('the last one: nothing to show, the viewer is empty', () { + final a = _feedStory('a', 'm'); + final b = _feedStory('b', 's'); + final playback = feed([a, b], initial: 1); + expect(playback.isEmpty, isTrue); + expect(StoriesServerProgress.viewedOf(b), isTrue); + expect(StoriesServerProgress.viewedOf(a), isFalse); + }); + + test( + 'forward over such a story marks it viewed; past the last — close', + () { + final a = _feedStory('a', 'm'); + final b = _feedStory('b', 'ss'); + final c = _feedStory('c', 'm'); + final playback = _open(feed([a, b, c])); + expect(playback.next(), StoriesStep.turn); + expect(playback.turnTarget, 2); + expect(StoriesServerProgress.viewedOf(b), isTrue); + expect(playback.settle(2), StoriesStep.slide); + expect(playback.story, c); + + final last = _open( + feed([_feedStory('x', 'm'), _feedStory('y', 's')]), + ); + expect(last.next(), StoriesStep.close); + }, + ); + + test('a swipe onto such a story turns on to the next one, or closes', () { + final a = _feedStory('a', 'm'); + final b = _feedStory('b', 's'); + final c = _feedStory('c', 'm'); + final playback = _open(feed([a, b, c])); + expect(playback.settle(1), StoriesStep.turn); + expect(playback.turnTarget, 2); + expect(StoriesServerProgress.viewedOf(a), isTrue, reason: 'left forward'); + expect(StoriesServerProgress.viewedOf(b), isTrue); + + final back = _open( + feed([_feedStory('x', 's'), _feedStory('y', 'm')]), + ); + expect(back.story.id, 'y'); + expect(back.settle(0), StoriesStep.close, reason: 'nothing before it'); + }); + + test('a link slide only sets the first open', () { + final a = _feedStory('a', 'mmm'); + final playback = _open(feed([a], slide: 1)); + expect(playback.slide.id, 'a1'); + expect(StoriesServerProgress.startOf(a), 1); + playback.mediaReady(playback.generation); + playback.next(); + expect(StoriesServerProgress.startOf(a), 2, reason: 'where it was left'); + + final skipped = _feedStory('b', 'msm'); + expect(_open(feed([skipped], slide: 1)).slide.id, 'b2'); + }); + }); + group('pause reasons and the clock', () { test('the clock runs only with no reason, in real deltas', () { final playback = StoriesPlayback(stories: [_story('a', 2)]); diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index 7162ef3..4044c4c 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -2,6 +2,7 @@ // the slide colour, text blocks, header, buttons without a link, promo codes), drawn by // the kit; the old feed keeps the kit's rules. +import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; @@ -10,6 +11,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_slide_view.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_sound.dart'; @@ -645,8 +647,10 @@ void main() { expect(sent(), ['view 1/10', 'view 1/12', 'view 1/10']); }); - testWidgets('a story opens past it; a story of such slides only is not ' - 'shown', (tester) async { + testWidgets('a story opens past it; a story of such slides only stays in ' + 'the bar, opening it opens the next one and marks it viewed', ( + tester, + ) async { stories.addAll(>[ _story(1, >[skipped('10')]), _story(2, >[ @@ -656,12 +660,146 @@ void main() { ], start: 1), ]); await bar(tester); + expect(find.text('Story 1'), findsOneWidget, reason: 'in the bar'); await open(tester, 'Story 2'); expect(find.text('Slide 22'), findsOneWidget); await close(tester); + expect(cover(tester, 0), PersonalizationStoryCoverState.unviewed); await open(tester, 'Story 1'); expect(find.text('Slide 22'), findsOneWidget, reason: 'the next story'); expect(sent(), ['view 2/22', 'view 2/22']); + await close(tester); + expect(cover(tester, 0), PersonalizationStoryCoverState.viewed); + }); + + testWidgets('the last such story: no viewer at all, it is viewed', ( + tester, + ) async { + stories.addAll(>[ + _story(1, >[_slide('10', duration: 30)]), + _story(2, >[skipped('20'), skipped('21')]), + ]); + await bar(tester); + await open(tester, 'Story 2'); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(find.byType(PersonalizationStoriesBar), findsOneWidget); + expect(cover(tester, 1), PersonalizationStoryCoverState.viewed); + expect(cover(tester, 0), PersonalizationStoryCoverState.unviewed); + expect(sent(), isEmpty); + }); + + testWidgets('started past its last shown slide: finished, the next story; ' + 'the last one closes the viewer', (tester) async { + stories.addAll(>[ + _story(1, >[ + _slide('10', duration: 30), + skipped('11'), + ], start: 1), + _story(2, >[_slide('20', duration: 30)]), + ]); + await bar(tester); + await open(tester, 'Story 1'); + expect(find.text('Slide 20'), findsOneWidget); + expect(cover(tester, 0), PersonalizationStoryCoverState.viewed); + final viewer = tester.getRect(find.byType(PersonalizationStoryViewer)); + await tester.tapAt(Offset(viewer.right - 10, viewer.center.dy)); + await settle(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + await open(tester, 'Story 1'); + expect(find.text('Slide 10'), findsOneWidget, reason: 'starts over'); + }); + + testWidgets('a swipe onto such a story turns on past it', (tester) async { + stories.addAll(>[ + _story(1, >[_slide('10', duration: 30)]), + _story(2, >[skipped('20')]), + _story(3, >[_slide('30', duration: 30)]), + ]); + await bar(tester); + await open(tester, 'Story 1'); + await tester.fling( + find.byType(PersonalizationStoryViewer), + const Offset(-500, 0), + 1500, + ); + for (var i = 0; i < 20; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.text('Slide 30'), findsOneWidget); + expect(sent(), ['view 1/10', 'view 3/30']); + await close(tester); + expect(cover(tester, 1), PersonalizationStoryCoverState.viewed); + }); + + testWidgets('show(): nothing to show — no viewer, no error', ( + tester, + ) async { + stories.add(_story(1, >[skipped('10')])); + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: Placeholder())), + ); + final errors = []; + var done = false; + unawaited( + PersonalizationStories.show( + tester.element(find.byType(Placeholder)), + code: _code, + sdk: sdk, + onError: errors.add, + ).then((_) => done = true), + ); + await settle(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(done, isTrue); + expect(errors, isEmpty); + }); + + group('handleLink', () { + Future link(WidgetTester tester, String url) async { + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: Placeholder())), + ); + expect( + PersonalizationStoriesV3.handleLink( + tester.element(find.byType(Placeholder)), + url, + sdk: sdk, + iconBuilder: _icon, + ), + isTrue, + ); + await settle(tester); + } + + testWidgets('a story of such slides only: no viewer, shared_open', ( + tester, + ) async { + stories.add(_story(1, >[skipped('10')])); + await link( + tester, + 'https://shop.example/?r46_stories=$_code&r46_story=1', + ); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(sent(), ['shared_open 1/10']); + }); + + testWidgets('a link slide that is skipped opens the next shown one', ( + tester, + ) async { + stories.add( + _story(1, >[ + _slide('10', duration: 30), + skipped('11'), + _slide('12', duration: 30), + ]), + ); + await link( + tester, + 'https://shop.example/?r46_stories=$_code&r46_story=1&r46_slide=11', + ); + expect(find.text('Slide 12'), findsOneWidget); + expect(sent(), ['view 1/12', 'shared_open 1/12']); + }); }); testWidgets('the old feed shows it', (tester) async { From 91032f910bdd38d8c88f7888226cccdc7ef294ee Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 13:47:32 +0400 Subject: [PATCH 10/24] fix(stories): going back on the first slide of the first story over API v3 closes the viewer, as the web SDK does, instead of restarting the slide; going back into a story with nothing to show steps over it. The old feed keeps the restart --- .../widgets/personalization_story_viewer.dart | 12 +++---- lib/src/ui/widgets/stories_playback.dart | 4 ++- test/ui/stories_share_widget_test.dart | 32 ++++++++++++++++--- 3 files changed, 35 insertions(+), 13 deletions(-) diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index 581e379..9165b81 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -32,8 +32,8 @@ import 'stories_v3_scope.dart'; /// - касание левой трети — назад, правой — вперёд, середина ничего не делает; в RTL края /// меняются местами. Удержание от 200 мс — пауза, отпускание её снимает и никуда не /// листает. Назад на первом слайде первой сторис перезапускает слайд — прогресс и видео -/// с нуля, без перезагрузки; вперёд на последнем слайде последней — закрывает -/// просмотр; +/// с нуля, без перезагрузки (у новой ленты, как в вебе, закрывает просмотр); вперёд на +/// последнем слайде последней — закрывает просмотр; /// - свайп вбок листает сторис; заход на сторис (просмотр слайда, трекинг `view`) — только /// когда страница осела, подглядывание соседней не считается. Свайп вниз дальше 120 или /// быстрее 800 в секунду закрывает, иначе слайд пружинит назад; пока тянут — пауза; @@ -435,15 +435,11 @@ class _PersonalizationStoryViewerState extends State case StoriesStep.slide: _entered(); case StoriesStep.restart: - // Тот же заход: медиа не перезагружается. С API v3 слайд показан снова — `view` - // ещё раз, как в вебе (повторы за 2 с сервер склеивает сам); старый трекинг — - // без повтора. + // Тот же заход: медиа не перезагружается, `view` не повторяется. Только у старой + // ленты: новая, как веб, здесь закрывает просмотр. _progress.value = 0; if (_videoReady) _video?.seekTo(Duration.zero); _gif?.restart(); - if (_v3Code != null) { - _trackV3(StoriesV3Event.view, _playback.story, _playback.slide); - } case StoriesStep.turn: _sync(); final target = _playback.turnTarget!; diff --git a/lib/src/ui/widgets/stories_playback.dart b/lib/src/ui/widgets/stories_playback.dart index 734823e..e64cfb8 100644 --- a/lib/src/ui/widgets/stories_playback.dart +++ b/lib/src/ui/widgets/stories_playback.dart @@ -383,7 +383,8 @@ class StoriesPlayback { } /// Назад: предыдущий слайд, предыдущая сторис или перезапуск первого слайда. Новая - /// лента перешагивает сторис, которую не открыть. + /// лента перешагивает сторис, которую не открыть, а на первом показываемом слайде + /// первой сторис, как веб, закрывает просмотр. StoriesStep previous() { if (!_entered || _sheet || _turnTarget != null) return StoriesStep.none; if (_nearest(story, _slide - 1, -1) case final before?) { @@ -395,6 +396,7 @@ class StoriesPlayback { _turnTo(before); return StoriesStep.turn; } + if (serverStart) return StoriesStep.close; _elapsed = Duration.zero; return StoriesStep.restart; } diff --git a/test/ui/stories_share_widget_test.dart b/test/ui/stories_share_widget_test.dart index 67e1c50..d686de5 100644 --- a/test/ui/stories_share_widget_test.dart +++ b/test/ui/stories_share_widget_test.dart @@ -278,15 +278,39 @@ void main() { }); }); - testWidgets('back on the first slide restarts it and sends view again', ( + testWidgets('back on the first slide of the first story closes the viewer, ' + 'as the web; back from the next story opens it where it was left', ( tester, ) async { await bar(tester); await open(tester, 'Products'); final viewer = tester.getRect(find.byType(PersonalizationStoryViewer)); - await tester.tapAt(Offset(viewer.left + 10, viewer.center.dy)); - await tester.pump(); - expect(server.events, ['view 39/39_0', 'view 39/39_0']); + final left = Offset(viewer.left + 10, viewer.center.dy); + final right = Offset(viewer.right - 10, viewer.center.dy); + // A turn of the page is idle a frame after its last step. + Future tap(Offset at) async { + await tester.tapAt(at); + await _settle(tester); + await tester.pump(const Duration(milliseconds: 100)); + } + + await tap(right); + await tap(right); + expect(find.text('Product 37'), findsOneWidget); + await tap(left); + expect( + find.text('Product 39_0'), + findsOneWidget, + reason: 'finished: from 0', + ); + await tap(left); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(server.events, [ + 'view 39/39_0', + 'view 39/39_1', + 'view 40/37', + 'view 39/39_0', + ]); }); testWidgets('share: the campaign link, a pause until the sheet closes', ( From a9c74eba4b0f21fc8b27a39f539b67d2751f8d18 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 13:48:06 +0400 Subject: [PATCH 11/24] fix(stories): the ring of a story over API v3 in the bar lights no segment before start_position: all of them once the story is viewed, none before, as start_position says where it opens and not what was seen --- .../ui/widgets/personalization_stories.dart | 8 +++--- test/ui/stories_v3_rules_test.dart | 27 +++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/lib/src/ui/widgets/personalization_stories.dart b/lib/src/ui/widgets/personalization_stories.dart index a0a8ce5..002cef2 100644 --- a/lib/src/ui/widgets/personalization_stories.dart +++ b/lib/src/ui/widgets/personalization_stories.dart @@ -726,10 +726,10 @@ class _PersonalizationStoriesState extends State { } /// Сторис новой ленты: просмотрена, как в вебе, по `viewed` сервера или когда с неё - /// ушли вперёд; дуги горят до слайда, с которого она откроется. + /// ушли вперёд. Дуги горят все у просмотренной, иначе ни одна: `start_position` — с + /// чего её открыть, а не что видели. PersonalizationStoryItem _serverItem(Story story) { final viewed = StoriesServerProgress.viewedOf(story); - final start = StoriesServerProgress.startOf(story); return PersonalizationStoryItem( id: story.id, label: story.name, @@ -738,8 +738,8 @@ class _PersonalizationStoriesState extends State { viewed: viewed, segments: story.slides.length, seenSegments: { - for (var i = 0; i < story.slides.length; i++) - if (viewed || i < start) i, + if (viewed) + for (var i = 0; i < story.slides.length; i++) i, }, ); } diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index 4044c4c..fa5f34e 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -204,6 +204,12 @@ void main() { await settle(tester); } + PersonalizationStoryPreview preview(WidgetTester tester, int index) => tester + .widgetList( + find.byType(PersonalizationStoryPreview), + ) + .elementAt(index); + PersonalizationStoryCoverState cover(WidgetTester tester, int index) => tester .widgetList( find.byType(PersonalizationStoryPreview), @@ -295,6 +301,27 @@ void main() { expect(find.text('Slide 10'), findsOneWidget, reason: 'its slide'); }); + testWidgets('the ring lights no segment before start_position; viewed — ' + 'all', (tester) async { + stories.addAll(>[ + _story(1, >[ + _slide('10', duration: 30), + _slide('11', duration: 30), + _slide('12', duration: 30), + ], start: 2), + _story(2, >[ + _slide('20', duration: 30), + _slide('21', duration: 30), + ], viewed: true), + ]); + await bar(tester); + expect(preview(tester, 0).seenSegments, isEmpty); + expect(preview(tester, 1).seenSegments, {0, 1}); + await open(tester, 'Story 1'); + await close(tester); + expect(preview(tester, 0).seenSegments, isEmpty, reason: 'left in it'); + }); + testWidgets('the old feed keeps the first unseen slide', (tester) async { api.seen = >{ '1': ['10'], From b4ce8f10916ef0875331e11021da136d450407ad Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 13:50:26 +0400 Subject: [PATCH 12/24] fix(stories): the Android bridge reads a video's audio track on a thread of its own per read and gives up after 5 s, so a hanging network read neither holds the next ones nor leaves the answer pending; an answer that is late or unreadable keeps the sound button, as the button hides only when no audio track is confirmed; the viewer reads the cached file when the cache has filled meanwhile, and stops waiting for the bridge after 6 s --- .../rees46_flutter_sdk/StoriesVideoAudio.kt | 50 +++++++++++++++---- .../StoriesVideoAudioTest.kt | 46 ++++++++++++++++- .../widgets/personalization_story_viewer.dart | 17 +++++-- lib/src/ui/widgets/stories_sound.dart | 9 +++- test/ui/stories_runtime_test.dart | 23 +++++++++ 5 files changed, 127 insertions(+), 18 deletions(-) diff --git a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudio.kt b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudio.kt index 1e26a9e..014c3c7 100644 --- a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudio.kt +++ b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudio.kt @@ -5,32 +5,60 @@ import android.os.Handler import android.os.Looper import java.util.concurrent.Executor import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicBoolean /** - * Whether a stories video has an audio track: the viewer shows its sound button only then, as - * the web SDK does. The container is read off the main thread (a network video reads its - * header over the network) and the answer goes back on the main thread, where Pigeon replies. + * Whether a stories video has an audio track: the viewer hides its sound button only when the + * track list says there is none. The container is read off the main thread (a network video + * reads its header over the network), each read on a thread of its own, so a read that hangs + * does not hold the next ones. A read that is not done in [timeoutMs] answers null + * (inconclusive: the button stays). The answer goes back on the main thread, where Pigeon + * replies, exactly once. */ internal class StoriesVideoAudio( private val probe: (String) -> Boolean? = ::readHasAudio, private val worker: Executor = defaultWorker, private val main: (Runnable) -> Unit = { mainHandler.post(it) }, + private val schedule: (Long, Runnable) -> Unit = { delay, task -> + mainHandler.postDelayed(task, delay) + }, + private val timeoutMs: Long = TIMEOUT_MS, ) { - /** Answers [callback] with the audio of [source]: null when it cannot be read. */ + /** Answers [callback] with the audio of [source]: null when it cannot be read in time. */ fun hasAudio(source: String, callback: (Result) -> Unit) { - worker.execute { - val answer = try { - probe(source) - } catch (e: Exception) { - null + val answered = AtomicBoolean(false) + fun reply(answer: Boolean?) { + if (answered.compareAndSet(false, true)) { + main(Runnable { callback(Result.success(answer)) }) } - main(Runnable { callback(Result.success(answer)) }) + } + schedule(timeoutMs, Runnable { reply(null) }) + try { + worker.execute { + val answer = try { + probe(source) + } catch (e: Exception) { + null + } + reply(answer) + } + } catch (e: Exception) { + // No thread for the read: inconclusive. + reply(null) } } companion object { - private val defaultWorker: Executor by lazy { Executors.newSingleThreadExecutor() } + /** How long a read may take before the answer is inconclusive. */ + const val TIMEOUT_MS = 5_000L + + /** A thread per read, kept a minute for the next one; daemon threads. */ + private val defaultWorker: Executor by lazy { + Executors.newCachedThreadPool { task -> + Thread(task, "rees46-stories-audio").apply { isDaemon = true } + } + } private val mainHandler: Handler by lazy { Handler(Looper.getMainLooper()) } /** `http(s)` addresses are read over the network, anything else is a file path. */ diff --git a/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudioTest.kt b/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudioTest.kt index 7dffefe..ab87098 100644 --- a/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudioTest.kt +++ b/android/src/test/kotlin/com/rees46/rees46_flutter_sdk/StoriesVideoAudioTest.kt @@ -30,6 +30,7 @@ internal class StoriesVideoAudioTest { probe = { probed += it; true }, worker = worker, main = { main.execute(it) }, + schedule = { _, _ -> }, ) val answers = mutableListOf>() audio.hasAudio("https://cdn.example/v.mp4") { answers += it } @@ -45,18 +46,58 @@ internal class StoriesVideoAudioTest { fun noAudioIsFalseAndAFailedReadIsNull() { val direct = Executor { it.run() } val answers = mutableListOf() - StoriesVideoAudio(probe = { false }, worker = direct, main = { it.run() }) + val never: (Long, Runnable) -> Unit = { _, _ -> } + StoriesVideoAudio(probe = { false }, worker = direct, main = { it.run() }, schedule = never) .hasAudio("/cache/v.mp4") { answers += it.getOrThrow() } StoriesVideoAudio( probe = { throw IllegalStateException("broken") }, worker = direct, main = { it.run() }, + schedule = never, ).hasAudio("/cache/v.mp4") { answers += it.getOrThrow() } - StoriesVideoAudio(probe = { null }, worker = direct, main = { it.run() }) + StoriesVideoAudio(probe = { null }, worker = direct, main = { it.run() }, schedule = never) .hasAudio("x") { answers += it.getOrThrow() } assertEquals(listOf(false, null, null), answers) } + @Test + fun aReadNotDoneInTimeIsInconclusiveAndAnsweredOnce() { + val worker = Queue() + val timers = mutableListOf>() + val answers = mutableListOf() + StoriesVideoAudio( + probe = { false }, + worker = worker, + main = { it.run() }, + schedule = { delay, task -> timers += delay to task }, + ).hasAudio("https://cdn.example/slow.mp4") { answers += it.getOrThrow() } + assertEquals(listOf(StoriesVideoAudio.TIMEOUT_MS), timers.map { it.first }) + timers.single().second.run() + assertEquals(listOf(null), answers, "the time is up: the button stays") + worker.run() + assertEquals(listOf(null), answers, "the late read is dropped") + } + + @Test + fun aHangingReadDoesNotHoldTheNextOne() { + val release = java.util.concurrent.CountDownLatch(1) + val done = java.util.concurrent.CountDownLatch(1) + val answers = java.util.Collections.synchronizedList(mutableListOf()) + val audio = StoriesVideoAudio( + probe = { source -> + if (source == "hang") release.await() + true + }, + main = { it.run() }, + schedule = { _, _ -> }, + ) + audio.hasAudio("hang") { } + audio.hasAudio("next") { answers += it.getOrThrow(); done.countDown() } + assertTrue(done.await(5, java.util.concurrent.TimeUnit.SECONDS)) + assertEquals(listOf(true), answers) + release.countDown() + } + @Test fun httpAddressesAreRemoteTheRestAreFiles() { assertTrue(StoriesVideoAudio.isRemote("https://cdn.example/v.mp4")) @@ -72,6 +113,7 @@ internal class StoriesVideoAudioTest { probe = { it.endsWith("sound.mp4") }, worker = { it.run() }, main = { it.run() }, + schedule = { _, _ -> }, ) val answers = mutableListOf() plugin.storiesVideoHasAudio("https://cdn.example/sound.mp4") { answers += it.getOrThrow() } diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index 9165b81..23cf8f7 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -694,10 +694,21 @@ class _PersonalizationStoryViewerState extends State /// Новая лента: у видео живого слайда есть звук (или его не прочитать) — кнопка звука. bool _videoSound = false; - /// Звук видео захода [generation] из файла кэша [file] или по адресу [url]: кнопка - /// звука новой ленты — только у видео со звуком, как в вебе; не прочитать — есть. + /// Звук видео захода [generation]: из файла кэша [file], а не было его — из файла, если + /// кэш уже заполнился, иначе по адресу [url]. Кнопки звука новой ленты нет, только + /// когда платформа подтвердила, что дорожки звука нет; не прочитать или не успели за + /// [StoriesSound.probeTimeout] — кнопка есть. Future _probeSound(String url, String? file, int generation) async { - final sound = await StoriesSound.instance.hasAudio(file ?? url); + var source = file; + if (source == null) { + try { + source = (await StoriesMediaCache.instance.cached(url))?.path; + } catch (_) { + // Кэша нет — по адресу. + } + } + if (!_current(generation)) return; + final sound = await StoriesSound.instance.hasAudio(source ?? url); if (!_current(generation) || _videoSound == (sound ?? true)) return; setState(() => _videoSound = sound ?? true); } diff --git a/lib/src/ui/widgets/stories_sound.dart b/lib/src/ui/widgets/stories_sound.dart index c4e2147..c51b9b2 100644 --- a/lib/src/ui/widgets/stories_sound.dart +++ b/lib/src/ui/widgets/stories_sound.dart @@ -99,10 +99,15 @@ class StoriesSound implements pigeon.PersonalizationStoriesFlutterApi { } } - /// Есть ли звук у видео [source] (адрес или файл кэша); не прочитать — `null`. + /// Сколько ждать ответа платформы о звуке видео: мост сам сдаётся раньше (Android — + /// 5 с), это — последняя граница. + static const Duration probeTimeout = Duration(seconds: 6); + + /// Есть ли звук у видео [source] (адрес или файл кэша); не прочитать или нет ответа за + /// [probeTimeout] — `null`. Future hasAudio(String source) async { try { - return await api.storiesVideoHasAudio(source); + return await api.storiesVideoHasAudio(source).timeout(probeTimeout); } catch (error) { debugPrint('PersonalizationStories: audio of $source — $error'); return null; diff --git a/test/ui/stories_runtime_test.dart b/test/ui/stories_runtime_test.dart index 6f49e51..1350c0c 100644 --- a/test/ui/stories_runtime_test.dart +++ b/test/ui/stories_runtime_test.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -45,6 +47,7 @@ class _FakeHostApi extends pigeon.PersonalizationHostApi { Future storiesVideoHasAudio(String source) async { probed.add(source); if (source.endsWith('broken.mp4')) throw PlatformException(code: 'x'); + if (source.endsWith('hang.mp4')) return Completer().future; return source.endsWith('sound.mp4'); } @@ -168,6 +171,26 @@ void main() { }, ); + testWidgets('no answer from the platform in time: unknown, the button ' + 'stays', (tester) async { + StoriesSound.api = _FakeHostApi(); + bool? answer = true; + var done = false; + unawaited( + StoriesSound.instance.hasAudio('https://cdn.example/hang.mp4').then(( + value, + ) { + answer = value; + done = true; + }), + ); + await tester.pump(StoriesSound.probeTimeout - const Duration(seconds: 1)); + expect(done, isFalse); + await tester.pump(const Duration(seconds: 1)); + expect(done, isTrue); + expect(answer, isNull); + }); + test('share hands the link and the button frame to the platform', () async { final api = _FakeHostApi(); final sdk = PersonalizationSdk(api: api, shopId: 'shop-a'); From 52770440307b32a7257322ac6c22f552a0cfa683 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 13:53:03 +0400 Subject: [PATCH 13/24] fix(stories): the viewer of stories over API v3 keeps a mute state of its own instead of restoring the saved choice into the one the old viewers share, so the old feed's sound stays exactly as before; only the sound button's choice is saved per shop, volume up unmutes the viewer on top without saving it --- .../widgets/personalization_story_viewer.dart | 34 +++++--- lib/src/ui/widgets/stories_sound.dart | 84 ++++++++++++------- test/ui/stories_runtime_test.dart | 72 ++++++++++++++-- test/ui/stories_v3_rules_test.dart | 7 +- 4 files changed, 147 insertions(+), 50 deletions(-) diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index 23cf8f7..c4480b0 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -233,6 +233,13 @@ class _PersonalizationStoryViewerState extends State final ValueNotifier _drag = ValueNotifier(0); StreamSubscription? _requests; + + /// Звук этого просмотра: у новой ленты — свой, у старой — общий процесса. + ValueNotifier get _sound => + StoriesSound.instance.of(v3: _playback.serverStart); + + /// Выбор кнопки звука магазина взят с устройства (новая лента). + Future _soundRestored = Future.value(); VideoPlayerController? _video; bool _videoReady = false; bool _videoPlaying = false; @@ -273,12 +280,12 @@ class _PersonalizationStoryViewerState extends State void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); - StoriesSound.instance.attach(); - // Новая лента, как веб, берёт выбор кнопки звука с устройства. - if (_playback.serverStart) { - unawaited(StoriesSound.instance.restore(_shopId)); + StoriesSound.instance.attach(v3: _playback.serverStart); + // Новая лента, как веб, берёт выбор кнопки звука с устройства — свой у магазина. + if (_playback.serverStart && _shopId.isNotEmpty) { + _soundRestored = StoriesSound.instance.restore(_shopId); } - StoriesSound.instance.muted.addListener(_onMuted); + _sound.addListener(_onMuted); widget.paused?.addListener(_onHostPause); _onHostPause(); _requests = widget.storyRequests?.listen(_onStoryRequest); @@ -335,13 +342,13 @@ class _PersonalizationStoryViewerState extends State WidgetsBinding.instance.removeObserver(this); widget.paused?.removeListener(_onHostPause); _requests?.cancel(); - StoriesSound.instance.muted.removeListener(_onMuted); + _sound.removeListener(_onMuted); _timeout?.cancel(); _autoRetry?.cancel(); _ticker.dispose(); _disposeVideo(); _disposeGif(); - StoriesSound.instance.detach(); + StoriesSound.instance.detach(v3: _playback.serverStart); _pages.dispose(); _progress.dispose(); _drag.dispose(); @@ -731,7 +738,9 @@ class _PersonalizationStoryViewerState extends State await video.initialize(); if (!_current(generation) || _video != video) return; await video.setLooping(false); - await video.setVolume(StoriesSound.instance.muted.value ? 0 : 1); + await _soundRestored; + if (!_current(generation) || _video != video) return; + await video.setVolume(_sound.value ? 0 : 1); await StoriesSound.instance.afterVideo(); if (!_current(generation) || _video != video) return; video.addListener(_onVideo); @@ -813,7 +822,7 @@ class _PersonalizationStoryViewerState extends State } void _onMuted() { - _video?.setVolume(StoriesSound.instance.muted.value ? 0 : 1); + _video?.setVolume(_sound.value ? 0 : 1); if (mounted) setState(() {}); } @@ -1009,7 +1018,7 @@ class _PersonalizationStoryViewerState extends State progress: live ? _progress : null, video: live && _videoReady ? _video : null, gif: live ? _gif : null, - muted: StoriesSound.instance.muted.value, + muted: _sound.value, sheetOpen: live && _playback.sheetOpen, failed: live && _playback.pausedBy(StoriesPauseReason.error), onTap: _tap, @@ -1017,8 +1026,9 @@ class _PersonalizationStoryViewerState extends State onClose: _close, onShare: _v3Code == null ? null : _share, shareLabel: _v3?.shareLabel ?? 'Share', - onToggleMute: () => - StoriesSound.instance.toggle(rememberFor: _byType ? _shopId : null), + onToggleMute: () => _playback.serverStart + ? StoriesSound.instance.toggleV3(_shopId) + : StoriesSound.instance.toggle(), onSheet: _sheet, onButton: _button, onProduct: _product, diff --git a/lib/src/ui/widgets/stories_sound.dart b/lib/src/ui/widgets/stories_sound.dart index c51b9b2..aaa1cac 100644 --- a/lib/src/ui/widgets/stories_sound.dart +++ b/lib/src/ui/widgets/stories_sound.dart @@ -9,12 +9,15 @@ import '../../pigeon/personalization_api.g.dart' as pigeon; /// Звук сторис на весь процесс. /// /// - При первом открытии звук выключен; выбор пользователя помнится до конца процесса и -/// переходит на следующие открытия ([muted]). Просмотр новой ленты, как веб, ещё и -/// хранит выбор кнопки звука на устройстве — у каждого магазина свой, как у веба у -/// каждого сайта ([restore], [toggle] с `rememberFor`). -/// - Кнопка громкости «вверх» включает звук: на Android клавиша сама доходит до -/// Flutter ([HardwareKeyboard]), на iOS плагин следит за громкостью аудиосессии и -/// сообщает о росте через `PersonalizationStoriesFlutterApi`. +/// переходит на следующие открытия ([muted]). +/// - Просмотр новой ленты держит свой звук ([mutedV3]), отдельно от старых просмотров: как +/// веб, он берёт выбор кнопки звука с устройства — у каждого магазина свой, как у веба у +/// каждого сайта ([restore]; нет выбора — без звука), и хранит там только выбор кнопки +/// ([toggleV3]). +/// - Кнопка громкости «вверх» включает звук верхнего открытого просмотра (у новой ленты — +/// не сохраняя): на Android клавиша сама доходит до Flutter ([HardwareKeyboard]), на iOS +/// плагин следит за громкостью аудиосессии и сообщает о росте через +/// `PersonalizationStoriesFlutterApi`. /// - iOS: пока идёт видео, сессия `ambient` без звука (музыка пользователя не /// прерывается) и `playback` со звуком; при закрытии просмотра возвращается сессия /// приложения. Android: видео играет с `mixWithOthers` и фокус не забирает. @@ -27,26 +30,46 @@ class StoriesSound implements pigeon.PersonalizationStoriesFlutterApi { @visibleForTesting static pigeon.PersonalizationHostApi api = pigeon.PersonalizationHostApi(); - /// Звук выключен. Общий для всех просмотров процесса. + /// Звук выключен. Общий для всех просмотров старой ленты процесса. final ValueNotifier muted = ValueNotifier(true); - int _viewers = 0; + /// Звук выключен у просмотров новой ленты: свой, старые просмотры его не видят. + final ValueNotifier mutedV3 = ValueNotifier(true); + + /// Звук просмотра новой ленты ([v3]) или старой. + ValueNotifier of({required bool v3}) => v3 ? mutedV3 : muted; + + /// Звуки открытых просмотров по порядку открытия: верхний — последний. + final List> _open = >[]; bool _session = false; - /// Просмотр открылся: слушать кнопку громкости. - void attach() { - if (_viewers++ > 0) return; + /// Звук верхнего открытого просмотра; нет открытых — старой ленты. + ValueNotifier get _current => _open.isEmpty ? muted : _open.last; + + /// Просмотр открылся: слушать кнопку громкости. [v3] — просмотр новой ленты. + void attach({bool v3 = false}) { + final sound = of(v3: v3); + _open.add(sound); + sound.addListener(_apply); + if (_open.length > 1) return; HardwareKeyboard.instance.addHandler(_onKey); pigeon.PersonalizationStoriesFlutterApi.setUp(this); - muted.addListener(_apply); } /// Просмотр закрылся. Последний — вернуть сессию приложения. - void detach() { - if (_viewers == 0 || --_viewers > 0) return; + void detach({bool v3 = false}) { + final sound = of(v3: v3); + final index = _open.lastIndexOf(sound); + if (index < 0) return; + _open.removeAt(index); + sound.removeListener(_apply); + if (_open.isNotEmpty) { + // Сверху теперь просмотр с другим звуком — сессия по нему. + if (index == _open.length && !identical(_open.last, sound)) _apply(); + return; + } HardwareKeyboard.instance.removeHandler(_onKey); pigeon.PersonalizationStoriesFlutterApi.setUp(null); - muted.removeListener(_apply); if (_session) { _session = false; _call(api.endStoriesAudio); @@ -60,29 +83,32 @@ class StoriesSound implements pigeon.PersonalizationStoriesFlutterApi { await _call(api.beginStoriesAudio); } - /// После готовности плеера: сессия по [muted] (iOS). Плеер при создании сам трогает - /// категорию, поэтому — после каждого. + /// После готовности плеера: сессия по звуку верхнего просмотра (iOS). Плеер при + /// создании сам трогает категорию, поэтому — после каждого. Future afterVideo() => _session - ? _call(() => api.updateStoriesAudio(muted.value)) + ? _call(() => api.updateStoriesAudio(_current.value)) : Future.value(); /// Ключ выбора кнопки звука магазина [shopId] на устройстве. static String mutedKey(String shopId) => 'personalization.stories.muted.$shopId'; - /// Кнопка звука: переключить; [rememberFor] — магазин, для которого сохранить выбор на - /// устройстве (`null` — не сохранять). - void toggle({String? rememberFor}) { - muted.value = !muted.value; - if (rememberFor != null) unawaited(_remember(rememberFor, muted.value)); + /// Кнопка звука старой ленты: переключить на весь процесс. + void toggle() => muted.value = !muted.value; + + /// Кнопка звука новой ленты: переключить и сохранить выбор магазина [shopId] на + /// устройстве (пустой магазин — не сохранять). + void toggleV3(String shopId) { + mutedV3.value = !mutedV3.value; + if (shopId.isNotEmpty) unawaited(_remember(shopId, mutedV3.value)); } - /// Взять выбор кнопки звука магазина [shopId] с устройства; его нет — звук выключен, - /// как у веба. Устройство не ответило — звук как был. + /// Взять в [mutedV3] выбор кнопки звука магазина [shopId] с устройства; его нет — звук + /// выключен, как у веба. Устройство не ответило — звук как был. Future restore(String shopId) async { try { final preferences = await SharedPreferences.getInstance(); - muted.value = preferences.getBool(mutedKey(shopId)) ?? true; + mutedV3.value = preferences.getBool(mutedKey(shopId)) ?? true; } catch (error) { debugPrint('PersonalizationStories: sound choice unavailable — $error'); } @@ -115,19 +141,19 @@ class StoriesSound implements pigeon.PersonalizationStoriesFlutterApi { } @override - void onStoriesVolumeUp() => muted.value = false; + void onStoriesVolumeUp() => _current.value = false; bool _onKey(KeyEvent event) { if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.audioVolumeUp) { - muted.value = false; + _current.value = false; } // Клавиша идёт дальше: громкость системы меняется как обычно. return false; } void _apply() { - if (_session) _call(() => api.updateStoriesAudio(muted.value)); + if (_session) _call(() => api.updateStoriesAudio(_current.value)); } static Future _call(Future Function() body) async { diff --git a/test/ui/stories_runtime_test.dart b/test/ui/stories_runtime_test.dart index 1350c0c..285c6a0 100644 --- a/test/ui/stories_runtime_test.dart +++ b/test/ui/stories_runtime_test.dart @@ -120,10 +120,13 @@ void main() { () async { SharedPreferences.setMockInitialValues({}); final sound = StoriesSound.instance; - addTearDown(() => sound.muted.value = true); + addTearDown(() { + sound.muted.value = true; + sound.mutedV3.value = true; + }); await sound.restore('shop-a'); - expect(sound.muted.value, isTrue, reason: 'muted by default'); - sound.toggle(rememberFor: 'shop-a'); + expect(sound.mutedV3.value, isTrue, reason: 'muted by default'); + sound.toggleV3('shop-a'); await Future.delayed(Duration.zero); final preferences = await SharedPreferences.getInstance(); expect( @@ -131,13 +134,13 @@ void main() { 'personalization.stories.muted.shop-a', ); expect(preferences.getBool(StoriesSound.mutedKey('shop-a')), isFalse); - sound.muted.value = true; + sound.mutedV3.value = true; await sound.restore('shop-a'); - expect(sound.muted.value, isFalse, reason: 'the stored choice'); + expect(sound.mutedV3.value, isFalse, reason: 'the stored choice'); await sound.restore('shop-b'); expect( - sound.muted.value, + sound.mutedV3.value, isTrue, reason: 'another shop has its own choice: none — muted, as the web', ); @@ -154,6 +157,63 @@ void main() { }, ); + test('the new feed has its own sound: the old feed\'s stays as it was; ' + 'volume up unmutes the top viewer and is not stored', () async { + SharedPreferences.setMockInitialValues({}); + final api = _FakeHostApi(); + StoriesSound.api = api; + final sound = StoriesSound.instance; + addTearDown(() { + sound.muted.value = true; + sound.mutedV3.value = true; + }); + // The test before leaves volume up pressed. + HardwareKeyboard.instance.clearState(); + sound.muted.value = false; + await sound.restore('shop-a'); + expect(sound.mutedV3.value, isTrue); + expect(sound.muted.value, isFalse, reason: 'restore leaves the old feed'); + + sound.attach(); + sound.attach(v3: true); + await sound.beforeVideo(); + await sound.afterVideo(); + await simulateKeyDownEvent(LogicalKeyboardKey.audioVolumeUp); + await simulateKeyUpEvent(LogicalKeyboardKey.audioVolumeUp); + expect(sound.mutedV3.value, isFalse); + sound.onStoriesVolumeUp(); + sound.toggleV3('shop-a'); + expect(sound.mutedV3.value, isTrue); + expect(sound.muted.value, isFalse, reason: 'the old viewer untouched'); + await Future.delayed(Duration.zero); + final preferences = await SharedPreferences.getInstance(); + expect( + preferences.getBool(StoriesSound.mutedKey('shop-a')), + isTrue, + reason: 'only the button choice is stored', + ); + sound.mutedV3.value = false; + await Future.delayed(Duration.zero); + expect( + preferences.getBool(StoriesSound.mutedKey('shop-a')), + isTrue, + reason: 'a change that is not the button is not stored', + ); + + sound.detach(v3: true); + sound.detach(); + await Future.delayed(Duration.zero); + expect(api.audio, [ + 'begin', + 'muted', + 'sound', + 'muted', + 'sound', + 'sound', + 'end', + ]); + }); + test( 'the audio of a video: the platform answers, a failure is unknown', () async { diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index fa5f34e..fffe3e8 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -485,7 +485,7 @@ void main() { tester, ) async { final sound = StoriesSound.instance; - addTearDown(() => sound.muted.value = true); + addTearDown(() => sound.mutedV3.value = true); stories.add(_story(1, >[_slide('10')])); SharedPreferences.setMockInitialValues({ @@ -493,7 +493,8 @@ void main() { }); await bar(tester); await open(tester, 'Story 1'); - expect(sound.muted.value, isFalse, reason: 'saved for this shop'); + expect(sound.mutedV3.value, isFalse, reason: 'saved for this shop'); + expect(sound.muted.value, isTrue, reason: 'the old feed keeps its own'); await close(tester); SharedPreferences.setMockInitialValues({ @@ -501,7 +502,7 @@ void main() { }); await open(tester, 'Story 1'); expect( - sound.muted.value, + sound.mutedV3.value, isTrue, reason: 'nothing saved for this shop: muted, as the web', ); From 0f69e3bad6ee9fac1b778f5c2ce1766e9f7fd870 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 13:57:07 +0400 Subject: [PATCH 14/24] fix(stories): the header element, text_italic and the monospace and case-insensitive font_type of text blocks are read only for stories over API v3, so the public getStories and the old feed keep the model and the text blocks of master --- lib/src/stories/stories_header_v3.dart | 6 +++ lib/src/stories/stories_response.dart | 60 ++++++++++++++++------ lib/src/ui/widgets/stories_api_v3.dart | 5 +- lib/src/ui/widgets/stories_slide_view.dart | 2 +- lib/src/ui/widgets/stories_support.dart | 22 +++++--- test/stories/stories_response_test.dart | 51 ++++++++++++++++-- test/ui/stories_v3_rules_test.dart | 9 ++++ 7 files changed, 123 insertions(+), 32 deletions(-) diff --git a/lib/src/stories/stories_header_v3.dart b/lib/src/stories/stories_header_v3.dart index 50413a6..b45d9ca 100644 --- a/lib/src/stories/stories_header_v3.dart +++ b/lib/src/stories/stories_header_v3.dart @@ -1,5 +1,11 @@ part of 'stories_response.dart'; +/// The `payload` of API v3 (`/api/v3/storefront/stories/{code}`): the keys of the old +/// feed plus what only API v3 has — the `header` element and its text block rules. Behind +/// the v3 gate; the old feed ([StoriesBlock.fromJson]) reads none of it. +StoriesBlock parseStoriesBlockV3(Map json) => + StoriesBlock._parse(json, v3: true); + /// `header` of a slide (API v3): the icon, the title and the subtitle of the shop or the /// campaign over the slide, with a link. Behind the v3 gate (`src/v3/personalization_v3.dart`), /// not the kit's; the old feed draws none. diff --git a/lib/src/stories/stories_response.dart b/lib/src/stories/stories_response.dart index 9f78939..6e38f04 100644 --- a/lib/src/stories/stories_response.dart +++ b/lib/src/stories/stories_response.dart @@ -23,10 +23,17 @@ class StoriesBlock { const StoriesBlock({required this.id, required this.stories}); - factory StoriesBlock.fromJson(Map json) { + factory StoriesBlock.fromJson(Map json) => + StoriesBlock._parse(json, v3: false); + + // [v3] — `payload` of API v3: its own elements (`header`) and text block rules, behind + // the v3 gate ([parseStoriesBlockV3]); the old feed reads none of them. + factory StoriesBlock._parse(Map json, {required bool v3}) { return StoriesBlock( id: json['id']?.toString() ?? '', - stories: _maps(json['stories']).map(Story.fromJson).toList(), + stories: _maps( + json['stories'], + ).map((story) => Story._parse(story, v3: v3)).toList(), ); } } @@ -76,7 +83,10 @@ class Story { required this.slides, }); - factory Story.fromJson(Map json) { + factory Story.fromJson(Map json) => + Story._parse(json, v3: false); + + factory Story._parse(Map json, {required bool v3}) { return Story._json( json['shareable'] != false, _text(json['share_url']), @@ -86,7 +96,9 @@ class Story { viewed: json['viewed'] == true, pinned: json['pinned'] == true, startPosition: toIntOrNull(json['start_position']) ?? 0, - slides: _maps(json['slides']).map(StorySlide.fromJson).toList(), + slides: _maps( + json['slides'], + ).map((slide) => StorySlide._parse(slide, v3: v3)).toList(), ); } } @@ -150,7 +162,10 @@ class StorySlide { required this.elements, }); - factory StorySlide.fromJson(Map json) { + factory StorySlide.fromJson(Map json) => + StorySlide._parse(json, v3: false); + + factory StorySlide._parse(Map json, {required bool v3}) { final seconds = toIntOrNull(json['duration']); return StorySlide._json( _text(json['share_url']), @@ -168,9 +183,10 @@ class StorySlide { ? defaultDurationSeconds : seconds, ), - elements: _maps( - json['elements'], - ).map(StoryElement.fromJson).whereType().toList(), + elements: _maps(json['elements']) + .map((element) => StoryElement._parse(element, v3: v3)) + .whereType() + .toList(), ); } @@ -183,20 +199,24 @@ class StorySlide { } } -/// An element placed on a slide. Unknown types are dropped while parsing, and so is a -/// `poll` of a kind the kit does not draw. +/// An element placed on a slide. Unknown types and `header` (not drawn by the kit) are +/// dropped while parsing, and so is a `poll` of a kind the kit does not draw. sealed class StoryElement { const StoryElement(); /// The element for [json], or `null` for a type the kit does not draw. - static StoryElement? fromJson(Map json) { + static StoryElement? fromJson(Map json) => + _parse(json, v3: false); + + // [v3] adds `header` and the text block rules of API v3. + static StoryElement? _parse(Map json, {required bool v3}) { return switch (json['type']) { 'button' => StoryButtonElement.fromJson(json), 'product' => StoryProductElement.fromJson(json), 'products' => StoryProductsElement.fromJson(json), - 'text_block' => StoryTextBlockElement.fromJson(json), + 'text_block' => StoryTextBlockElement._parse(json, v3: v3), 'poll' => StoryPollElement.tryParse(json), - 'header' => StoryHeaderElement.fromJson(json), + 'header' when v3 => StoryHeaderElement.fromJson(json), _ => null, }; } @@ -289,7 +309,7 @@ class StoryTextBlockElement extends StoryElement { /// Font size in logical pixels; 14 when not set, as in the native SDKs. final double fontSize; - /// `serif`, `sans-serif`, `monospace` (or `monospaced`) or empty. + /// `serif`, `sans-serif`, `monospaced` or empty. final String fontType; final bool bold; final bool italic; @@ -351,7 +371,15 @@ class StoryTextBlockElement extends StoryElement { required this.promocode, }); - factory StoryTextBlockElement.fromJson(Map json) { + factory StoryTextBlockElement.fromJson(Map json) => + StoryTextBlockElement._parse(json, v3: false); + + // [v3] — the text block rules of API v3 ([StoryTextBlockV3]); the old feed reads the + // fields as before. + factory StoryTextBlockElement._parse( + Map json, { + required bool v3, + }) { final promocode = json['promocode']; final fontSize = toDoubleOrNull(json['font_size']); return StoryTextBlockElement._json( @@ -360,7 +388,7 @@ class StoryTextBlockElement extends StoryElement { fontSize: fontSize ?? defaultFontSize, fontType: json['font_type'] as String? ?? '', bold: json['bold'] == true || json['text_bold'] == true, - italic: json['italic'] == true || json['text_italic'] == true, + italic: json['italic'] == true || (v3 && json['text_italic'] == true), textAlign: json['text_align'] as String? ?? '', textColor: json['text_color'] as String? ?? '', backgroundColor: json['text_background_color'] as String? ?? '', diff --git a/lib/src/ui/widgets/stories_api_v3.dart b/lib/src/ui/widgets/stories_api_v3.dart index 82a2f18..1cb1f90 100644 --- a/lib/src/ui/widgets/stories_api_v3.dart +++ b/lib/src/ui/widgets/stories_api_v3.dart @@ -370,14 +370,15 @@ abstract final class StoriesApiV3 { } /// Ответ GET: `{"status":"success","payload":{id, settings, stories}}` — `payload` тем - /// же разбором, что и старая лента. HTTP не 2xx, не JSON, `status` не `success` или + /// же разбором, что и старая лента, плюс то, что есть только у API v3 + /// ([parseStoriesBlockV3]). HTTP не 2xx, не JSON, `status` не `success` или /// нет `payload` — [StoriesV3Exception]. static StoriesBlock parseResponse(StoriesV3Response response) { final json = _decode(response); if (json['status'] != 'success' || json['payload'] is! Map) { throw StoriesV3Exception('unexpected response: ${_short(response)}'); } - return StoriesBlock.fromJson( + return parseStoriesBlockV3( Map.from(json['payload'] as Map), ); } diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index 7e2646d..80c7830 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -538,7 +538,7 @@ class StorySlideView extends StatelessWidget { } Widget _textBlock(BuildContext context, StoryTextBlockElement element) { - final block = storyTextBlock(element, bodySize: v3); + final block = storyTextBlock(element, newFeed: v3); final code = element.promocode; if (code == null || !live) return block; // Блок с промокодом копирует его: тост сверху и `click` в трекинг. diff --git a/lib/src/ui/widgets/stories_support.dart b/lib/src/ui/widgets/stories_support.dart index d8f1992..091aabc 100644 --- a/lib/src/ui/widgets/stories_support.dart +++ b/lib/src/ui/widgets/stories_support.dart @@ -308,23 +308,29 @@ TextAlign storyTextAlign(String value) => switch (value.trim().toLowerCase()) { /// Текстовый блок сервера → [PersonalizationStoryTextBlock]. /// -/// Шрифт `serif` / `monospace` (и `monospaced`) — системные семейства с запасными для -/// iOS, где имён `serif` и `monospace` нет; `sans-serif` и пусто — шрифт темы. -/// Межстрочный не задан — заготовка макета для этого кегля -/// ([PersonalizationStoryTextBlock.presetLineHeight]). С [bodySize] (новая лента) без +/// Шрифт `serif` / `monospaced` — системные семейства с запасными для iOS, где имён +/// `serif` и `monospace` нет; `sans-serif` и пусто — шрифт темы. Межстрочный не задан — +/// заготовка макета для этого кегля ([PersonalizationStoryTextBlock.presetLineHeight]). +/// Новая лента ([newFeed]): `font_type` без учёта регистра и `monospace` тоже; без /// `font_size` — кегль основного текста кита ([PersonalizationTypography.baseDefault]), а /// не 14. PersonalizationStoryTextBlock storyTextBlock( StoryTextBlockElement element, { - bool bodySize = false, + bool newFeed = false, }) { - final (family, fallback) = switch (element.fontType.trim().toLowerCase()) { + final type = newFeed + ? element.fontType.trim().toLowerCase() + : element.fontType; + final (family, fallback) = switch (type) { 'serif' => ('serif', const ['Georgia', 'Times New Roman']), - 'monospace' || 'monospaced' => ('monospace', const ['Menlo', 'Courier']), + 'monospace' when newFeed => ( + 'monospace', + const ['Menlo', 'Courier'], + ), _ => (null, null), }; - final fontSize = bodySize && !element.hasFontSize + final fontSize = newFeed && !element.hasFontSize ? PersonalizationTypography.baseDefault.fontSize! : element.fontSize; return PersonalizationStoryTextBlock( diff --git a/test/stories/stories_response_test.dart b/test/stories/stories_response_test.dart index 8fa26b9..32e4fa4 100644 --- a/test/stories/stories_response_test.dart +++ b/test/stories/stories_response_test.dart @@ -231,12 +231,9 @@ void main() { expect(product.image, 'https://pictures.example/180/135478.jpg'); }); - test('products, text block; header parsed for the new feed', () { + test('products, text block; header dropped', () { final elements = block.stories[1].slides[1].elements; - expect(elements, hasLength(4)); - final header = elements.whereType().single; - expect(header.title, 'dropped'); - expect((header.icon, header.subtitle, header.link), ('', '', '')); + expect(elements, hasLength(3), reason: 'header is not drawn by the kit'); final products = elements.whereType().single; expect(products.showLabel, 'Товары для геймеров'); @@ -257,6 +254,45 @@ void main() { expect(text.promocode, 'SALE10'); }); + test('only API v3 reads a header and the text block rules of API v3', () { + final v3 = parseStoriesBlockV3(_block).stories[1].slides[1].elements; + expect(v3, hasLength(4)); + final header = v3.whereType().single; + expect(header.title, 'dropped'); + expect((header.icon, header.subtitle, header.link), ('', '', '')); + + const italic = { + 'type': 'text_block', + 'text_input': 'x', + 'text_italic': true, + }; + expect(StoryTextBlockElement.fromJson(italic).italic, isFalse); + final slide = { + 'id': '1', + 'type': 'image', + 'elements': >[italic], + }; + final feed = { + 'id': 1, + 'stories': >[ + { + 'id': 1, + 'slides': >[slide], + }, + ], + }; + StoryTextBlockElement text(StoriesBlock block) => block + .stories + .single + .slides + .single + .elements + .whereType() + .single; + expect(text(StoriesBlock.fromJson(feed)).italic, isFalse); + expect(text(parseStoriesBlockV3(feed)).italic, isTrue); + }); + test('a text block without fields takes the native defaults', () { final text = StoryTextBlockElement.fromJson(const { 'type': 'text_block', @@ -288,6 +324,11 @@ void main() { ('115bd0b67cf5989a1b60c841790b2af6', 'shop-a'), ]); expect(block.stories, hasLength(2)); + expect( + block.stories[1].slides[1].elements.whereType(), + isEmpty, + reason: 'the public getStories keeps the model of the old feed', + ); expect(() => sdk.getStories(''), throwsArgumentError); }); diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index fffe3e8..ab6bc27 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -157,6 +157,8 @@ void main() { ]; Future bar(WidgetTester tester, {bool v3 = true}) async { + // A bar of its own: the one before keeps the stories it loaded. + await tester.pumpWidget(const SizedBox()); if (!v3) { StoriesApiV3.domain = null; api.bridgeFeed = jsonEncode({ @@ -429,6 +431,13 @@ void main() { StoryTextBlockElement.defaultFontSize, reason: 'the old feed keeps 14', ); + final legacy = tester.widget(find.text('Plain')).style!; + expect( + legacy.fontStyle, + isNot(FontStyle.italic), + reason: 'no text_italic', + ); + expect(legacy.fontFamily, isNot('monospace'), reason: 'monospaced only'); }); }); From 89b274f0e25897c1a37b6eef125e9c8c3fc00368 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 13:59:27 +0400 Subject: [PATCH 15/24] =?UTF-8?q?fix(stories):=20a=20slide=20over=20API=20?= =?UTF-8?q?v3=20without=20media=20takes=20the=20kit's=20light=20or=20dark?= =?UTF-8?q?=20text=20by=20the=20higher=20WCAG=20contrast=20against=20its?= =?UTF-8?q?=20background=5Fcolor=20instead=20of=20a=20luminance=20threshol?= =?UTF-8?q?d,=20and=20its=20colours=20=E2=80=94=20the=20slide,=20its=20let?= =?UTF-8?q?terbox,=20a=20text=20block's=20text=20and=20background=20?= =?UTF-8?q?=E2=80=94=20are=20read=20by=20one=20parser,=20as=20CSS=20reads?= =?UTF-8?q?=20them=20on=20the=20web:=20#RGB,=20#RRGGBB,=20#RRGGBBAA,=20rgb?= =?UTF-8?q?()=20and=20rgba();=20the=20old=20feed=20keeps=20its=20colours?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/src/ui/widgets/stories_slide_view.dart | 9 ++-- lib/src/ui/widgets/stories_support.dart | 52 ++++++++++++++++---- test/ui/stories_v3_rules_test.dart | 57 ++++++++++++++++++++++ 3 files changed, 103 insertions(+), 15 deletions(-) diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index 80c7830..94d1d11 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -168,7 +168,8 @@ class StorySlideView extends StatelessWidget { final media = _media(slide) != StoryMedia.none; final body = Builder(builder: (context) => _body(context, slide, media)); // Слайды с медиа — тёмные токены кита: текст и кнопки лежат на фото или видео. Свой - // цвет слайда без медиа — токены по его яркости. + // цвет слайда без медиа — токены кита, у которых основной текст контрастнее с ним по + // WCAG. final color = media ? null : _slideColor(slide); if (media) { return PersonalizationBrightness( @@ -178,9 +179,7 @@ class StorySlideView extends StatelessWidget { } if (color == null) return body; return PersonalizationBrightness( - brightness: color.computeLuminance() > 0.5 - ? Brightness.light - : Brightness.dark, + brightness: PersonalizationBrightness.on(color.withValues(alpha: 1)), child: body, ); } @@ -203,7 +202,7 @@ class StorySlideView extends StatelessWidget { width: constraints.maxWidth, child: ColoredBox( color: media - ? storyLetterbox(slide) + ? storyLetterbox(slide, newFeed: v3) : _slideColor(slide) ?? colors.backgroundCard, child: Stack( fit: StackFit.expand, diff --git a/lib/src/ui/widgets/stories_support.dart b/lib/src/ui/widgets/stories_support.dart index 091aabc..4f2cf97 100644 --- a/lib/src/ui/widgets/stories_support.dart +++ b/lib/src/ui/widgets/stories_support.dart @@ -6,6 +6,7 @@ import '../components/personalization_product.dart'; import '../components/personalization_story_price.dart'; import '../components/personalization_story_text_block.dart'; import '../personalization_typography.dart'; +import '../popups_v3/css_color.dart'; import 'stories_image.dart'; /// Как получить картинку по адресу из данных сторис. Не задан — свой загрузчик SDK: качает @@ -38,6 +39,22 @@ Color? parseStoryColor(String value, {double opacity = 1}) { return color.withValues(alpha: color.a * opacity.clamp(0, 1)); } +/// Цвет новой ленты — одним разбором для слайда и текстовых блоков, как его читает CSS +/// веба: `#RGB`, `#RRGGBB`, `#RRGGBBAA` (альфа в конце) и `rgb()` / `rgba()`; остальное — +/// `null`. +Color? parseStoryCssColor(String value) { + final text = value.trim().toLowerCase(); + if (text.startsWith('#')) { + final digits = text.length - 1; + if (digits != 3 && digits != 6 && digits != 8) return null; + return parseCssColor(text); + } + if (text.startsWith('rgb(') || text.startsWith('rgba(')) { + return parseCssColor(text); + } + return null; +} + /// Что слайд показывает фоном. enum StoryMedia { /// Ничего: фон Background/Card темы приложения. @@ -67,16 +84,19 @@ StoryMedia storyMediaOf(StorySlide slide, {bool byType = false}) { : StoryMedia.image; } -/// Цвет слайда новой ленты без медиа: `background_color`, как в вебе; не задан — `null`, -/// слайд на Background/Card кита. +/// Цвет слайда новой ленты без медиа: `background_color`, как в вебе +/// ([parseStoryCssColor]); не задан — `null`, слайд на Background/Card кита. Color? storySlideColor(StorySlide slide) => - parseStoryColor(slide.backgroundColor); + parseStoryCssColor(slide.backgroundColor); -/// Цвет полей вокруг вписанного медиа: `background_color` слайда, без него чёрный. Это -/// единственное место, где цвет админки идёт в дело: слайд без медиа всегда на -/// Background/Card. -Color storyLetterbox(StorySlide slide) => - parseStoryColor(slide.backgroundColor) ?? const Color(0xFF000000); +/// Цвет полей вокруг вписанного медиа: `background_color` слайда, без него чёрный. У +/// старой ленты это единственное место, где цвет админки идёт в дело: слайд без медиа +/// всегда на Background/Card. Новая лента ([newFeed]) читает цвет, как веб. +Color storyLetterbox(StorySlide slide, {bool newFeed = false}) => + (newFeed + ? parseStoryCssColor(slide.backgroundColor) + : parseStoryColor(slide.backgroundColor)) ?? + const Color(0xFF000000); /// Текстовые блоки, которые рисуются: пустые и из одних пробелов пропускаются. List storyTextBlocks(StorySlide slide) => @@ -339,8 +359,12 @@ PersonalizationStoryTextBlock storyTextBlock( lineHeight: element.lineSpacing > 0 ? element.lineSpacing : PersonalizationStoryTextBlock.presetLineHeight(fontSize), - color: parseStoryColor(element.textColor), - background: element.backgroundOpacity > 0 + color: newFeed + ? parseStoryCssColor(element.textColor) + : parseStoryColor(element.textColor), + background: newFeed + ? _newFeedBackground(element) + : element.backgroundOpacity > 0 ? parseStoryColor( element.backgroundColor, opacity: element.backgroundOpacity, @@ -354,6 +378,14 @@ PersonalizationStoryTextBlock storyTextBlock( ); } +/// Фон текстового блока новой ленты: цвет ([parseStoryCssColor]) с непрозрачностью +/// элемента; у цвета со своей альфой (`#RRGGBBAA`, `rgba()`) — его альфа, как в вебе. +Color? _newFeedBackground(StoryTextBlockElement element) { + final color = parseStoryCssColor(element.backgroundColor); + if (color == null || color.a < 1) return color; + return color.withValues(alpha: element.backgroundOpacity.clamp(0, 1)); +} + /// Сторис, которые можно показать: со слайдами (C16) и без повторов id — сервер иногда /// отдаёт одну сторис дважды; остаётся первая, иначе просмотренность по id склеивается. List playableStories(Iterable stories) { diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index ab6bc27..fc5cc13 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -15,6 +15,7 @@ import 'package:rees46_sdk/src/v3/personalization_v3.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_slide_view.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_sound.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_support.dart'; import 'package:shared_preferences/shared_preferences.dart'; const String _code = 'block'; @@ -387,6 +388,62 @@ void main() { expect(find.text('Retry'), findsNothing); }); + test('one colour parser: #RGB, #RRGGBB, #RRGGBBAA, rgb() and rgba()', () { + expect(parseStoryCssColor('#123'), const Color(0xFF112233)); + expect(parseStoryCssColor(' #112233 '), const Color(0xFF112233)); + expect(parseStoryCssColor('#11223380'), const Color(0x80112233)); + expect(parseStoryCssColor('rgb(17, 34, 51)'), const Color(0xFF112233)); + expect( + parseStoryCssColor('rgba(17, 34, 51, 0.5)'), + const Color.fromARGB(128, 17, 34, 51), + ); + for (final bad in [ + '', + 'red', + '#1234', + '#12345', + 'hsl(0,0%,0%)', + ]) { + expect(parseStoryCssColor(bad), isNull, reason: bad); + } + }); + + testWidgets('the slide colour picks the kit text by WCAG contrast', ( + tester, + ) async { + Brightness? brightness(String text) => tester + .widget( + find + .ancestor( + of: find.text(text), + matching: find.byType(PersonalizationBrightness), + ) + .first, + ) + .brightness; + stories.addAll(>[ + // Red: luminance 0.21 — black text contrasts more (5.3 against 4.0). + _story(1, >[ + _slide('10', type: '', color: '#FF0000', elements: [_product('a')]), + ]), + _story(2, >[ + _slide( + '20', + type: '', + color: 'rgb(0, 0, 128)', + elements: [_product('b')], + ), + ]), + ]); + await bar(tester); + await open(tester, 'Story 1'); + expect(brightness('Product a'), Brightness.light); + await close(tester); + await open(tester, 'Story 2'); + expect(slideColor(tester, 'Product b'), const Color(0xFF000080)); + expect(brightness('Product b'), Brightness.dark); + }); + testWidgets('the old feed keeps the kit card colour', (tester) async { stories.add( _story(1, >[ From a1f660b4b24af40f82ab6598e4af1cd8dffadda7 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 14:28:29 +0400 Subject: [PATCH 16/24] fix(stories): text blocks over API v3 take bold from bold first and text_bold only without it, italic from italic and else text_italic, each of true, 1 and "true", and read the background opacity as the web's calculateOpacity does: a number is percents ("0.5" is 0.5 %, "50" and "50%" are 50 %) and a background colour without an opacity is painted opaque; the old feed keeps its rules --- lib/src/stories/stories_header_v3.dart | 6 +- lib/src/stories/stories_response.dart | 43 ++++++++++++-- test/stories/stories_response_test.dart | 74 +++++++++++++++++++++++++ test/ui/stories_v3_rules_test.dart | 25 ++++++++- 4 files changed, 141 insertions(+), 7 deletions(-) diff --git a/lib/src/stories/stories_header_v3.dart b/lib/src/stories/stories_header_v3.dart index b45d9ca..0eb6ed5 100644 --- a/lib/src/stories/stories_header_v3.dart +++ b/lib/src/stories/stories_header_v3.dart @@ -46,7 +46,11 @@ class StoryHeaderElement extends StoryElement { ); } -/// Text blocks over API v3. Behind the v3 gate, not the kit's. +/// Text blocks over API v3, as the web SDK reads them: `bold` (else the old `text_bold`) +/// and `italic` (else `text_italic`) take `true`, `1` and `"true"`; the background +/// opacity is percents as calculateOpacity reads them (`"0.5"` — 0.5 %, `"50"` and `"50%"` +/// — 50 %), and a background colour without an opacity is opaque; `font_type` is read +/// regardless of case, `monospace` too. Behind the v3 gate, not the kit's. extension StoryTextBlockV3 on StoryTextBlockElement { /// The server sent `font_size`; without it API v3 takes the kit's body text size. bool get hasFontSize => _hasFontSize; diff --git a/lib/src/stories/stories_response.dart b/lib/src/stories/stories_response.dart index 6e38f04..2a58371 100644 --- a/lib/src/stories/stories_response.dart +++ b/lib/src/stories/stories_response.dart @@ -387,14 +387,18 @@ class StoryTextBlockElement extends StoryElement { text: json['text_input'] as String? ?? '', fontSize: fontSize ?? defaultFontSize, fontType: json['font_type'] as String? ?? '', - bold: json['bold'] == true || json['text_bold'] == true, - italic: json['italic'] == true || (v3 && json['text_italic'] == true), + bold: v3 + ? _firstFlag(json, 'bold', 'text_bold') + : json['bold'] == true || json['text_bold'] == true, + italic: v3 + ? _firstFlag(json, 'italic', 'text_italic') + : json['italic'] == true, textAlign: json['text_align'] as String? ?? '', textColor: json['text_color'] as String? ?? '', backgroundColor: json['text_background_color'] as String? ?? '', - backgroundOpacity: parseStoryOpacity( - json['text_background_color_opacity'], - ), + backgroundOpacity: v3 + ? _cssOpacity(json['text_background_color_opacity']) + : parseStoryOpacity(json['text_background_color_opacity']), lineSpacing: toDoubleOrNull(json['text_line_spacing']) ?? 0, yOffset: toDoubleOrNull(json['y_offset']) ?? 0, promocode: promocode is String && promocode.isNotEmpty ? promocode : null, @@ -498,6 +502,35 @@ double parseStoryOpacity(dynamic value) { return fraction.clamp(0, 1).toDouble(); } +// A flag of API v3 under [key], or under its old name [legacy] when [key] is not sent: +// true is `true`, `1` or `"true"` ([_flag]). +bool _firstFlag(Map json, String key, String legacy) => + _flag(json[key] ?? json[legacy]); + +final RegExp _leadingNumber = RegExp( + r'^\s*[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?', +); + +// The opacity of a text block's background over API v3, as the web's calculateOpacity +// reads it: the number (or the number a string starts with, as parseFloat) is percents — +// `"0.5"` is 0.5 %, `"50"` and `"50%"` are 50 %; nothing (`null`, `""`, `0`, `false`), not +// a number or out of 0…100 — the colour as it is, opaque. +double _cssOpacity(Object? value) { + if (value == null || value == false || value == '' || value == 0) return 1; + final double? percent = switch (value) { + final num number => number.toDouble(), + final String text => switch (_leadingNumber.firstMatch(text)) { + final match? => double.tryParse(match.group(0)!.trim()), + null => null, + }, + _ => null, + }; + if (percent == null || percent.isNaN || percent < 0 || percent > 100) { + return 1; + } + return percent / 100; +} + // A string field; JSON `null` (API v3 sends it for empty fields) and other types are empty. String _text(dynamic value) => value is String ? value : ''; diff --git a/test/stories/stories_response_test.dart b/test/stories/stories_response_test.dart index 32e4fa4..3bf66b3 100644 --- a/test/stories/stories_response_test.dart +++ b/test/stories/stories_response_test.dart @@ -293,6 +293,80 @@ void main() { expect(text(parseStoriesBlockV3(feed)).italic, isTrue); }); + test('API v3 text blocks: bold and italic first, the old names else; the ' + 'opacity as the web calculateOpacity', () { + StoryTextBlockElement v3(Map fields) => + parseStoriesBlockV3({ + 'stories': >[ + { + 'id': 1, + 'slides': >[ + { + 'id': '1', + 'type': 'image', + 'elements': >[ + {'type': 'text_block', ...fields}, + ], + }, + ], + }, + ], + }).stories.single.slides.single.elements + .whereType() + .single; + + for (final yes in [true, 1, 'true']) { + expect(v3({'bold': yes}).bold, isTrue, reason: '$yes'); + expect(v3({'italic': yes}).italic, isTrue); + expect(v3({'text_bold': yes}).bold, isTrue); + expect(v3({'text_italic': yes}).italic, isTrue); + } + for (final no in [false, 0, 'false', '1', 'yes']) { + expect(v3({'bold': no}).bold, isFalse, reason: '$no'); + } + expect( + v3({'bold': false, 'text_bold': true}).bold, + isFalse, + reason: 'bold comes first', + ); + expect( + v3({'italic': false, 'text_italic': true}).italic, + isFalse, + ); + + double opacity(Object? value) => v3({ + 'text_background_color': '#112233', + 'text_background_color_opacity': value, + }).backgroundOpacity; + expect(opacity('50%'), closeTo(0.5, 1e-9)); + expect(opacity('50'), closeTo(0.5, 1e-9)); + expect(opacity(' 25% '), closeTo(0.25, 1e-9)); + expect(opacity('0.5'), closeTo(0.005, 1e-9), reason: 'a percent'); + expect(opacity(80), closeTo(0.8, 1e-9)); + expect(opacity(0.3), closeTo(0.003, 1e-9)); + expect(opacity('0%'), 0); + expect(opacity('0'), 0); + for (final opaque in [null, '', 0, 'abc', '-10', '110', true]) { + expect(opacity(opaque), 1, reason: '$opaque: the colour as it is'); + } + expect( + v3({ + 'text_background_color': '#112233', + }).backgroundOpacity, + 1, + reason: 'no opacity — opaque', + ); + + final legacy = StoryTextBlockElement.fromJson(const { + 'type': 'text_block', + 'bold': 1, + 'italic': 'true', + 'text_background_color_opacity': '0.5', + }); + expect((legacy.bold, legacy.italic), (false, false), reason: 'master'); + expect(legacy.backgroundOpacity, closeTo(0.005, 1e-9)); + }); + test('a text block without fields takes the native defaults', () { final text = StoryTextBlockElement.fromJson(const { 'type': 'text_block', diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index fc5cc13..b7b98ef 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -466,9 +466,15 @@ void main() { 'type': 'text_block', 'text_input': 'Plain', 'text_italic': true, - 'font_type': 'monospace', + 'font_type': 'MonoSpace', 'y_offset': 20, }, + { + 'type': 'text_block', + 'text_input': 'Framed', + 'text_background_color': '#112233', + 'y_offset': 40, + }, ], ), ]), @@ -479,6 +485,18 @@ void main() { expect(style.fontSize, PersonalizationTypography.baseDefault.fontSize); expect(style.fontStyle, FontStyle.italic); expect(style.fontFamily, 'monospace'); + PersonalizationStoryTextBlock block(String text) => + tester.widget( + find.ancestor( + of: find.text(text), + matching: find.byType(PersonalizationStoryTextBlock), + ), + ); + expect( + block('Framed').background, + const Color(0xFF112233), + reason: 'a colour without an opacity is opaque, as the web', + ); await close(tester); await bar(tester, v3: false); @@ -495,6 +513,11 @@ void main() { reason: 'no text_italic', ); expect(legacy.fontFamily, isNot('monospace'), reason: 'monospaced only'); + expect( + block('Framed').background, + isNull, + reason: 'the old feed: no opacity, no frame', + ); }); }); From 2b2e85b9f24d187ea8df4fae5f86e397889cd0da Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 14:30:32 +0400 Subject: [PATCH 17/24] fix(stories): a poll answer over API v3 the server accepted is shown before it is saved and stays when saving fails, instead of being rolled back as a failed send; a percent JSON cannot write (NaN, infinity) is saved as the card shows it, and an encoding or storage error only skips the saved record --- lib/src/stories/stories_poll.dart | 18 +++++++-- lib/src/ui/widgets/stories_poll.dart | 54 +++++++++++++++++--------- test/ui/stories_poll_test.dart | 58 ++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+), 23 deletions(-) diff --git a/lib/src/stories/stories_poll.dart b/lib/src/stories/stories_poll.dart index 9d108cc..eccae35 100644 --- a/lib/src/stories/stories_poll.dart +++ b/lib/src/stories/stories_poll.dart @@ -110,12 +110,13 @@ class StoryPollAnswer { ); } - /// Ответ в JSON, как его читает [tryParse]: пустые поля не пишутся. + /// Ответ в JSON, как его читает [tryParse]: пустые поля не пишутся, не конечная оценка + /// — тоже (JSON её не держит). Map toJson() => { 'id': ?id, 'option_ids': ?optionIds, 'text': ?text, - 'rate': ?rate, + 'rate': ?(rate?.isFinite ?? false ? rate : null), 'comment': ?comment, }; } @@ -142,13 +143,22 @@ class StoryPollResults { return 0; } - /// Итоги в JSON, как их читает [tryParse]. + /// Итоги в JSON, как их читает [tryParse]. Не конечный процент (сервер прислал, + /// например, `1e400`) JSON не держит: он пишется так, как его показывает [percentOf] — + /// NaN нулём, бесконечность краем 0…100. Map toJson() => { 'total': total, if (options case final options?) 'options': >[ for (final option in options) - {'id': option.id, 'percent': option.percent}, + { + 'id': option.id, + 'percent': option.percent.isFinite + ? option.percent + : option.percent.isNaN + ? 0 + : option.percent.clamp(0, 100), + }, ], }; diff --git a/lib/src/ui/widgets/stories_poll.dart b/lib/src/ui/widgets/stories_poll.dart index 8243bac..b1cf3fb 100644 --- a/lib/src/ui/widgets/stories_poll.dart +++ b/lib/src/ui/widgets/stories_poll.dart @@ -224,7 +224,8 @@ class StoryPollStore { } /// Ответ [state] опроса [poll] отправлен: он заменяет ответ этого элемента ленты в - /// процессе и пишется на устройство (без `did` — только в процессе). + /// процессе и пишется на устройство (без `did` — только в процессе). Не бросает: + /// запись, которую не сохранить, остаётся только в процессе. void write( StoryPollElement poll, StoryPollPlace place, @@ -233,11 +234,17 @@ class StoryPollStore { _sent[poll] = state; final key = keyOf(poll, place); if (key == null) return; - final record = jsonEncode({ - 'answer': (state.answer ?? const StoryPollAnswer()).toJson(), - 'results': state.results?.toJson(), - 'saved_at': _clock().millisecondsSinceEpoch, - }); + final String record; + try { + record = jsonEncode({ + 'answer': (state.answer ?? const StoryPollAnswer()).toJson(), + 'results': state.results?.toJson(), + 'saved_at': _clock().millisecondsSinceEpoch, + }); + } catch (error) { + debugPrint('PersonalizationStories: poll answer not saved — $error'); + return; + } unawaited(_save(key, record)); } @@ -567,20 +574,9 @@ class StoryPollController extends ChangeNotifier { _sending = true; _failed = false; _changed(); + final StoryPollReply reply; try { - final reply = await request(); - // У шкалы ответ — сама оценка (и комментарий), итогов нет. - final StoryPollState state = scale - ? (answer: sent, results: null) - : (answer: reply.answer ?? sent, results: reply.results); - _store.write(poll, _place, state); - if (_disposed) return; - _answer = state.answer; - _results = state.results; - _answered = true; - _sending = false; - _text = ''; - _changed(); + reply = await request(); } catch (_) { // Лог ошибки — забота транспорта. if (_disposed) return; @@ -588,6 +584,26 @@ class StoryPollController extends ChangeNotifier { _failed = true; rollback?.call(); _changed(); + return; + } + // Сервер ответ принял: сначала карточка, потом хранилище — сбой хранилища ответ не + // откатывает. + // У шкалы ответ — сама оценка (и комментарий), итогов нет. + final StoryPollState state = scale + ? (answer: sent, results: null) + : (answer: reply.answer ?? sent, results: reply.results); + if (!_disposed) { + _answer = state.answer; + _results = state.results; + _answered = true; + _sending = false; + _text = ''; + _changed(); + } + try { + _store.write(poll, _place, state); + } catch (error) { + debugPrint('PersonalizationStories: poll answer not saved — $error'); } } diff --git a/test/ui/stories_poll_test.dart b/test/ui/stories_poll_test.dart index 2b561db..177f572 100644 --- a/test/ui/stories_poll_test.dart +++ b/test/ui/stories_poll_test.dart @@ -35,6 +35,18 @@ class _Transport implements StoryPollsTransport { } } +/// A store whose write throws, as a broken storage would. +class _FailingStore extends StoryPollStore { + _FailingStore({super.clock}); + + @override + void write( + StoryPollElement poll, + StoryPollPlace place, + StoryPollState state, + ) => throw StateError('storage is broken'); +} + /// A mini poll like the web fixtures: «Кому выбираете подарок?» with three options. StoryPollElement _mini( StoryMiniPollKind kind, { @@ -1045,6 +1057,52 @@ void main() { }, ); + test( + 'a reply that cannot be saved keeps the answer the server took', + () async { + final poll = mountAt(_mini(StoryMiniPollKind.singleChoice)); + poll.choose(2); + // `1e400` of JSON is infinity: a percent JSON cannot write back. + await reply( + 0, + const StoryPollReply( + results: StoryPollResults( + total: 3, + options: <({int id, double percent})>[ + (id: 1, percent: double.nan), + (id: 2, percent: double.infinity), + (id: 3, percent: double.negativeInfinity), + ], + ), + ), + ); + expect(poll.failed, isFalse); + expect(poll.answered, isTrue); + expect(poll.selected, {2}); + expect(poll.results!.percentOf(2), 100); + final saved = jsonDecode( + (await SharedPreferences.getInstance()).getString(key)!, + ); + expect((saved as Map)['results']['options'], >[ + {'id': 1, 'percent': 0}, + {'id': 2, 'percent': 100.0}, + {'id': 3, 'percent': 0.0}, + ]); + }, + ); + + test('a store that fails to write keeps the answer too', () async { + store = StoryPollStore.instance = _FailingStore(clock: () => now); + final poll = mountAt(_mini(StoryMiniPollKind.text)); + poll + ..text = 'Книга' + ..submitText(); + await reply(0); + expect(poll.failed, isFalse); + expect(poll.answered, isTrue); + expect(poll.answer!.text, 'Книга'); + }); + test( 'a reply after the card is gone: only the store, no hold change', () async { From ce362470f1bcda91e52a01090da0e84223c56e20 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 14:33:09 +0400 Subject: [PATCH 18/24] =?UTF-8?q?fix(stories):=20a=20poll=20over=20API=20v?= =?UTF-8?q?3=20counts=20as=20answered=20as=20the=20web's=20hasAnswer=20doe?= =?UTF-8?q?s=20=E2=80=94=20option=20ids,=20a=20non-empty=20text=20or=20a?= =?UTF-8?q?=20numeric=20rate=20=E2=80=94=20also=20for=20an=20answer=20sent?= =?UTF-8?q?=20in=20this=20process;=20what=20it=20shows=20goes=20from=20the?= =?UTF-8?q?=20answer=20sent=20from=20the=20same=20feed=20element,=20a=20fr?= =?UTF-8?q?eshly=20loaded=20feed's=20answer,=20an=20answer=20sent=20earlie?= =?UTF-8?q?r=20in=20this=20process=20from=20the=20same=20place=20(with=20n?= =?UTF-8?q?o=20did=20too),=20to=20the=20saved=20record;=20a=20saved=20reco?= =?UTF-8?q?rd=20that=20cannot=20be=20read=20is=20deleted?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/src/stories/stories_poll.dart | 2 +- lib/src/ui/widgets/stories_poll.dart | 59 +++++++++++++++------- test/ui/stories_poll_test.dart | 73 ++++++++++++++++++++++++++-- 3 files changed, 112 insertions(+), 22 deletions(-) diff --git a/lib/src/stories/stories_poll.dart b/lib/src/stories/stories_poll.dart index eccae35..80aac87 100644 --- a/lib/src/stories/stories_poll.dart +++ b/lib/src/stories/stories_poll.dart @@ -89,7 +89,7 @@ class StoryPollAnswer { /// Ответ на вопрос полосы оценки; `null` — его не давали. final String? comment; - /// Ответ есть: непустые варианты, непустой текст или оценка. + /// Ответ есть, как `hasAnswer` веба: непустые варианты, непустой текст или оценка. bool get isAnswered => (optionIds?.isNotEmpty ?? false) || (text?.isNotEmpty ?? false) || diff --git a/lib/src/ui/widgets/stories_poll.dart b/lib/src/ui/widgets/stories_poll.dart index b1cf3fb..afa81c0 100644 --- a/lib/src/ui/widgets/stories_poll.dart +++ b/lib/src/ui/widgets/stories_poll.dart @@ -141,9 +141,10 @@ typedef StoryPollPlace = ({ /// - запись — `{answer, results, saved_at}` (мс эпохи) в SharedPreferences под ключом /// `personalization.storiesPolls.<магазин>.stories_poll__<вид>_<код>_<сторис>_<слайд>` /// ([keyOf]); без `did` ничего не читается и не пишется; -/// - живёт 90 дней ([ttl]): старше или без даты — удаляется при чтении; -/// - что показать ([stateOf]): отправленное в этом процессе (так веб меняет элемент -/// ленты в кэше) < ответ ленты < сохранённое < ничего; лента важнее сохранённого. +/// - живёт 90 дней ([ttl]): старше, без даты или нечитаемая — удаляется при чтении; +/// - что показать ([stateOf]): ответ, отправленный с этого же элемента ленты (так веб +/// меняет элемент ленты в кэше), > ответ свежей ленты > ответ, отправленный раньше в +/// этом процессе с того же места > сохранённое > ничего. class StoryPollStore { StoryPollStore({DateTime Function()? clock}) : _clock = clock ?? DateTime.now; @@ -157,6 +158,13 @@ class StoryPollStore { final DateTime Function() _clock; final Expando _sent = Expando('storyPoll'); + + /// Отправленное в этом процессе по месту опроса — и без `did`. + final Map _process = {}; + + static String _placeKey(StoryPollElement poll, StoryPollPlace place) => + '${place.shopId}\u0000${place.did}\u0000${poll.pollType.wire}\u0000' + '${poll.code}\u0000${place.storyId}\u0000${place.slideId}'; SharedPreferences? _preferences; Future? _opening; @@ -183,18 +191,20 @@ class StoryPollStore { '${poll.pollType.wire}_${poll.code}_${place.storyId}_${place.slideId}'; } - /// Что показать у опроса [poll] сейчас: отправленное в процессе, ответ ленты, - /// сохранённое на устройстве ([saved]); ничего — ответ и итоги ленты как есть. + /// Что показать у опроса [poll] сейчас: отправленное с этого элемента, ответ свежей + /// ленты, отправленное раньше в процессе с того же места, сохранённое на устройстве + /// ([saved]); ничего — ответ и итоги ленты как есть. StoryPollState stateOf(StoryPollElement poll, StoryPollPlace place) { final sent = _sent[poll]; if (sent != null) return sent; final feed = (answer: poll.answer, results: poll.results); if (poll.answer != null) return feed; - return saved(poll, place) ?? feed; + return _process[_placeKey(poll, place)] ?? saved(poll, place) ?? feed; } - /// Ответ [poll] отправлен в этом процессе. - bool sentOf(StoryPollElement poll) => _sent[poll] != null; + /// Ответ [poll] отправлен в этом процессе — с этого элемента или с его места. + bool sentOf(StoryPollElement poll, StoryPollPlace place) => + _sent[poll] != null || _process.containsKey(_placeKey(poll, place)); /// Сохранённая запись опроса [poll]; нет, без `did`, хранилище не открыто, битая — /// `null`. Старше [ttl] или без даты — удаляется. @@ -206,11 +216,12 @@ class StoryPollStore { final raw = preferences.getString(key); if (raw == null) return null; final value = jsonDecode(raw); - if (value is! Map || value['answer'] is! Map) return null; - final savedAt = value['saved_at']; - if (savedAt is! num || + final savedAt = value is Map ? value['saved_at'] : null; + if (value is! Map || + value['answer'] is! Map || + savedAt is! num || _clock().millisecondsSinceEpoch - savedAt > ttl.inMilliseconds) { - preferences.remove(key).ignore(); + _drop(preferences, key); return null; } return ( @@ -218,11 +229,21 @@ class StoryPollStore { results: StoryPollResults.tryParse(value['results']), ); } catch (error) { - debugPrint('PersonalizationStories: saved poll answer skipped — $error'); + // Не прочитать — запись удаляется, как устаревшая. + debugPrint('PersonalizationStories: saved poll answer dropped — $error'); + _drop(preferences, key); return null; } } + static void _drop(SharedPreferences preferences, String key) { + try { + preferences.remove(key).ignore(); + } catch (_) { + // Хранилище не удаляет — запись останется до следующего чтения. + } + } + /// Ответ [state] опроса [poll] отправлен: он заменяет ответ этого элемента ленты в /// процессе и пишется на устройство (без `did` — только в процессе). Не бросает: /// запись, которую не сохранить, остаётся только в процессе. @@ -232,6 +253,7 @@ class StoryPollStore { StoryPollState state, ) { _sent[poll] = state; + _process[_placeKey(poll, place)] = state; final key = keyOf(poll, place); if (key == null) return; final String record; @@ -273,9 +295,9 @@ abstract final class StoryPollPointers { /// Логика карточки опроса — как `createPoll` веб-SDK, без UI. /// -/// - Состояния: форма и отвеченное ([answered]). Что показать сначала — [StoryPollStore]: -/// отправленное в процессе, ответ ленты, сохранённое на устройстве; отвечено, когда -/// ответ отправлен в процессе или в нём есть варианты, текст или оценка. +/// - Состояния: форма и отвеченное ([answered]). Что показать сначала — [StoryPollStore] +/// ([StoryPollStore.stateOf]); отвечено, как `hasAnswer` веба, когда в ответе есть +/// варианты, непустой текст или оценка (после удачной отправки — сразу). /// - Выбор одного и шкала отправляются нажатием ([choose], [rate]); выбор сразу /// подсвечен, при ошибке откатывается к прежнему. Выбор нескольких и текст — кнопкой /// ([submitChoices], [submitText]); варианты уходят в порядке опроса, текст — без @@ -312,7 +334,7 @@ class StoryPollController extends ChangeNotifier { // карточку не трогали. if (!_store.ready && did.isNotEmpty && poll.answer == null) { _store.load().then((_) { - if (_disposed || _touched || _store.sentOf(poll)) return; + if (_disposed || _touched || _store.sentOf(poll, _place)) return; final saved = _store.saved(poll, _place); if (saved == null) return; _show(saved); @@ -410,10 +432,11 @@ class StoryPollController extends ChangeNotifier { /// Слайд держится. bool get holding => _held; + /// Отвечено — как `hasAnswer` веба: в ответе есть варианты, непустой текст или оценка. void _show(StoryPollState state) { _answer = state.answer; _results = state.results; - _answered = _store.sentOf(poll) || (_answer?.isAnswered ?? false); + _answered = _answer?.isAnswered ?? false; _resetForm(); } diff --git a/test/ui/stories_poll_test.dart b/test/ui/stories_poll_test.dart index 177f572..c237e70 100644 --- a/test/ui/stories_poll_test.dart +++ b/test/ui/stories_poll_test.dart @@ -226,11 +226,17 @@ void main() { }); test('an answer of the reply without ids is still the answer', () async { - final poll = mount(_mini(StoryMiniPollKind.singleChoice))..choose(2); + final element = _mini(StoryMiniPollKind.singleChoice); + final poll = mount(element)..choose(2); await reply(0, const StoryPollReply(answer: StoryPollAnswer(id: 77))); expect(poll.answered, isTrue, reason: 'answered after any success'); expect(poll.answer!.id, 77); expect(poll.answer!.optionIds, isNull, reason: 'not the sent one'); + expect( + mount(element).answered, + isFalse, + reason: 'shown again: answered only as hasAnswer of the web', + ); }); test( @@ -1008,12 +1014,73 @@ void main() { expect(preferences.getKeys(), isEmpty); expect(mountAt(element, did: '').answer!.text, 'Книга'); expect( - mountAt(_mini(StoryMiniPollKind.text), did: '').answered, - isFalse, + mountAt(_mini(StoryMiniPollKind.text), did: '').answer!.text, + 'Книга', + reason: 'a new feed without an answer: the one sent in this process', + ); + }, + ); + + test( + 'precedence: a fresh feed > sent earlier in this process > saved', + () async { + SharedPreferences.setMockInitialValues({ + key: jsonEncode({ + 'answer': { + 'option_ids': [1], + }, + 'saved_at': now.millisecondsSinceEpoch, + }), + }); + store = StoryPollStore.instance = StoryPollStore(clock: () => now); + await store.load(); + final saved = (await SharedPreferences.getInstance()).getString(key)!; + expect( + mountAt(_mini(StoryMiniPollKind.singleChoice)).answer!.optionIds, + [1], + reason: 'only the saved one', + ); + mountAt(_mini(StoryMiniPollKind.singleChoice, allowReanswer: true)) + ..reanswer() + ..choose(3); + await reply(0); + // The device still holds the old record (another copy wrote it, say). + await (await SharedPreferences.getInstance()).setString(key, saved); + expect( + mountAt(_mini(StoryMiniPollKind.singleChoice)).answer!.optionIds, + [3], + reason: 'sent in this process wins over the saved record', + ); + expect( + mountAt( + _mini(StoryMiniPollKind.singleChoice, answer: _answered), + ).answer!.optionIds, + [2], + reason: 'a fresh feed wins over both', ); }, ); + test('unreadable records are deleted on read', () async { + for (final raw in [ + 'not json', + '[1, 2]', + '{"answer": "a", "saved_at": 1}', + '{"results": null}', + ]) { + SharedPreferences.setMockInitialValues({key: raw}); + store = StoryPollStore.instance = StoryPollStore(clock: () => now); + await store.load(); + expect(mountAt(_mini(StoryMiniPollKind.text)).answered, isFalse); + await pumpEventQueue(); + expect( + (await SharedPreferences.getInstance()).getKeys(), + isEmpty, + reason: raw, + ); + } + }); + test('90 days: older or undated records are deleted on read', () async { Future withRecord(Object? savedAt) async { SharedPreferences.setMockInitialValues({ From 1ec9d21be44545f33aa040ece66758ab32260823 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 14:35:13 +0400 Subject: [PATCH 19/24] fix(stories): every poll element of a slide over API v3 is drawn, each as its own card at its own y_offset, as the web SDK renders each one, instead of the first only; the slide stands while any of its cards holds it --- .../widgets/personalization_story_viewer.dart | 14 +++-- lib/src/ui/widgets/stories_poll.dart | 10 ++-- lib/src/ui/widgets/stories_slide_view.dart | 52 +++++++++++-------- test/ui/stories_poll_widget_test.dart | 36 +++++++++++++ 4 files changed, 79 insertions(+), 33 deletions(-) diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index c4480b0..a6575a3 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -496,6 +496,8 @@ class _PersonalizationStoryViewerState extends State /// Новый заход на слайд: прогресс с нуля, медиа, просмотренное, трекинг, хост. void _entered() { + // Заход снимает паузу опросов: карточки прошлого слайда её больше не держат. + _pollHolds.clear(); final story = _playback.story; final slide = _playback.slide; final index = _playback.slideIndex; @@ -582,6 +584,14 @@ class _PersonalizationStoryViewerState extends State StoriesPollsApi? _pollsApi; + /// Карточки опросов, которые держат слайд: их может быть несколько на слайде. + final Set _pollHolds = {}; + + void _pollHold(Object card, bool held) { + held ? _pollHolds.add(card) : _pollHolds.remove(card); + if (mounted) _setPaused(StoriesPauseReason.poll, _pollHolds.isNotEmpty); + } + // Куда отправлять ответы опросов: транспорт режима v3, иначе HTTP API v3 хоста // просмотра; без транспорта, API v3 или [PersonalizationStoryViewer.sdk] — `null`, // опросы не рисуются. @@ -1038,9 +1048,7 @@ class _PersonalizationStoryViewerState extends State pollTexts: _v3?.pollTexts ?? const StoryPollTexts(), pollShopId: _shopId, pollDid: widget.sdk == null ? '' : StoriesApiV3.knownDid(widget.sdk!), - onPollHold: (held) { - if (mounted) _setPaused(StoriesPauseReason.poll, held); - }, + onPollHold: _pollHold, v3: _byType, hasAudio: live && _videoSound, onHeader: _header, diff --git a/lib/src/ui/widgets/stories_poll.dart b/lib/src/ui/widgets/stories_poll.dart index afa81c0..5e49f0c 100644 --- a/lib/src/ui/widgets/stories_poll.dart +++ b/lib/src/ui/widgets/stories_poll.dart @@ -654,10 +654,6 @@ class StoryPollController extends ChangeNotifier { } } -/// Опрос слайда — первый элемент `poll`; нет — `null`. -StoryPollElement? storyPollOf(StorySlide slide) { - for (final element in slide.elements) { - if (element is StoryPollElement) return element; - } - return null; -} +/// Опросы слайда — все элементы `poll` по порядку, как их рисует веб. +List storyPollsOf(StorySlide slide) => + slide.elements.whereType().toList(); diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index 94d1d11..71a1d45 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -43,9 +43,9 @@ import 'stories_support.dart'; /// - Медиа не загрузилось — по центру кнопка кита [PersonalizationStoryViewer.retryText]. /// - У слайда есть ссылка «Поделиться» ([storySlideShareUrl]) и задан [onShare] — в шапке /// кнопка слева от крестика. -/// - Опрос слайда ([storyPollOf]) при заданном [pollsTransport] — карточка -/// [PersonalizationStoryPoll] на `y_offset`% высоты всего слайда, и на товарном слайде -/// тоже, но целиком между шапкой и нижними кнопками; не влезает — прокрутка в ней. +/// - Опросы слайда ([storyPollsOf]) при заданном [pollsTransport] — каждый своей +/// карточкой [PersonalizationStoryPoll] на своём `y_offset`% высоты всего слайда, и на +/// товарном слайде тоже; не влезает — прокрутка в ней. /// Открыта клавиатура — карточка над ней (+16), слайд не сжимается, тап мимо /// карточки только прячет клавиатуру. /// @@ -140,8 +140,9 @@ class StorySlideView extends StatelessWidget { final String pollShopId; final String pollDid; - /// Опрос держит слайд (`true`) или отпускает. - final ValueChanged? onPollHold; + /// Карточка опроса [card] держит слайд (`true`) или отпускает: у слайда их может быть + /// несколько, слайд стоит, пока держит хоть одна. + final void Function(Object card, bool held)? onPollHold; /// Слайд новой ленты (API v3): правила веба, см. описание класса. final bool v3; @@ -706,9 +707,9 @@ class StorySlideView extends StatelessWidget { poll: poll, ); - /// Опрос, который рисуется: есть элемент и транспорт. - StoryPollElement? _pollOf(StorySlide slide) => - pollsTransport == null ? null : storyPollOf(slide); + /// Опросы, которые рисуются: есть элементы и транспорт. + List _pollsOf(StorySlide slide) => + pollsTransport == null ? const [] : storyPollsOf(slide); /// Открыта клавиатура (поле опроса живого слайда). bool _keyboardOpen(BuildContext context) => @@ -723,20 +724,13 @@ class StorySlideView extends StatelessWidget { StorySlide slide, { required double bottom, }) { - final poll = _pollOf(slide); + final polls = _pollsOf(slide); final transport = pollsTransport; - if (poll == null || transport == null) return const []; + if (polls.isEmpty || transport == null) return const []; final safeBottom = MediaQuery.viewPaddingOf(outer).bottom; - return [ - Positioned.fill( - child: Builder( - builder: (context) => IgnorePointer( - ignoring: !_keyboardOpen(context), - child: _keyboardBarrier(), - ), - ), - ), - Positioned.fill( + Widget card(int index, StoryPollElement poll) { + final key = 'poll-${slide.id}-$index'; + return Positioned.fill( child: Builder( builder: (context) { final keyboard = live @@ -756,7 +750,7 @@ class StorySlideView extends StatelessWidget { child: IgnorePointer( ignoring: !live, child: PersonalizationStoryPoll( - key: ValueKey('poll-${slide.id}'), + key: ValueKey(key), poll: poll, storyId: story.id, slideId: slide.id, @@ -765,13 +759,25 @@ class StorySlideView extends StatelessWidget { did: pollDid, texts: pollTexts, live: live, - onHold: onPollHold, + onHold: (held) => onPollHold?.call(key, held), ), ), ); }, ), + ); + } + + return [ + Positioned.fill( + child: Builder( + builder: (context) => IgnorePointer( + ignoring: !_keyboardOpen(context), + child: _keyboardBarrier(), + ), + ), ), + for (var i = 0; i < polls.length; i++) card(i, polls[i]), ]; } @@ -792,7 +798,7 @@ class StorySlideView extends StatelessWidget { /// Шапка и нижняя строка слайда с опросом при открытой клавиатуре не нажимаются: тап /// по ним достаётся подложке и только прячет клавиатуру. Widget _keyboardShield(Widget child) { - if (_pollOf(slide) == null) return child; + if (_pollsOf(slide).isEmpty) return child; return Builder( builder: (context) => IgnorePointer(ignoring: _keyboardOpen(context), child: child), diff --git a/test/ui/stories_poll_widget_test.dart b/test/ui/stories_poll_widget_test.dart index 1a836cf..8a772ae 100644 --- a/test/ui/stories_poll_widget_test.dart +++ b/test/ui/stories_poll_widget_test.dart @@ -219,6 +219,42 @@ void main() { expect((rect.left, rect.right), (12, _screen.width - 12)); }); + testWidgets('every poll of a slide is drawn at its own y_offset; the slide ' + 'stands while any card holds it', (tester) async { + final top = _poll('mini_poll', kind: 'single_choice', yOffset: 10); + final bottom = _poll('nps', yOffset: 60); + await open( + tester, + _stories(>>[ + >[ + _slide('1', >[top, bottom]), + _slide('2'), + ], + ]), + ); + expect(card, findsNWidgets(2)); + final first = tester.getRect(card.first); + final second = tester.getRect(card.last); + expect(first.top, closeTo(_screen.height * 0.1, 0.5)); + expect(second.top, closeTo(_screen.height * 0.6, 0.5)); + + // A finger on the first card, the second sends and lets go: still held. + final finger = await tester.startGesture( + tester.getCenter(find.text('Q mini_poll single_choice')), + ); + await tester.pump(); + await tester.tap(find.text('7')); + await tester.pump(); + expect(transport.bodies.single['rate'], 7); + transport.pending.single.complete(const StoryPollReply()); + await _replied(tester); + await _wait(tester, const Duration(milliseconds: 1500)); + expect(find.text('Slide 1'), findsOneWidget, reason: 'the first one holds'); + await finger.up(); + await _wait(tester, const Duration(milliseconds: 1500)); + expect(find.text('Slide 2'), findsOneWidget); + }); + testWidgets('taps, holds and swipes on the card stay on it', (tester) async { await open( tester, From 2823dee864c352477bdc9487e181df421c8882f2 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 14:36:59 +0400 Subject: [PATCH 20/24] fix(stories): a poll card over API v3 keeps 16 from the sides instead of 12, and a card lifted to fit stays 16 above the bottom row (the sound button, Used products) while it is shown, else 16 above the safe area's bottom --- .../personalization_story_poll.dart | 4 +-- lib/src/ui/widgets/stories_slide_view.dart | 28 ++++++++++++++----- test/ui/stories_poll_widget_test.dart | 27 ++++++++++++++++-- 3 files changed, 48 insertions(+), 11 deletions(-) diff --git a/lib/src/ui/components/personalization_story_poll.dart b/lib/src/ui/components/personalization_story_poll.dart index 69e5c84..485b629 100644 --- a/lib/src/ui/components/personalization_story_poll.dart +++ b/lib/src/ui/components/personalization_story_poll.dart @@ -54,7 +54,7 @@ abstract final class _Poll { // Размеры. static const double maxWidth = 420; - static const double edge = PersonalizationSpacing.lg; + static const double edge = PersonalizationSpacing.xl; static const double radius = PersonalizationRadius.xl6; static const double padding = PersonalizationSpacing.xl2; static const double blur = 20; @@ -166,7 +166,7 @@ class PersonalizationStoryPoll extends StatefulWidget { final bool live; final ValueChanged? onHold; - /// Ширина карточки на слайде шириной [width]: по 12 от краёв, не шире 420. + /// Ширина карточки на слайде шириной [width]: по 16 от краёв, не шире 420. static double widthFor(double width) => (width - 2 * _Poll.edge).clamp(0, _Poll.maxWidth).toDouble(); diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index 71a1d45..c1ffa03 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -679,6 +679,9 @@ class StorySlideView extends StatelessWidget { // --- Опрос и место блоков ------------------------------------------------------------ + /// Высота нижней строки слайда: звук, «Используемые товары». + static const double _rowHeight = 64; + /// Верх места блоков слайда (опрос, текстовые блоки): под шапкой, с зазором 8. static const double _blockTop = 16 + PersonalizationStoryNavigation.height + 8; @@ -696,6 +699,7 @@ class StorySlideView extends StatelessWidget { required double bottom, double keyboard = 0, bool poll = false, + double row = 0, }) => _SlideBlockLayout( yOffset: yOffset, // Отступы SafeArea слайда (снизу — системный и при клавиатуре). @@ -705,6 +709,7 @@ class StorySlideView extends StatelessWidget { bottom: bottom, keyboard: keyboard, poll: poll, + row: row, ); /// Опросы, которые рисуются: есть элементы и транспорт. @@ -746,6 +751,8 @@ class StorySlideView extends StatelessWidget { bottom: bottom, keyboard: keyboard, poll: true, + // Нижняя строка (звук, «Используемые товары») видна — карточка над ней. + row: _hasRow(slide) ? _rowHeight : 0, ), child: IgnorePointer( ignoring: !live, @@ -811,10 +818,12 @@ class StorySlideView extends StatelessWidget { /// и местом нижних кнопок [bottom]; выше этого места — от его верха. /// /// Карточка опроса ([poll]) — как в вебе: по центру, шириной -/// [PersonalizationStoryPoll.widthFor], верх на [yOffset]%, а не влезает — поднимается, -/// чтобы низ был на 16 выше низа слайда, но не выше его верха; шапку и нижние кнопки -/// она может накрыть. Выше слайда — ниже высотой, прокрутка внутри. Клавиатура -/// перекрывает слайд снизу на [keyboard] — карточка поднимается над ней на 16. +/// [PersonalizationStoryPoll.widthFor], верх на [yOffset]% всего слайда (не выше верха +/// SafeArea), а не влезает — поднимается, чтобы низ был на 16 выше нижней строки [row] +/// (звук, «Используемые товары»), когда она видна, иначе на 16 выше низа SafeArea, но не +/// выше её верха; шапку и кнопки слайда она может накрыть. Выше слайда — ниже высотой, +/// прокрутка внутри. Клавиатура перекрывает слайд снизу на [keyboard] — карточка +/// поднимается над ней на 16. /// Текстовый блок — во всю ширину с полями 16, своей высоты. /// /// Раскладка — в области SafeArea: [above] и [below] — отступы её от краёв слайда. @@ -827,6 +836,7 @@ class _SlideBlockLayout extends SingleChildLayoutDelegate { required this.bottom, this.keyboard = 0, this.poll = false, + this.row = 0, }); final double yOffset; @@ -837,9 +847,12 @@ class _SlideBlockLayout extends SingleChildLayoutDelegate { final double keyboard; final bool poll; + /// Высота видимой нижней строки слайда; нет её — 0. + final double row; + static const double _aboveKeyboard = 16; - /// Зазор карточки опроса до низа слайда. + /// Зазор карточки опроса до нижней строки или низа SafeArea. static const double _pollMargin = 16; /// Поля текстового блока слева и справа. @@ -850,7 +863,7 @@ class _SlideBlockLayout extends SingleChildLayoutDelegate { /// Ниже этого низ блока не опускается. double _limit(Size size) { - var limit = poll ? size.height - _pollMargin : size.height - bottom; + var limit = poll ? size.height - row - _pollMargin : size.height - bottom; if (keyboard > 0) { limit = math.min(limit, size.height - keyboard - _aboveKeyboard); } @@ -890,7 +903,8 @@ class _SlideBlockLayout extends SingleChildLayoutDelegate { oldDelegate.top != top || oldDelegate.bottom != bottom || oldDelegate.keyboard != keyboard || - oldDelegate.poll != poll; + oldDelegate.poll != poll || + oldDelegate.row != row; } /// Касание слайда по третям; касания карточки опроса и подложки клавиатуры diff --git a/test/ui/stories_poll_widget_test.dart b/test/ui/stories_poll_widget_test.dart index 8a772ae..0ef0713 100644 --- a/test/ui/stories_poll_widget_test.dart +++ b/test/ui/stories_poll_widget_test.dart @@ -213,10 +213,10 @@ void main() { await open(tester, stories); expect(card, findsOneWidget); expect(find.text('Q mini_poll single_choice'), findsOneWidget); - // y_offset 50 of the slide, 12 from the edges, centred. + // y_offset 50 of the slide, 16 from the edges, centred. final rect = tester.getRect(card); expect(rect.top, _screen.height / 2); - expect((rect.left, rect.right), (12, _screen.width - 12)); + expect((rect.left, rect.right), (16, _screen.width - 16)); }); testWidgets('every poll of a slide is drawn at its own y_offset; the slide ' @@ -1173,6 +1173,29 @@ void main() { expect(rects[5], rects[4]); }); + testWidgets('a visible bottom row: the card stays 16 above it', ( + tester, + ) async { + await open( + tester, + _stories(>>[ + >[ + _slide('1', >[ + _poll('nps', yOffset: 150), + { + 'type': 'products', + 'products': >[ + {'id': 'p1', 'name': 'Product', 'price': 1}, + ], + }, + ]), + ], + ]), + ); + expect(find.text('Used products'), findsOneWidget); + expect(tester.getRect(card).bottom, _screen.height - 64 - 16); + }); + group('PersonalizationStories', () { late _HostApi api; late PersonalizationSdk sdk; From 02c046bc989d138903653c3cb7941605967c0048 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 14:38:45 +0400 Subject: [PATCH 21/24] fix(stories): the header of a slide over API v3 has a 40 icon, 12 to its text, under the cross row, and text blocks are laid out with it so they stand below it instead of under it, their y_offset still measured from the whole slide --- lib/src/ui/widgets/stories_slide_view.dart | 98 +++++++++++++++++++--- test/ui/stories_v3_rules_test.dart | 62 ++++++++++++++ 2 files changed, 148 insertions(+), 12 deletions(-) diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index c1ffa03..b1be561 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -441,24 +441,32 @@ class StorySlideView extends StatelessWidget { final buttons = storyButtons(slide); final bottom = (_hasRow(slide) ? 64 : 16) + buttons.length * _buttonSpace(context); + final header = _storyHeader(context, slide); return Stack( fit: StackFit.expand, children: [ - for (final text in texts) - Positioned.fill( - child: CustomSingleChildLayout( - delegate: _blockLayout(context, text.yOffset, bottom: bottom), - child: _textBlock(context, text), - ), + // Шапка `header` и текстовые блоки — в одной раскладке: блоки встают под шапку, + // `y_offset` у них, как у опроса, — от всего слайда. + Positioned.fill( + child: CustomMultiChildLayout( + delegate: _BodyLayout(<_SlideBlockLayout>[ + for (final text in texts) + _blockLayout(context, text.yOffset, bottom: bottom), + ]), + children: [ + for (final (index, text) in texts.indexed) + LayoutId(id: index, child: _textBlock(context, text)), + if (header != null) + LayoutId(id: _BodyLayout.header, child: header), + ], ), + ), Positioned( left: 16, right: 16, bottom: _hasRow(slide) ? 64 : 16, child: _primaryButtons(buttons), ), - if (_storyHeader(context, slide) case final header?) - Positioned(left: 16, right: 16, top: _blockTop, child: header), ..._poll(context, slide, bottom: bottom), ..._bottomRow(slide), _header(), @@ -466,8 +474,9 @@ class StorySlideView extends StatelessWidget { ); } - /// Шапка `header` слайда новой ленты: иконка в круге, заголовок и подзаголовок кита; - /// нажатие — [onHeader]. Нечего показать или не новая лента — `null`. + /// Шапка `header` слайда новой ленты под строкой крестика: иконка 40 в круге, зазор + /// 12, заголовок (SM полужирный) и подзаголовок (XS) кита; нажатие — [onHeader]. + /// Нечего показать или не новая лента — `null`. Widget? _storyHeader(BuildContext context, StorySlide slide) { final header = v3 ? storyHeaderOf(slide) : null; if (header == null) return null; @@ -492,7 +501,7 @@ class StorySlideView extends StatelessWidget { if (icon != null) ...[ ClipOval( child: SizedBox.square( - dimension: 32, + dimension: _headerIcon, child: Image( image: icon, fit: BoxFit.cover, @@ -501,7 +510,7 @@ class StorySlideView extends StatelessWidget { ), ), ), - const SizedBox(width: 8), + const SizedBox(width: _headerGap), ], Expanded( child: Column( @@ -679,6 +688,10 @@ class StorySlideView extends StatelessWidget { // --- Опрос и место блоков ------------------------------------------------------------ + /// Иконка шапки `header` и зазор от неё до текста. + static const double _headerIcon = 40; + static const double _headerGap = 12; + /// Высота нижней строки слайда: звук, «Используемые товары». static const double _rowHeight = 64; @@ -850,6 +863,18 @@ class _SlideBlockLayout extends SingleChildLayoutDelegate { /// Высота видимой нижней строки слайда; нет её — 0. final double row; + /// Та же раскладка, но не выше [top] (под шапкой `header`). + _SlideBlockLayout from(double top) => _SlideBlockLayout( + yOffset: yOffset, + above: above, + below: below, + top: top, + bottom: bottom, + keyboard: keyboard, + poll: poll, + row: row, + ); + static const double _aboveKeyboard = 16; /// Зазор карточки опроса до нижней строки или низа SafeArea. @@ -907,6 +932,55 @@ class _SlideBlockLayout extends SingleChildLayoutDelegate { oldDelegate.row != row; } +/// Шапка `header` и текстовые блоки медиа-слайда: шапка — под строкой крестика +/// ([StorySlideView._blockTop]) во всю ширину с полями 16; блоки — по своим +/// [_SlideBlockLayout] (`y_offset` от всего слайда), но не выше низа шапки с зазором 8: +/// шапка их не накрывает. +class _BodyLayout extends MultiChildLayoutDelegate { + _BodyLayout(this.blocks); + + /// Раскладки текстовых блоков; блок [i] — ребёнок с id `i`. + final List<_SlideBlockLayout> blocks; + + /// Id шапки. + static const Object header = 'header'; + + static const double _edge = 16; + static const double _gap = 8; + + @override + void performLayout(Size size) { + var top = StorySlideView._blockTop; + if (hasChild(header)) { + final height = layoutChild( + header, + BoxConstraints.tightFor(width: math.max(0, size.width - 2 * _edge)), + ).height; + positionChild(header, Offset(_edge, top)); + top += height + _gap; + } + for (var i = 0; i < blocks.length; i++) { + if (!hasChild(i)) continue; + final base = blocks[i]; + final block = top > base.top ? base.from(top) : base; + final child = layoutChild( + i, + block.getConstraintsForChild(BoxConstraints.tight(size)), + ); + positionChild(i, block.getPositionForChild(size, child)); + } + } + + @override + bool shouldRelayout(_BodyLayout oldDelegate) { + if (oldDelegate.blocks.length != blocks.length) return true; + for (var i = 0; i < blocks.length; i++) { + if (blocks[i].shouldRelayout(oldDelegate.blocks[i])) return true; + } + return false; + } +} + /// Касание слайда по третям; касания карточки опроса и подложки клавиатуры /// ([StoryPollPointers]) — не его. class _SlideTap extends TapGestureRecognizer { diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index b7b98ef..052e881 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -628,6 +628,68 @@ void main() { expect(find.byType(PersonalizationStoryViewer), findsNothing); }); + testWidgets( + 'the header: icon 40, 12 to the text, under the cross row; text ' + 'blocks stand below it', + (tester) async { + stories.add( + _story(1, >[ + { + 'id': '10', + 'type': 'image', + 'background': '', + 'duration': 30, + 'elements': >[ + { + 'type': 'header', + 'icon': 'https://cdn.example/icon.png', + 'title': 'Brand', + 'subtitle': 'Since 1990', + }, + { + 'type': 'text_block', + 'text_input': 'On top', + 'y_offset': 0, + }, + ], + }, + ]), + ); + await bar(tester); + await open(tester, 'Story 1'); + final icon = tester.getRect( + find + .descendant( + of: find.byType(ClipOval), + matching: find.byType(SizedBox), + ) + .first, + ); + expect(icon.size, const Size(40, 40)); + final title = tester.getRect(find.text('Brand')); + expect(title.left - icon.right, 12); + final cross = tester.getRect( + find.byKey(const ValueKey(PersonalizationIcons.cross)), + ); + expect(icon.top, greaterThan(cross.bottom)); + final header = tester.getRect( + find + .ancestor(of: find.text('Brand'), matching: find.byType(Row)) + .first, + ); + final text = tester.getRect( + find + .ancestor( + of: find.text('On top'), + matching: find.byType(PersonalizationStoryTextBlock), + ) + .first, + ); + expect(text.top, greaterThanOrEqualTo(header.bottom + 8)); + await tester.pump(const Duration(seconds: 1)); + }, + ); + testWidgets('the old feed draws no header', (tester) async { stories.add( _story(1, >[ From 1aca8ae3d558ae579f8203f32d4efa8b6618db50 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 15:22:09 +0400 Subject: [PATCH 22/24] fix(stories): stories over API v3 follow the last cross-platform rules: a back swipe on the first story closes the viewer as the web does, a story stepped over going back is marked viewed as going forward, a translucent background_color lies over the viewer's black also for the text scheme, and a valid opacity replaces the alpha of a #RRGGBBAA or rgba() text background while without one the colour keeps its own --- lib/src/stories/stories_header_v3.dart | 7 +- lib/src/stories/stories_response.dart | 23 ++- .../widgets/personalization_story_viewer.dart | 50 +++++- lib/src/ui/widgets/stories_playback.dart | 8 +- lib/src/ui/widgets/stories_slide_view.dart | 6 +- lib/src/ui/widgets/stories_support.dart | 17 ++- test/stories/stories_response_test.dart | 16 ++ test/ui/stories_playback_test.dart | 18 +++ test/ui/stories_v3_rules_test.dart | 142 ++++++++++++++++++ 9 files changed, 266 insertions(+), 21 deletions(-) diff --git a/lib/src/stories/stories_header_v3.dart b/lib/src/stories/stories_header_v3.dart index 0eb6ed5..8e7cdbc 100644 --- a/lib/src/stories/stories_header_v3.dart +++ b/lib/src/stories/stories_header_v3.dart @@ -49,9 +49,14 @@ class StoryHeaderElement extends StoryElement { /// Text blocks over API v3, as the web SDK reads them: `bold` (else the old `text_bold`) /// and `italic` (else `text_italic`) take `true`, `1` and `"true"`; the background /// opacity is percents as calculateOpacity reads them (`"0.5"` — 0.5 %, `"50"` and `"50%"` -/// — 50 %), and a background colour without an opacity is opaque; `font_type` is read +/// — 50 %), a background colour without an opacity is opaque, and a valid opacity +/// replaces the alpha of a colour that has its own; `font_type` is read /// regardless of case, `monospace` too. Behind the v3 gate, not the kit's. extension StoryTextBlockV3 on StoryTextBlockElement { /// The server sent `font_size`; without it API v3 takes the kit's body text size. bool get hasFontSize => _hasFontSize; + + /// A valid `text_background_color_opacity` came: it replaces the alpha of a colour that + /// has its own (`#RRGGBBAA`, `rgba()`); without it such a colour keeps its alpha. + bool get hasBackgroundOpacity => _hasOpacity; } diff --git a/lib/src/stories/stories_response.dart b/lib/src/stories/stories_response.dart index 2a58371..6a2a056 100644 --- a/lib/src/stories/stories_response.dart +++ b/lib/src/stories/stories_response.dart @@ -340,6 +340,9 @@ class StoryTextBlockElement extends StoryElement { // The server sent `font_size`: behind the v3 gate, read through [StoryTextBlockV3]. final bool _hasFontSize; + // API v3 sent a valid background opacity: read through [StoryTextBlockV3]. + final bool _hasOpacity; + const StoryTextBlockElement({ required this.text, this.fontSize = defaultFontSize, @@ -353,10 +356,12 @@ class StoryTextBlockElement extends StoryElement { this.lineSpacing = 0, this.yOffset = 0, this.promocode, - }) : _hasFontSize = true; + }) : _hasFontSize = true, + _hasOpacity = false; const StoryTextBlockElement._json( - this._hasFontSize, { + this._hasFontSize, + this._hasOpacity, { required this.text, required this.fontSize, required this.fontType, @@ -382,8 +387,12 @@ class StoryTextBlockElement extends StoryElement { }) { final promocode = json['promocode']; final fontSize = toDoubleOrNull(json['font_size']); + final opacity = v3 + ? _cssOpacity(json['text_background_color_opacity']) + : null; return StoryTextBlockElement._json( fontSize != null, + opacity != null, text: json['text_input'] as String? ?? '', fontSize: fontSize ?? defaultFontSize, fontType: json['font_type'] as String? ?? '', @@ -397,7 +406,7 @@ class StoryTextBlockElement extends StoryElement { textColor: json['text_color'] as String? ?? '', backgroundColor: json['text_background_color'] as String? ?? '', backgroundOpacity: v3 - ? _cssOpacity(json['text_background_color_opacity']) + ? opacity ?? 1 : parseStoryOpacity(json['text_background_color_opacity']), lineSpacing: toDoubleOrNull(json['text_line_spacing']) ?? 0, yOffset: toDoubleOrNull(json['y_offset']) ?? 0, @@ -514,9 +523,9 @@ final RegExp _leadingNumber = RegExp( // The opacity of a text block's background over API v3, as the web's calculateOpacity // reads it: the number (or the number a string starts with, as parseFloat) is percents — // `"0.5"` is 0.5 %, `"50"` and `"50%"` are 50 %; nothing (`null`, `""`, `0`, `false`), not -// a number or out of 0…100 — the colour as it is, opaque. -double _cssOpacity(Object? value) { - if (value == null || value == false || value == '' || value == 0) return 1; +// a number or out of 0…100 — `null`: no opacity, the colour as it is. +double? _cssOpacity(Object? value) { + if (value == null || value == false || value == '' || value == 0) return null; final double? percent = switch (value) { final num number => number.toDouble(), final String text => switch (_leadingNumber.firstMatch(text)) { @@ -526,7 +535,7 @@ double _cssOpacity(Object? value) { _ => null, }; if (percent == null || percent.isNaN || percent < 0 || percent > 100) { - return 1; + return null; } return percent / 100; } diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index a6575a3..3573a57 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -34,9 +34,11 @@ import 'stories_v3_scope.dart'; /// листает. Назад на первом слайде первой сторис перезапускает слайд — прогресс и видео /// с нуля, без перезагрузки (у новой ленты, как в вебе, закрывает просмотр); вперёд на /// последнем слайде последней — закрывает просмотр; -/// - свайп вбок листает сторис; заход на сторис (просмотр слайда, трекинг `view`) — только -/// когда страница осела, подглядывание соседней не считается. Свайп вниз дальше 120 или -/// быстрее 800 в секунду закрывает, иначе слайд пружинит назад; пока тянут — пауза; +/// - свайп вбок листает сторис (у новой ленты свайп назад на первой сторис дальше 100, +/// как в вебе, закрывает просмотр); заход на сторис (просмотр слайда, трекинг `view`) — +/// только когда страница осела, подглядывание соседней не считается. Свайп вниз дальше +/// 120 или быстрее 800 в секунду закрывает, иначе слайд пружинит назад; пока тянут — +/// пауза; /// - раскрытая шторка товаров ставит паузу и блокирует листание; тап мимо неё и системное /// «назад» её закрывают; смена слайда её сбрасывает; /// - пауза и когда приложение свёрнуто или потеряло фокус, и когда просмотр закрыт другим @@ -940,17 +942,59 @@ class _PersonalizationStoryViewerState extends State // --- Сборка ------------------------------------------------------------------------- + /// Сколько палец протянул назад за край первой сторис в текущем свайпе. + double _backPull = 0; + + /// Свайп назад на первой сторис, как в вебе (`i <= 0` — `close()`): у новой ленты + /// закрывает просмотр, когда палец ушёл за край дальше этого. + static const double _backSwipe = 100; + bool _onScroll(ScrollNotification notification) { if (notification.depth != 0) return false; if (notification is ScrollStartNotification && notification.dragDetails != null) { + _backPull = 0; _setPaused(StoriesPauseReason.drag, true); + } else if (notification is ScrollUpdateNotification) { + _pullBack(notification.metrics, notification.dragDetails); + } else if (notification is OverscrollNotification) { + _pullBack(notification.metrics, notification.dragDetails); } else if (notification is ScrollEndNotification && _pages.hasClients) { + if (_closeOnBackSwipe()) return false; _settled(_pages.page?.round() ?? _playback.storyIndex); } return false; } + /// Палец тянет назад за край первой страницы: копится путь пальца ([_backPull]). + /// Палец отпустили (дальше пружина без него) — решается, закрыть ли просмотр. + void _pullBack(ScrollMetrics metrics, DragUpdateDetails? drag) { + if (drag == null) { + _closeOnBackSwipe(); + return; + } + final delta = drag.primaryDelta; + if (delta == null || metrics.pixels > metrics.minScrollExtent) return; + // Назад — палец по оси к началу ленты: вправо в LTR, влево в RTL. + final back = metrics.axisDirection == AxisDirection.left ? -delta : delta; + _backPull = math.max(0, _backPull + back); + } + + /// Свайп назад на первой сторис новой ленты закрывает просмотр, как в вебе; `true` — + /// закрыт. + bool _closeOnBackSwipe() { + final back = _backPull; + _backPull = 0; + if (back < _backSwipe || + !_playback.serverStart || + !_playback.entered || + _playback.storyIndex != 0) { + return false; + } + _close(); + return true; + } + void _dragEnd(double velocity) { if (_drag.value > _closeDistance || velocity > _closeVelocity) { _close(); diff --git a/lib/src/ui/widgets/stories_playback.dart b/lib/src/ui/widgets/stories_playback.dart index e64cfb8..698ce88 100644 --- a/lib/src/ui/widgets/stories_playback.dart +++ b/lib/src/ui/widgets/stories_playback.dart @@ -145,7 +145,8 @@ bool storySlideSkipped(StorySlide slide) => /// просмотр закрывается ([StoriesServerProgress.open]). Сторис, где не показывается ни /// один слайд, остаётся в ленте: открыть её — то же самое. Пустого просмотра нет: /// открывать нечего — [isEmpty]. Назад на первом показываемом слайде первой сторис, как в -/// вебе, закрывает просмотр; назад в сторис, которую не открыть, перешагивает её. +/// вебе, закрывает просмотр; назад в сторис, которую не открыть, перешагивает её и +/// отмечает просмотренной, как вперёд; открыть перед ней нечего — просмотр закрывается. /// [initialSlide] у новой ленты не обходит правила, а только ставит слайд первого /// открытия начальной сторис — дальше, как у любой, где остановились. /// @@ -211,10 +212,13 @@ class StoriesPlayback { return null; } - /// Ближайшая сторис от [from] назад, которую можно открыть; нет — `null`. + /// Ближайшая сторис от [from] назад, которую можно открыть; нет — `null`. Новая + /// лента: сторис, которые перешагнули, досмотрены — просмотрены, как и при + /// листании вперёд ([StoriesServerProgress.open]). int? _openableBefore(int from) { for (var i = from; i >= 0; i--) { if (_openable(i)) return i; + StoriesServerProgress.leftForward(stories[i], finished: true); } return null; } diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index b1be561..0f413ce 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -169,8 +169,8 @@ class StorySlideView extends StatelessWidget { final media = _media(slide) != StoryMedia.none; final body = Builder(builder: (context) => _body(context, slide, media)); // Слайды с медиа — тёмные токены кита: текст и кнопки лежат на фото или видео. Свой - // цвет слайда без медиа — токены кита, у которых основной текст контрастнее с ним по - // WCAG. + // цвет слайда без медиа (уже на чёрном фоне просмотра) — токены кита, у которых + // основной текст контрастнее с ним по WCAG. final color = media ? null : _slideColor(slide); if (media) { return PersonalizationBrightness( @@ -180,7 +180,7 @@ class StorySlideView extends StatelessWidget { } if (color == null) return body; return PersonalizationBrightness( - brightness: PersonalizationBrightness.on(color.withValues(alpha: 1)), + brightness: PersonalizationBrightness.on(color), child: body, ); } diff --git a/lib/src/ui/widgets/stories_support.dart b/lib/src/ui/widgets/stories_support.dart index 4f2cf97..de2ee26 100644 --- a/lib/src/ui/widgets/stories_support.dart +++ b/lib/src/ui/widgets/stories_support.dart @@ -85,9 +85,14 @@ StoryMedia storyMediaOf(StorySlide slide, {bool byType = false}) { } /// Цвет слайда новой ленты без медиа: `background_color`, как в вебе -/// ([parseStoryCssColor]); не задан — `null`, слайд на Background/Card кита. -Color? storySlideColor(StorySlide slide) => - parseStoryCssColor(slide.backgroundColor); +/// ([parseStoryCssColor]), положенный на чёрный фон просмотра — полупрозрачный тоже; +/// по нему же выбирается схема текста. Не задан — `null`, слайд на Background/Card кита. +Color? storySlideColor(StorySlide slide) { + final color = parseStoryCssColor(slide.backgroundColor); + return color == null + ? null + : Color.alphaBlend(color, const Color(0xFF000000)); +} /// Цвет полей вокруг вписанного медиа: `background_color` слайда, без него чёрный. У /// старой ленты это единственное место, где цвет админки идёт в дело: слайд без медиа @@ -379,10 +384,12 @@ PersonalizationStoryTextBlock storyTextBlock( } /// Фон текстового блока новой ленты: цвет ([parseStoryCssColor]) с непрозрачностью -/// элемента; у цвета со своей альфой (`#RRGGBBAA`, `rgba()`) — его альфа, как в вебе. +/// элемента — она заменяет и альфу цвета (`#RRGGBBAA`, `rgba()`); без неё цвет со своей +/// альфой остаётся как есть, а без альфы — непрозрачен. Color? _newFeedBackground(StoryTextBlockElement element) { final color = parseStoryCssColor(element.backgroundColor); - if (color == null || color.a < 1) return color; + if (color == null) return null; + if (!element.hasBackgroundOpacity) return color; return color.withValues(alpha: element.backgroundOpacity.clamp(0, 1)); } diff --git a/test/stories/stories_response_test.dart b/test/stories/stories_response_test.dart index 3bf66b3..4b4d9e2 100644 --- a/test/stories/stories_response_test.dart +++ b/test/stories/stories_response_test.dart @@ -357,6 +357,22 @@ void main() { reason: 'no opacity — opaque', ); + expect( + v3({ + 'text_background_color_opacity': '50%', + }).hasBackgroundOpacity, + isTrue, + ); + for (final none in [null, '', 0, 'abc', '110']) { + expect( + v3({ + 'text_background_color_opacity': none, + }).hasBackgroundOpacity, + isFalse, + reason: '$none', + ); + } + final legacy = StoryTextBlockElement.fromJson(const { 'type': 'text_block', 'bold': 1, diff --git a/test/ui/stories_playback_test.dart b/test/ui/stories_playback_test.dart index 10085b3..3acfc2e 100644 --- a/test/ui/stories_playback_test.dart +++ b/test/ui/stories_playback_test.dart @@ -242,6 +242,24 @@ void main() { expect(back.settle(0), StoriesStep.close, reason: 'nothing before it'); }); + test('back over such a story marks it viewed, as forward does; nothing ' + 'before it — close', () { + final a = _feedStory('a', 'm'); + final b = _feedStory('b', 'ss'); + final c = _feedStory('c', 'm'); + final playback = _open(feed([a, b, c], initial: 2)); + expect(playback.story, c); + expect(playback.previous(), StoriesStep.turn); + expect(playback.turnTarget, 0); + expect(StoriesServerProgress.viewedOf(b), isTrue); + expect(StoriesServerProgress.viewedOf(a), isFalse); + + final x = _feedStory('x', 's'); + final first = _open(feed([x, _feedStory('y', 'm')], initial: 1)); + expect(first.previous(), StoriesStep.close); + expect(StoriesServerProgress.viewedOf(x), isTrue); + }); + test('a link slide only sets the first open', () { final a = _feedStory('a', 'mmm'); final playback = _open(feed([a], slide: 1)); diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index 052e881..aa81d7a 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -5,6 +5,7 @@ import 'dart:async'; import 'dart:convert'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -444,6 +445,79 @@ void main() { expect(brightness('Product b'), Brightness.dark); }); + testWidgets('a translucent slide colour lies over the black of the viewer, ' + 'also for the text scheme', (tester) async { + Brightness? brightness(String text) => tester + .widget( + find + .ancestor( + of: find.text(text), + matching: find.byType(PersonalizationBrightness), + ) + .first, + ) + .brightness; + stories.add( + _story(1, >[ + _slide( + '10', + type: '', + color: 'rgba(255, 255, 255, 0.2)', + elements: [_product('a')], + ), + ]), + ); + await bar(tester); + await open(tester, 'Story 1'); + expect(slideColor(tester, 'Product a'), const Color(0xFF333333)); + expect( + brightness('Product a'), + Brightness.dark, + reason: 'white at 20 % over black is dark: the light text', + ); + }); + + testWidgets('a valid opacity replaces the alpha of #RRGGBBAA; without one ' + 'the colour keeps its own', (tester) async { + stories.add( + _story(1, >[ + _slide( + '10', + elements: >[ + { + 'type': 'text_block', + 'text_input': 'Replaced', + 'text_background_color': '#11223380', + 'text_background_color_opacity': '25%', + 'y_offset': 30, + }, + { + 'type': 'text_block', + 'text_input': 'Own', + 'text_background_color': 'rgba(17, 34, 51, 0.5)', + 'y_offset': 50, + }, + ], + ), + ]), + ); + await bar(tester); + await open(tester, 'Story 1'); + Color? background(String text) => tester + .widget( + find.ancestor( + of: find.text(text), + matching: find.byType(PersonalizationStoryTextBlock), + ), + ) + .background; + expect( + background('Replaced'), + const Color(0xFF112233).withValues(alpha: 0.25), + ); + expect(background('Own'), const Color.fromARGB(128, 17, 34, 51)); + }); + testWidgets('the old feed keeps the kit card colour', (tester) async { stories.add( _story(1, >[ @@ -800,6 +874,74 @@ void main() { await tester.pump(const Duration(seconds: 3)); }); }); + group('a back swipe on the first story closes the viewer, as the web', () { + Future swipeBack(WidgetTester tester) async { + await tester.drag( + find.byType(PersonalizationStoryViewer), + const Offset(250, 0), + ); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + } + + for (final platform in [ + TargetPlatform.android, + TargetPlatform.iOS, + ]) { + testWidgets('${platform.name}: closes; a short pull does not', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = platform; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + stories.addAll(>[ + _story(1, >[_slide('10', duration: 30)]), + _story(2, >[_slide('20', duration: 30)]), + ]); + await bar(tester); + await open(tester, 'Story 1'); + await tester.drag( + find.byType(PersonalizationStoryViewer), + const Offset(40, 0), + ); + await settle(tester); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + await swipeBack(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + debugDefaultTargetPlatformOverride = null; + }); + } + + testWidgets('not on the second story: back to the first', (tester) async { + stories.addAll(>[ + _story(1, >[_slide('10', duration: 30)]), + _story(2, >[_slide('20', duration: 30)]), + ]); + await bar(tester); + await open(tester, 'Story 2'); + await tester.fling( + find.byType(PersonalizationStoryViewer), + const Offset(500, 0), + 1500, + ); + for (var i = 0; i < 20; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.text('Slide 10'), findsOneWidget); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + }); + + testWidgets('the old feed stays open', (tester) async { + stories.add( + _story(1, >[_slide('10', duration: 30)]), + ); + await bar(tester, v3: false); + await open(tester, 'Story 1'); + await swipeBack(tester); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + }); + }); + group('a slide with no media and no product is skipped, as the web', () { Map skipped(String id) => _slide(id, type: '', duration: 30, color: '#112233'); From d440106c3b7f9787358ec83f02fc33ad355ae0c3 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 16:36:51 +0400 Subject: [PATCH 23/24] fix(stories): over API v3 a forward swipe on the last story marks it viewed and closes the viewer, and a vertical swipe longer than 100 up or down closes it, as the web SDK does; swipes are measured from the touch, as the web measures them, and the old feed keeps its swipes --- .../widgets/personalization_story_viewer.dart | 173 ++++++++++++------ lib/src/ui/widgets/stories_playback.dart | 8 + test/ui/stories_playback_test.dart | 12 ++ test/ui/stories_v3_rules_test.dart | 105 +++++++++++ 4 files changed, 237 insertions(+), 61 deletions(-) diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index 3573a57..19861d3 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -35,10 +35,11 @@ import 'stories_v3_scope.dart'; /// с нуля, без перезагрузки (у новой ленты, как в вебе, закрывает просмотр); вперёд на /// последнем слайде последней — закрывает просмотр; /// - свайп вбок листает сторис (у новой ленты свайп назад на первой сторис дальше 100, -/// как в вебе, закрывает просмотр); заход на сторис (просмотр слайда, трекинг `view`) — -/// только когда страница осела, подглядывание соседней не считается. Свайп вниз дальше -/// 120 или быстрее 800 в секунду закрывает, иначе слайд пружинит назад; пока тянут — -/// пауза; +/// как в вебе, закрывает просмотр, а вперёд на последней — отмечает её просмотренной и +/// закрывает); заход на сторис (просмотр слайда, трекинг `view`) — только когда страница +/// осела, подглядывание соседней не считается. Свайп вниз дальше 120 или быстрее 800 в +/// секунду закрывает (у новой ленты, как в вебе, — вверх или вниз дальше 100), иначе +/// слайд пружинит назад; пока тянут — пауза; /// - раскрытая шторка товаров ставит паузу и блокирует листание; тап мимо неё и системное /// «назад» её закрывают; смена слайда её сбрасывает; /// - пауза и когда приложение свёрнуто или потеряло фокус, и когда просмотр закрыт другим @@ -942,61 +943,104 @@ class _PersonalizationStoryViewerState extends State // --- Сборка ------------------------------------------------------------------------- - /// Сколько палец протянул назад за край первой сторис в текущем свайпе. - double _backPull = 0; + /// Свайп у новой ленты, как в вебе (`swipeLength`): путь пальца от касания до + /// отпускания дальше этого. Назад на первой сторис (`i <= 0` — `close()`) и вперёд на + /// последней (`next` — просмотрена и `close()`) закрывают просмотр; вертикальный свайп + /// вверх или вниз — тоже. + static const double _swipe = 100; + + /// Палец текущего свайпа: где коснулся и где сейчас (путь — как в вебе, от касания, + /// вместе с порогом распознавания жеста). + int? _finger; + Offset _fingerDown = Offset.zero; + Offset _fingerAt = Offset.zero; + + /// В текущем свайпе лента упиралась в начало (первая страница) или в конец. + bool _atStart = false; + bool _atEnd = false; + + /// Путь пальца с касания. + Offset get _swiped => _fingerAt - _fingerDown; + + void _onPointerDown(PointerDownEvent event) { + if (_finger != null) return; + _finger = event.pointer; + _fingerDown = _fingerAt = event.position; + } + + void _onPointerMove(PointerMoveEvent event) { + if (event.pointer == _finger) _fingerAt = event.position; + } - /// Свайп назад на первой сторис, как в вебе (`i <= 0` — `close()`): у новой ленты - /// закрывает просмотр, когда палец ушёл за край дальше этого. - static const double _backSwipe = 100; + void _onPointerUp(PointerEvent event) { + if (event.pointer != _finger) return; + _fingerAt = event.position; + _finger = null; + } bool _onScroll(ScrollNotification notification) { if (notification.depth != 0) return false; if (notification is ScrollStartNotification && notification.dragDetails != null) { - _backPull = 0; + _atStart = _atEnd = false; _setPaused(StoriesPauseReason.drag, true); } else if (notification is ScrollUpdateNotification) { - _pullBack(notification.metrics, notification.dragDetails); + _edge(notification.metrics, notification.dragDetails); } else if (notification is OverscrollNotification) { - _pullBack(notification.metrics, notification.dragDetails); + _edge(notification.metrics, notification.dragDetails); } else if (notification is ScrollEndNotification && _pages.hasClients) { - if (_closeOnBackSwipe()) return false; + if (_closeOnEdgeSwipe()) return false; _settled(_pages.page?.round() ?? _playback.storyIndex); } return false; } - /// Палец тянет назад за край первой страницы: копится путь пальца ([_backPull]). - /// Палец отпустили (дальше пружина без него) — решается, закрыть ли просмотр. - void _pullBack(ScrollMetrics metrics, DragUpdateDetails? drag) { + /// Палец тянет ленту, упёртую в край, — запоминается край. Палец отпустили (дальше + /// пружина без него) — решается, закрыть ли просмотр. + void _edge(ScrollMetrics metrics, DragUpdateDetails? drag) { if (drag == null) { - _closeOnBackSwipe(); + _closeOnEdgeSwipe(); return; } - final delta = drag.primaryDelta; - if (delta == null || metrics.pixels > metrics.minScrollExtent) return; - // Назад — палец по оси к началу ленты: вправо в LTR, влево в RTL. - final back = metrics.axisDirection == AxisDirection.left ? -delta : delta; - _backPull = math.max(0, _backPull + back); + if (metrics.pixels <= metrics.minScrollExtent) _atStart = true; + if (metrics.pixels >= metrics.maxScrollExtent) _atEnd = true; } - /// Свайп назад на первой сторис новой ленты закрывает просмотр, как в вебе; `true` — + /// Свайп за край ленты у новой ленты, как в вебе: назад на первой сторис закрывает + /// просмотр, вперёд на последней — отмечает её просмотренной и закрывает; `true` — /// закрыт. - bool _closeOnBackSwipe() { - final back = _backPull; - _backPull = 0; - if (back < _backSwipe || - !_playback.serverStart || - !_playback.entered || - _playback.storyIndex != 0) { - return false; + bool _closeOnEdgeSwipe() { + final atStart = _atStart; + final atEnd = _atEnd; + _atStart = _atEnd = false; + if (!_playback.serverStart || !_playback.entered) return false; + final swiped = _swiped; + if (swiped.dx.abs() <= swiped.dy.abs()) return false; + // Назад — палец к началу ленты: вправо в LTR, влево в RTL. + final rtl = Directionality.of(context) == TextDirection.rtl; + final back = rtl ? -swiped.dx : swiped.dx; + final index = _playback.storyIndex; + if (atStart && back > _swipe && index == 0) { + _close(); + return true; } - _close(); - return true; + if (atEnd && -back > _swipe && index == _playback.stories.length - 1) { + _playback.leaveForward(); + _close(); + return true; + } + return false; } + /// Конец вертикального свайпа: у новой ленты, как в вебе, путь пальца дальше + /// [_swipe] вверх или вниз (вертикальнее, чем вбок) закрывает просмотр; у старой — + /// вниз дальше 120 или быстрее 800 в секунду. void _dragEnd(double velocity) { - if (_drag.value > _closeDistance || velocity > _closeVelocity) { + final swiped = _swiped; + final close = _playback.serverStart + ? swiped.dy.abs() > _swipe && swiped.dy.abs() > swiped.dx.abs() + : _drag.value > _closeDistance || velocity > _closeVelocity; + if (close) { _close(); return; } @@ -1019,34 +1063,41 @@ class _PersonalizationStoryViewerState extends State // приложения — с жёлтым подчёркиванием. child: DefaultTextStyle( style: const TextStyle(), - child: GestureDetector( - onVerticalDragStart: sheet - ? null - : (_) => _setPaused(StoriesPauseReason.drag, true), - onVerticalDragUpdate: sheet - ? null - : (details) => - _drag.value = math.max(0, _drag.value + details.delta.dy), - onVerticalDragEnd: sheet - ? null - : (details) => _dragEnd(details.primaryVelocity ?? 0), - onVerticalDragCancel: sheet ? null : () => _dragEnd(0), - child: ValueListenableBuilder( - valueListenable: _drag, - builder: (context, drag, child) => Transform.translate( - offset: Offset(0, drag), - child: Transform.scale( - scale: 1 - math.min(drag / 2000, 0.1), - child: child, + // Путь пальца свайпа — от касания, как в вебе. + child: Listener( + onPointerDown: _onPointerDown, + onPointerMove: _onPointerMove, + onPointerUp: _onPointerUp, + onPointerCancel: _onPointerUp, + child: GestureDetector( + onVerticalDragStart: sheet + ? null + : (_) => _setPaused(StoriesPauseReason.drag, true), + onVerticalDragUpdate: sheet + ? null + : (details) => + _drag.value = math.max(0, _drag.value + details.delta.dy), + onVerticalDragEnd: sheet + ? null + : (details) => _dragEnd(details.primaryVelocity ?? 0), + onVerticalDragCancel: sheet ? null : () => _dragEnd(0), + child: ValueListenableBuilder( + valueListenable: _drag, + builder: (context, drag, child) => Transform.translate( + offset: Offset(0, drag), + child: Transform.scale( + scale: 1 - math.min(drag / 2000, 0.1), + child: child, + ), ), - ), - child: NotificationListener( - onNotification: _onScroll, - child: PageView.builder( - controller: _pages, - physics: sheet ? const NeverScrollableScrollPhysics() : null, - itemCount: _playback.stories.length, - itemBuilder: _page, + child: NotificationListener( + onNotification: _onScroll, + child: PageView.builder( + controller: _pages, + physics: sheet ? const NeverScrollableScrollPhysics() : null, + itemCount: _playback.stories.length, + itemBuilder: _page, + ), ), ), ), diff --git a/lib/src/ui/widgets/stories_playback.dart b/lib/src/ui/widgets/stories_playback.dart index 698ce88..865c266 100644 --- a/lib/src/ui/widgets/stories_playback.dart +++ b/lib/src/ui/widgets/stories_playback.dart @@ -424,6 +424,14 @@ class StoriesPlayback { return StoriesStep.turn; } + /// Свайп вперёд с последней сторис новой ленты, как `next` веба: она просмотрена + /// (просмотр закрывается). + void leaveForward() { + if (serverStart && _entered && !isEmpty) { + StoriesServerProgress.leftForward(story); + } + } + void _turnTo(int index) { _turnTarget = index; _reasons.add(StoriesPauseReason.drag); diff --git a/test/ui/stories_playback_test.dart b/test/ui/stories_playback_test.dart index 3acfc2e..40e845d 100644 --- a/test/ui/stories_playback_test.dart +++ b/test/ui/stories_playback_test.dart @@ -260,6 +260,18 @@ void main() { expect(StoriesServerProgress.viewedOf(x), isTrue); }); + test('leaving forward past the last story marks it viewed', () { + final a = _feedStory('a', 'mm'); + final playback = _open(feed([a])); + playback.leaveForward(); + expect(StoriesServerProgress.viewedOf(a), isTrue); + expect(StoriesServerProgress.startOf(a), 0, reason: 'not finished'); + + final legacy = _story('l', 1); + _open(StoriesPlayback(stories: [legacy])).leaveForward(); + expect(StoriesServerProgress.viewedOf(legacy), isFalse); + }); + test('a link slide only sets the first open', () { final a = _feedStory('a', 'mmm'); final playback = _open(feed([a], slide: 1)); diff --git a/test/ui/stories_v3_rules_test.dart b/test/ui/stories_v3_rules_test.dart index aa81d7a..89875a8 100644 --- a/test/ui/stories_v3_rules_test.dart +++ b/test/ui/stories_v3_rules_test.dart @@ -942,6 +942,111 @@ void main() { }); }); + group('a forward swipe on the last story marks it viewed and closes the ' + 'viewer, as the web', () { + Future swipeForward(WidgetTester tester, {double by = 250}) async { + await tester.drag( + find.byType(PersonalizationStoryViewer), + Offset(-by, 0), + ); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + } + + for (final platform in [ + TargetPlatform.android, + TargetPlatform.iOS, + ]) { + testWidgets('${platform.name}: closes, viewed; a short pull does not', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = platform; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + stories.addAll(>[ + _story(1, >[_slide('10', duration: 30)]), + _story(2, >[ + _slide('20', duration: 30), + _slide('21', duration: 30), + ]), + ]); + await bar(tester); + await open(tester, 'Story 2'); + await swipeForward(tester, by: 60); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + await swipeForward(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(cover(tester, 1), PersonalizationStoryCoverState.viewed); + expect(cover(tester, 0), PersonalizationStoryCoverState.unviewed); + debugDefaultTargetPlatformOverride = null; + }); + } + + testWidgets('the old feed stays open', (tester) async { + stories.add( + _story(1, >[_slide('10', duration: 30)]), + ); + await bar(tester, v3: false); + await open(tester, 'Story 1'); + await swipeForward(tester); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + }); + }); + + group( + 'a vertical swipe over 100, up or down, closes the viewer, as the web', + () { + Future swipe(WidgetTester tester, double dy) async { + await tester.drag( + find.byType(PersonalizationStoryViewer), + Offset(0, dy), + ); + await settle(tester); + } + + testWidgets('up and down close; 80 does not', (tester) async { + stories.add( + _story(1, >[_slide('10', duration: 30)]), + ); + await bar(tester); + await open(tester, 'Story 1'); + await swipe(tester, 80); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + await swipe(tester, -80); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + await swipe(tester, -150); + expect( + find.byType(PersonalizationStoryViewer), + findsNothing, + reason: 'up', + ); + await open(tester, 'Story 1'); + await swipe(tester, 150); + expect( + find.byType(PersonalizationStoryViewer), + findsNothing, + reason: 'down', + ); + }); + + testWidgets('the old feed: up does nothing, down over 120 closes', ( + tester, + ) async { + stories.add( + _story(1, >[_slide('10', duration: 30)]), + ); + await bar(tester, v3: false); + await open(tester, 'Story 1'); + await swipe(tester, -200); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + await swipe(tester, 110); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + await swipe(tester, 200); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + }); + }, + ); + group('a slide with no media and no product is skipped, as the web', () { Map skipped(String id) => _slide(id, type: '', duration: 30, color: '#112233'); From dbc8cc3c2e6e841f379732d680f253ffa319b741 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Mon, 23 Nov 2026 19:49:45 +0400 Subject: [PATCH 24/24] fix(stories): the built-in poll texts of stories over API v3 are the web SDK's English constants (Answer again, Failed to send the answer. Please try again, Send) whatever the device language, replaced by the element's labels and the poll's submit_label as on the web; the host's poll texts of PersonalizationStoriesV3 and handleLink take these defaults again, as on master --- .../personalization_story_poll.dart | 15 ++---- .../widgets/personalization_stories_v3.dart | 33 ++++++------ lib/src/ui/widgets/stories_poll.dart | 52 +++++++------------ test/ui/stories_poll_test.dart | 31 +++-------- test/ui/stories_poll_widget_test.dart | 26 ++++++++-- 5 files changed, 68 insertions(+), 89 deletions(-) diff --git a/lib/src/ui/components/personalization_story_poll.dart b/lib/src/ui/components/personalization_story_poll.dart index 485b629..4d96e3d 100644 --- a/lib/src/ui/components/personalization_story_poll.dart +++ b/lib/src/ui/components/personalization_story_poll.dart @@ -136,7 +136,8 @@ abstract final class _Poll { /// полос (Danger, Warning, зелёный опроса), после ответа выбранная оценка, остальные /// приглушены и не нажимаются; дальше вопрос полосы с полем комментария (до 5000, со /// счётчиком) или её `success`. Вид — токены кита. -/// - Встроенные тексты — по языку устройства ([StoryPollTexts]). +/// - Встроенные тексты — английские константы веба ([StoryPollTexts]), `labels` опроса и +/// его `submit_label` важнее. /// - RTL: поля, полоски итогов и шкала зеркалятся. class PersonalizationStoryPoll extends StatefulWidget { const PersonalizationStoryPoll({ @@ -236,12 +237,6 @@ class _PersonalizationStoryPollState extends State } } - @override - void didChangeLocales(List? locales) { - // Встроенные тексты — по языку устройства. - if (mounted) setState(() {}); - } - @override void dispose() { WidgetsBinding.instance.removeObserver(this); @@ -414,10 +409,8 @@ class _PersonalizationStoryPollState extends State /// Содержимое карточки по виду и состоянию: строки и зазор перед каждой. extension on _PersonalizationStoryPollState { - /// Тексты карточки: `labels`, хост, встроенные по языку устройства. - StoryPollTexts get _texts => _poll.textsFor( - WidgetsBinding.instance.platformDispatcher.locale.languageCode, - ); + /// Тексты карточки: `labels`, хост, английские умолчания веба. + StoryPollTexts get _texts => _poll.texts; List<(Widget, double)> _body( PersonalizationTheme theme, diff --git a/lib/src/ui/widgets/personalization_stories_v3.dart b/lib/src/ui/widgets/personalization_stories_v3.dart index 2594048..33ff7f4 100644 --- a/lib/src/ui/widgets/personalization_stories_v3.dart +++ b/lib/src/ui/widgets/personalization_stories_v3.dart @@ -43,9 +43,9 @@ class PersonalizationStoriesV3 extends StatelessWidget { this.shareLabel = 'Share', this.shareUrlTransform, this.pollsTransport, - this.pollReanswerText, - this.pollSubmitText, - this.pollErrorText, + this.pollReanswerText = 'Answer again', + this.pollSubmitText = 'Send', + this.pollErrorText = 'Failed to send the answer. Please try again', required this.child, }) : ownApiV3Domain = apiV3Domain; @@ -67,11 +67,10 @@ class PersonalizationStoriesV3 extends StatelessWidget { /// Тексты карточки опроса: ссылка «Ответить заново», кнопка отправки без своей подписи /// опроса (и кнопка комментария к оценке шкалы) и ошибка отправки. Непустые `labels` - /// опроса от сервера важнее; `null` или пусто — встроенные по языку устройства - /// (русские или английские). - final String? pollReanswerText; - final String? pollSubmitText; - final String? pollErrorText; + /// опроса от сервера важнее; пусто — английские умолчания веба, на любом языке. + final String pollReanswerText; + final String pollSubmitText; + final String pollErrorText; /// Поддерево в режиме v3. final Widget child; @@ -93,9 +92,9 @@ class PersonalizationStoriesV3 extends StatelessWidget { shareUrlTransform: shareUrlTransform, pollsTransport: pollsTransport, pollTexts: StoryPollTexts( - reanswer: pollReanswerText ?? '', - error: pollErrorText ?? '', - submit: pollSubmitText ?? '', + reanswer: pollReanswerText, + error: pollErrorText, + submit: pollSubmitText, ), ), child: child, @@ -147,9 +146,9 @@ class PersonalizationStoriesV3 extends StatelessWidget { iconBuilder, String Function(String url)? shareUrlTransform, StoryPollsTransport? pollsTransport, - String? pollReanswerText, - String? pollSubmitText, - String? pollErrorText, + String pollReanswerText = 'Answer again', + String pollSubmitText = 'Send', + String pollErrorText = 'Failed to send the answer. Please try again', String? apiV3Domain, }) { final link = parseStoriesShareLink(url); @@ -186,9 +185,9 @@ class PersonalizationStoriesV3 extends StatelessWidget { shareUrlTransform: shareUrlTransform, pollsTransport: pollsTransport, pollTexts: StoryPollTexts( - reanswer: pollReanswerText ?? '', - error: pollErrorText ?? '', - submit: pollSubmitText ?? '', + reanswer: pollReanswerText, + error: pollErrorText, + submit: pollSubmitText, ), ); unawaited( diff --git a/lib/src/ui/widgets/stories_poll.dart b/lib/src/ui/widgets/stories_poll.dart index 5e49f0c..ffee616 100644 --- a/lib/src/ui/widgets/stories_poll.dart +++ b/lib/src/ui/widgets/stories_poll.dart @@ -1,6 +1,5 @@ import 'dart:async'; import 'dart:convert'; -import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -8,28 +7,21 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../../stories/stories_response.dart'; import 'stories_polls_api.dart'; -/// Тексты карточки опроса: `labels` элемента < тексты хоста < встроенные по языку -/// устройства (русские для `ru`, остальные — английские). Пустой текст хоста — не задан. +/// Тексты карточки опроса, как в вебе: `labels` элемента > тексты хоста > умолчания — +/// английские константы веба, на любом языке устройства и приложения. Пустой текст хоста +/// — не задан. @immutable class StoryPollTexts { - const StoryPollTexts({this.reanswer = '', this.error = '', this.submit = ''}); + const StoryPollTexts({ + this.reanswer = defaultReanswer, + this.error = defaultError, + this.submit = defaultSubmit, + }); - /// Встроенные русские. - static const StoryPollTexts ru = StoryPollTexts( - reanswer: 'Ответить заново', - error: 'Не удалось отправить ответ. Попробуйте еще раз', - submit: 'Отправить', - ); - - /// Встроенные английские. - static const StoryPollTexts en = StoryPollTexts( - reanswer: 'Answer again', - error: 'Failed to send the answer. Please try again', - submit: 'Send', - ); - - /// Встроенные для кода языка [language]: `ru` — русские, остальные — английские. - static StoryPollTexts builtIn(String language) => language == 'ru' ? ru : en; + static const String defaultReanswer = 'Answer again'; + static const String defaultError = + 'Failed to send the answer. Please try again'; + static const String defaultSubmit = 'Send'; /// Ссылка «Ответить заново» у отвеченного опроса с `allow_reanswer`. final String reanswer; @@ -42,17 +34,14 @@ class StoryPollTexts { final String submit; /// Тексты для [poll]: непустые `labels` сервера, иначе непустые тексты хоста, иначе - /// встроенные языка [language] (по умолчанию — устройства). - StoryPollTexts forPoll(StoryPollElement poll, {String? language}) { - final builtIn = StoryPollTexts.builtIn( - language ?? ui.PlatformDispatcher.instance.locale.languageCode, - ); + /// умолчания. + StoryPollTexts forPoll(StoryPollElement poll) { String pick(String? label, String host, String fallback) => label ?? (host.isNotEmpty ? host : fallback); return StoryPollTexts( - reanswer: pick(poll.labels.reanswer, reanswer, builtIn.reanswer), - error: pick(poll.labels.error, error, builtIn.error), - submit: pick(poll.labels.submit, submit, builtIn.submit), + reanswer: pick(poll.labels.reanswer, reanswer, defaultReanswer), + error: pick(poll.labels.error, error, defaultError), + submit: pick(poll.labels.submit, submit, defaultSubmit), ); } @@ -380,11 +369,8 @@ class StoryPollController extends ChangeNotifier { StoryPollPlace get _place => (shopId: shopId, did: did, storyId: storyId, slideId: slideId); - /// Тексты с учётом `labels` опроса — языка устройства или [language]. - StoryPollTexts textsFor([String? language]) => - hostTexts.forPoll(poll, language: language); - - StoryPollTexts get texts => textsFor(); + /// Тексты с учётом `labels` опроса. + StoryPollTexts get texts => hostTexts.forPoll(poll); StoryPollAnswer? get answer => _answer; StoryPollResults? get results => _results; diff --git a/test/ui/stories_poll_test.dart b/test/ui/stories_poll_test.dart index c237e70..b888165 100644 --- a/test/ui/stories_poll_test.dart +++ b/test/ui/stories_poll_test.dart @@ -779,7 +779,8 @@ void main() { }); group('texts', () { - test('labels of the element > texts of the host > built-in', () { + test('labels of the element > texts of the host > the web defaults, in ' + 'English whatever the language', () { const host = StoryPollTexts( reanswer: 'Answer again', error: 'Ошибка', @@ -790,40 +791,24 @@ void main() { StoryMiniPollKind.singleChoice, labels: const StoryPollLabels(reanswer: 'Ещё раз'), ), - language: 'en', ); expect(texts.reanswer, 'Ещё раз'); expect(texts.error, 'Ошибка'); - expect(texts.submit, 'Send', reason: 'an empty host text — built-in'); - final en = const StoryPollTexts().forPoll( + expect(texts.submit, 'Send', reason: 'an empty host text — the default'); + final defaults = const StoryPollTexts().forPoll( _scale(StoryPollType.nps), - language: 'de', ); - expect(en, StoryPollTexts.en); expect( - (en.reanswer, en.error, en.submit), + (defaults.reanswer, defaults.error, defaults.submit), ('Answer again', 'Failed to send the answer. Please try again', 'Send'), ); - final ru = const StoryPollTexts().forPoll( - _scale(StoryPollType.nps), - language: 'ru', - ); - expect( - (ru.reanswer, ru.error, ru.submit), - ( - 'Ответить заново', - 'Не удалось отправить ответ. Попробуйте еще раз', - 'Отправить', - ), - ); expect( - mount(_mini(StoryMiniPollKind.text), texts: host).textsFor('ru').error, + mount(_mini(StoryMiniPollKind.text), texts: host).texts.error, 'Ошибка', ); expect( - mount(_mini(StoryMiniPollKind.text), texts: host).textsFor('ru').submit, - 'Отправить', - reason: 'no untranslated fallback in a Russian UI', + mount(_mini(StoryMiniPollKind.text), texts: host).texts.submit, + 'Send', ); }); diff --git a/test/ui/stories_poll_widget_test.dart b/test/ui/stories_poll_widget_test.dart index 0ef0713..d2027fd 100644 --- a/test/ui/stories_poll_widget_test.dart +++ b/test/ui/stories_poll_widget_test.dart @@ -814,7 +814,8 @@ void main() { expect(find.text('31%'), findsOneWidget, reason: 'the same rows'); }); - testWidgets('built-in texts follow the device language', (tester) async { + testWidgets('built-in texts are the web\'s English ones, also in a Russian ' + 'UI; submit_label and labels win', (tester) async { tester.platformDispatcher.localeTestValue = const Locale('ru', 'RU'); addTearDown(tester.platformDispatcher.clearLocaleTestValue); await tester.pumpWidget( @@ -826,7 +827,22 @@ void main() { ), ), ); - expect(find.text('Отправить'), findsOneWidget); + expect(find.text('Send'), findsOneWidget); + await tester.pumpWidget( + alone( + _poll( + 'mini_poll', + kind: 'text', + fields: {'submit_label': 'Отправить идею'}, + labels: {'submit': 'Отправить'}, + ), + ), + ); + expect( + find.text('Отправить идею'), + findsOneWidget, + reason: 'submit_label', + ); await tester.pumpWidget( alone( _poll( @@ -839,7 +855,7 @@ void main() { ), ), ); - expect(find.text('Ответить заново'), findsOneWidget); + expect(find.text('Answer again'), findsOneWidget); }); testWidgets('sizes: left-aligned text, rows 56 and 8 apart, the track, ' @@ -1034,7 +1050,7 @@ void main() { expect(find.text('Что улучшить?'), findsOneWidget); expect(find.byType(TextField), findsOneWidget); expect(find.text('0/5000'), findsOneWidget); - expect(find.text('Отправить'), findsOneWidget, reason: 'localized'); + expect(find.text('Send'), findsOneWidget, reason: 'the web default'); expect(find.text('Band thanks'), findsNothing); await tester.enterText(find.byType(TextField), ' Быстрее '); await tester.pump(); @@ -1042,7 +1058,7 @@ void main() { // Focused: the slide waits. await _wait(tester, const Duration(seconds: 12)); expect(find.text('Slide 1'), findsOneWidget); - await tester.tap(find.text('Отправить')); + await tester.tap(find.text('Send')); await tester.pump(); expect(transport.bodies.last, { 'channel': 'stories',