From ca28cd809f31b07929a62c9728a3f8f0430f89c5 Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Tue, 20 Oct 2026 11:15:52 +0400 Subject: [PATCH 1/2] feat(popups): server popups over the root navigator, configurable UI theme --- README.md | 93 ++ .../rees46/rees46_flutter_sdk/PopupJson.kt | 45 + .../Rees46FlutterSdkPlugin.kt | 40 +- .../pigeon/PersonalizationApi.g.kt | 85 ++ example/lib/main.dart | 114 +- example/lib/ui_kit_pane.dart | 5 +- ios/Classes/Rees46FlutterSdkPlugin.swift | 87 +- ios/Classes/pigeon/PersonalizationApi.g.swift | 87 ++ lib/rees46_sdk.dart | 12 + lib/src/multi_instance/rees46_config.dart | 3 + lib/src/personalization_sdk.dart | 37 +- lib/src/pigeon/personalization_api.g.dart | 1170 +++++++++++------ lib/src/popups/in_app_popup.dart | 122 ++ lib/src/popups/popup_dispatcher.dart | 47 + lib/src/popups/popup_presenter.dart | 456 +++++++ lib/src/tracking/tracking_api.dart | 19 +- .../personalization_in_app_popup.dart | 244 +++- lib/src/ui/personalization_colors.dart | 108 -- lib/src/ui/personalization_theme.dart | 202 ++- lib/src/ui/widgets/stories_slide_view.dart | 42 +- pigeons/personalization_api.dart | 22 + test/popups/in_app_popup_test.dart | 167 +++ test/popups/popup_presenter_test.dart | 569 ++++++++ test/popups/popup_sdk_test.dart | 72 + .../ui/personalization_in_app_popup_test.dart | 208 ++- test/ui/personalization_theme_mode_test.dart | 211 +++ 26 files changed, 3588 insertions(+), 679 deletions(-) create mode 100644 android/src/main/kotlin/com/rees46/rees46_flutter_sdk/PopupJson.kt create mode 100644 lib/src/popups/in_app_popup.dart create mode 100644 lib/src/popups/popup_dispatcher.dart create mode 100644 lib/src/popups/popup_presenter.dart create mode 100644 test/popups/in_app_popup_test.dart create mode 100644 test/popups/popup_presenter_test.dart create mode 100644 test/popups/popup_sdk_test.dart create mode 100644 test/ui/personalization_theme_mode_test.dart diff --git a/README.md b/README.md index 9ea3884..b46724b 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ native init threw). | `stream` | `android` / `ios` | Traffic stream label; defaults to the current platform | | `autoSendPushToken` | `true` | Fetches and sends the push token during init | | `needReInitialization` | `false` | Forces a fresh session / device id | +| `enableAutoPopupPresentation` | `true` | Shows server popups without an `onPopup` handler, see [Popups](#popups) | Push delivery needs platform setup of its own — a Firebase config on Android, the Push Notifications capability on iOS. Without it initialization still succeeds; @@ -138,6 +139,98 @@ without an id resolves only while exactly one shop is registered, and throws never registered). +## Popups + +Popups made in the REES46 admin arrive with the responses to init and tracking +calls. The SDK shows them over the app's root navigator — the one `MaterialApp`, +`CupertinoApp` or `MaterialApp.router` builds — with nothing to set up. + +A popup sits in the centre, at the top or at the bottom as set in the admin, and +fills the screen when no position is set. It waits out the delay set in the admin, +one is shown at a time, and one shown within the last minute is not shown again. +The link button opens its link, the push-subscription button opens the app's +notification settings. A popup is reported as shown once it is on screen. + +To decide yourself — hold a popup back on a checkout screen, or draw it your way — +take popups with `onPopup`. The SDK then shows nothing: + +```dart +sdk.onPopup = (InAppPopup popup) { + if (onCheckout) { + held = popup; // later: sdk.presentPopup(held!) + return; + } + showDialog( + context: context, + builder: (context) => Center( + child: SizedBox( + width: 370, + // Unbounded in height, the popup takes the height of its content. + child: SingleChildScrollView( + child: PersonalizationInAppPopup( + view: popup.imageUrl == null + ? PersonalizationInAppPopupView.text + : PersonalizationInAppPopupView.image, + title: popup.title, + text: popup.text, + actionText: popup.actionText, + closeText: popup.closeText, + image: popup.imageUrl == null ? null : NetworkImage(popup.imageUrl!), + onAction: () { + Navigator.pop(context); + // Open popup.linkUrl, or the notification settings when + // popup.pushSubscribeText is set — with url_launcher, for instance. + }, + onClose: () => Navigator.pop(context), + ), + ), + ), + ), + ); + sdk.tracking.popupShown(popup.id); // the SDK reports only what it shows itself +}; +``` + +`sdk.presentPopup(popup)` shows a popup the way the SDK does and reports it. With +`enableAutoPopupPresentation: false` and no `onPopup`, popups are not shown. + +## UI theme + +The SDK's UI (popups, for now) is drawn in the REES46 design. Set your brand once, in +`main` before `runApp`; it applies in `MaterialApp`, `CupertinoApp` and without +either: + +```dart +PersonalizationTheme.configure( + lightColors: PersonalizationColors.light.copyWith( + brandPrimary: const Color(0xFF7C3AED), + buttonPrimary: const Color(0xFF7C3AED), + ), + darkColors: PersonalizationColors.dark.copyWith( + brandPrimary: const Color(0xFFA78BFA), + buttonPrimary: const Color(0xFFA78BFA), + ), + fontFamily: const PersonalizationFontFamily(regular: 'Inter', emphasized: 'Inter'), +); +``` + +- Colours are set per scheme, font and radii once for both. Anything left out stays + as designed, so start from `PersonalizationColors.light` / `.dark` and change only + what you need. +- Without `darkColors` the dark scheme takes the brand colours (brand, primary + button, brand line and text) from `lightColors`, the rest from the design. +- The font families must be declared in your `pubspec.yaml`; pass `package:` for + fonts that come from another package. + +Light or dark follows the app — its Material theme, else its Cupertino theme, else +the device setting. To keep the SDK's UI one way whatever the app is in: + +```dart +PersonalizationTheme.mode = ThemeMode.dark; // or ThemeMode.light; ThemeMode.system by default +``` + +Both settings can change at runtime; what is on screen is redrawn. + ## Track events Standard events live in the `tracking` namespace of the handle: diff --git a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/PopupJson.kt b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/PopupJson.kt new file mode 100644 index 0000000..ba4c7cc --- /dev/null +++ b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/PopupJson.kt @@ -0,0 +1,45 @@ +package com.rees46.rees46_flutter_sdk + +import com.personalization.sdk.data.models.dto.popUp.PopupDto +import org.json.JSONObject + +/** + * The popup as the server sends it — the keys the native SDK parsed it from — so Dart reads + * one shape from both platforms. + */ +internal fun PopupDto.toJson(): JSONObject = JSONObject().apply { + put("id", id) + put("position", position.value) + put("delay", delay) + components?.let { components -> + put( + "components", + JSONObject() + .put("header", components.header) + .put("text", components.text) + .put("image", components.image) + .put("button", components.button) + .put("header_enabled", components.headerEnabled) + .put("text_enabled", components.textEnabled) + .put("image_enabled", components.imageEnabled), + ) + } + popupActions?.let { actions -> + val json = JSONObject() + actions.link?.let { link -> + json.put( + "link", + JSONObject() + .put("link_android", link.linkAndroid) + .put("link_ios", link.linkIos) + .put("link_web", link.linkWeb) + .put("button_text", link.buttonText), + ) + } + actions.close?.let { json.put("close", JSONObject().put("button_text", it.buttonText)) } + actions.pushSubscribe?.let { + json.put("system_mobile_push_subscribe", JSONObject().put("button_text", it.buttonText)) + } + put("popup_actions", json) + } +} 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 635cfec..1896711 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 @@ -4,19 +4,23 @@ import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri +import android.os.Build import android.os.Bundle +import android.provider.Settings import android.os.SystemClock import com.rees46.rees46_flutter_sdk.pigeon.FlutterError import com.rees46.rees46_flutter_sdk.pigeon.InitConfig import com.rees46.rees46_flutter_sdk.pigeon.ManageSubscriptionParamsWire import com.rees46.rees46_flutter_sdk.pigeon.PersonalizationFlutterApi import com.rees46.rees46_flutter_sdk.pigeon.PersonalizationHostApi +import com.rees46.rees46_flutter_sdk.pigeon.PersonalizationPopupFlutterApi import com.rees46.rees46_flutter_sdk.pigeon.ProfileParamsWire import com.rees46.rees46_flutter_sdk.pigeon.PurchaseLineItemWire import com.rees46.rees46_flutter_sdk.pigeon.TrackingItemWire import com.rees46.rees46_flutter_sdk.pigeon.TrackingSourceWire import com.google.gson.Gson import com.personalization.Params +import com.personalization.PopupPresentationListener import com.personalization.PushEventType import com.personalization.PushProvider import com.personalization.Rees46 @@ -56,6 +60,7 @@ class Rees46FlutterSdkPlugin : private lateinit var applicationContext: Context private val coroutineScope = CoroutineScope(Dispatchers.Main + Job()) private var flutterApi: PersonalizationFlutterApi? = null + private var popupApi: PersonalizationPopupFlutterApi? = null private var activityBinding: ActivityPluginBinding? = null private val onNewIntentListener = @@ -70,11 +75,13 @@ class Rees46FlutterSdkPlugin : applicationContext = flutterPluginBinding.applicationContext PersonalizationHostApi.setUp(flutterPluginBinding.binaryMessenger, this) flutterApi = PersonalizationFlutterApi(flutterPluginBinding.binaryMessenger) + popupApi = PersonalizationPopupFlutterApi(flutterPluginBinding.binaryMessenger) } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { PersonalizationHostApi.setUp(binding.binaryMessenger, null) flutterApi = null + popupApi = null coroutineScope.cancel() } @@ -149,7 +156,16 @@ class Rees46FlutterSdkPlugin : ) // F3: initialize (and register) the instance through the multi-instance // `Rees46` facade so it is reachable by shopId via Rees46.getInstance. - Rees46.initialize(context = applicationContext, config = shopConfig) + val sdk = Rees46.initialize(context = applicationContext, config = shopConfig) + + // Dart draws popups with the UI kit: every popup is kept back from the native SDK + // (null — not shown, not reported, not remembered) and handed over. Dart decides + // whether to show it, and reports it once it is on screen. The listener runs on the + // main thread, where the Pigeon channel has to be called. + sdk.popupPresentationListener = PopupPresentationListener { _, popup -> + runCatching { popupApi?.onPopup(shopId, popup.toJson().toString()) { _ -> } } + null + } // Persist so the cold-start push provider (Rees46PushInitProvider) can re-register this // shop on a process FCM spins up before Dart runs — otherwise the registry is empty and @@ -539,6 +555,28 @@ class Rees46FlutterSdkPlugin : } } + override fun trackPopupShown(popupId: Long, shopId: String?, callback: (Result) -> Unit) = + trackingCall(callback, shopId) { + it.popupShown(popupId.toInt(), trackingListener(callback)) + } + + override fun openNotificationSettings() { + val packageName = applicationContext.packageName + val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, packageName) + } else { + Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName")) + } + val activity = activityBinding?.activity + if (activity == null) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + try { + (activity ?: applicationContext).startActivity(intent) + } catch (e: ActivityNotFoundException) { + android.util.Log.w(Rees46PushNotifier.TAG, "No notification settings screen", e) + } + } + // region stories viewer (UI kit) override fun getStoriesSeen(shop: String): Map> = 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 b9d3f24..83d816c 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 @@ -681,6 +681,18 @@ interface PersonalizationHostApi { fun trackSetSource(source: TrackingSourceWire, shopId: String?) /** [customJson] and [recommendedSourceJson] are JSON object strings or null. */ fun trackPurchase(orderId: String, orderPrice: Double, items: List, deliveryType: String?, deliveryAddress: String?, paymentType: String?, isTaxFree: Boolean, isGiftPackage: Boolean, promocode: String?, orderCash: Double?, orderBonuses: Double?, orderDelivery: Double?, orderDiscount: Double?, channel: String?, customJson: String?, recommendedSourceJson: String?, stream: String?, segment: String?, shopId: String?, callback: (Result) -> Unit) + /** + * Reports popup [popupId] as shown (`popup/showed`) — native `tracking.popupShown` + * (Android) / `trackPopupShown` (iOS). The native SDKs never show a popup themselves + * under the plugin, so they never report one either: Dart does, once it is on screen. + */ + fun trackPopupShown(popupId: Long, shopId: 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 + * native popups do for their push-subscription button. + */ + fun openNotificationSettings() companion object { /** The codec used by PersonalizationHostApi. */ @@ -1546,6 +1558,79 @@ interface PersonalizationHostApi { channel.setMessageHandler(null) } } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackPopupShown$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val popupIdArg = args[0] as Long + val shopIdArg = args[1] as String? + api.trackPopupShown(popupIdArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + reply.reply(PersonalizationApiPigeonUtils.wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openNotificationSettings$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + val wrapped: List = try { + api.openNotificationSettings() + listOf(null) + } catch (exception: Throwable) { + PersonalizationApiPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } +} +/** + * Server popups, handed over instead of being shown natively: the plugin sets the native + * presentation listener (Android) / delegate (iOS), which keeps every popup back and + * forwards it here. Separate from [PersonalizationFlutterApi], which the push dispatcher + * owns. + * + * Generated class from Pigeon that represents Flutter messages that can be called from Kotlin. + */ +class PersonalizationPopupFlutterApi(private val binaryMessenger: BinaryMessenger, private val messageChannelSuffix: String = "") { + companion object { + /** The codec used by PersonalizationPopupFlutterApi. */ + val codec: MessageCodec by lazy { + PersonalizationApiPigeonCodec() + } + } + /** + * A popup arrived for [shopId]. [popupJson] is the popup as the server sends it: + * `id`, `position`, `delay`, `components` and `popup_actions` (an object). + */ + fun onPopup(shopIdArg: String, popupJsonArg: String, callback: (Result) -> Unit) +{ + val separatedMessageChannelSuffix = if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" + val channelName = "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationPopupFlutterApi.onPopup$separatedMessageChannelSuffix" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(shopIdArg, popupJsonArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback(Result.failure(FlutterError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(PersonalizationApiPigeonUtils.createConnectionError(channelName))) + } } } } diff --git a/example/lib/main.dart b/example/lib/main.dart index db9483c..5063b03 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -5,10 +5,6 @@ import 'package:rees46_sdk/rees46_sdk.dart'; import 'app_theme_mode.dart'; import 'multi_instance_pane.dart'; -// The kit is private until release: the theme comes from the src barrel. -// ignore: implementation_imports -import 'package:rees46_sdk/src/ui/personalization_ui.dart' - show PersonalizationTheme; import 'ui_kit_pane.dart'; void main() => runApp(const App()); @@ -24,22 +20,14 @@ class App extends StatelessWidget { valueListenable: appThemeMode, builder: (context, mode, _) => MaterialApp( title: 'REES46 Flutter SDK', - // The kit's theme extension rides on ThemeData: light and dark sets - // switch together with the app's brightness. theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), - extensions: const >[ - PersonalizationTheme.light, - ], ), darkTheme: ThemeData( colorScheme: ColorScheme.fromSeed( seedColor: Colors.blue, brightness: Brightness.dark, ), - extensions: const >[ - PersonalizationTheme.dark, - ], ), themeMode: mode, home: const InitPage(), @@ -185,6 +173,7 @@ class _InitPageState extends State { bool _autoSendPushToken = true; bool _sendAdvertisingId = false; bool _enableAutoPopupPresentation = true; + bool _holdPopups = false; bool _needReInitialization = false; InitState _initState = InitState.idle; @@ -328,6 +317,8 @@ class _InitPageState extends State { needReInitialization: _needReInitialization, ), ); + // Holding popups back: the app takes each one and shows it when the user asks. + _sdk.onPopup = _holdPopups ? _holdPopup : null; _sdk.setPushNotificationCallbacks( onReceived: (payload) { // In the demo we only surface init/token state; push payloads can be @@ -354,6 +345,41 @@ class _InitPageState extends State { } } + /// A popup as the admin would send it, shown the way the SDK shows server popups. The + /// demo shops have no popups set up, so this is the way to see one. + void _showTestPopup(InAppPopupPosition position) { + final picture = + position == InAppPopupPosition.center || + position == InAppPopupPosition.unknown; + _sdk.presentPopup( + InAppPopup( + id: 990 + position.index, + position: position, + title: 'Weekend sale', + text: 'Up to 30% off home appliances until Sunday.', + imageUrl: picture + ? 'https://pictures.rees46.ru/resize-images/520/$_shopId/143748.jpg' + : null, + linkText: 'Shop now', + linkUrl: 'https://rees46.com', + closeText: position == InAppPopupPosition.top ? null : 'Not now', + ), + ); + } + + void _holdPopup(InAppPopup popup) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Popup ${popup.id} held back: ${popup.title ?? ''}'), + action: SnackBarAction( + label: 'Show', + onPressed: () => _sdk.presentPopup(popup), + ), + ), + ); + } + Future _refreshToken() async { setState(() => _tokenLoading = true); try { @@ -838,7 +864,12 @@ class _InitPageState extends State { value: _enableAutoPopupPresentation, onChanged: (v) => setState(() => _enableAutoPopupPresentation = v), - title: const Text('enableAutoPopupPresentation (iOS)'), + title: const Text('enableAutoPopupPresentation'), + ), + SwitchListTile( + value: _holdPopups, + onChanged: (v) => setState(() => _holdPopups = v), + title: const Text('Hold popups back (onPopup)'), ), SwitchListTile( value: _needReInitialization, @@ -857,6 +888,8 @@ class _InitPageState extends State { ), ), const SizedBox(height: 12), + _PopupsCard(onShow: _showTestPopup), + const SizedBox(height: 12), _ProfileCard( sid: _sid, did: _did, @@ -1048,6 +1081,61 @@ class _InitStatusCard extends StatelessWidget { } } +class _PopupsCard extends StatelessWidget { + const _PopupsCard({required this.onShow}); + + final void Function(InAppPopupPosition position) onShow; + + @override + Widget build(BuildContext context) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Popups', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 4), + const Text('A test popup in each position the admin offers.'), + const SizedBox(height: 12), + // PersonalizationTheme.mode: the SDK's UI follows the app, or stays light + // or dark whatever the app is in. + SegmentedButton( + key: const Key('seg_sdk_theme'), + segments: const [ + ButtonSegment(value: ThemeMode.system, label: Text('Auto')), + ButtonSegment(value: ThemeMode.light, label: Text('Light')), + ButtonSegment(value: ThemeMode.dark, label: Text('Dark')), + ], + selected: {PersonalizationTheme.mode}, + onSelectionChanged: (selection) => + PersonalizationTheme.mode = selection.single, + ), + const SizedBox(height: 12), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (final (label, position) in const [ + ('Centre', InAppPopupPosition.center), + ('Top', InAppPopupPosition.top), + ('Bottom', InAppPopupPosition.bottom), + ('Fullscreen', InAppPopupPosition.unknown), + ]) + OutlinedButton( + key: Key('btn_popup_${position.name}'), + onPressed: () => onShow(position), + child: Text(label), + ), + ], + ), + ], + ), + ), + ); + } +} + class _ProfileCard extends StatelessWidget { final String? sid; final String? did; diff --git a/example/lib/ui_kit_pane.dart b/example/lib/ui_kit_pane.dart index c903a10..9cb0d06 100644 --- a/example/lib/ui_kit_pane.dart +++ b/example/lib/ui_kit_pane.dart @@ -1014,9 +1014,8 @@ class _OnMediaSlide extends StatelessWidget { @override Widget build(BuildContext context) { - final base = Theme.of(context); - return Theme( - data: base.copyWith(extensions: [PersonalizationTheme.dark]), + return PersonalizationBrightness( + brightness: Brightness.dark, child: ClipRRect( borderRadius: BorderRadius.circular(PersonalizationRadius.xl2), child: DecoratedBox( diff --git a/ios/Classes/Rees46FlutterSdkPlugin.swift b/ios/Classes/Rees46FlutterSdkPlugin.swift index abdd0af..7dab496 100644 --- a/ios/Classes/Rees46FlutterSdkPlugin.swift +++ b/ios/Classes/Rees46FlutterSdkPlugin.swift @@ -16,7 +16,9 @@ public class Rees46FlutterSdkPlugin: NSObject, FlutterPlugin, FlutterApplication public static func register(with registrar: FlutterPluginRegistrar) { let instance = Rees46FlutterSdkPlugin() instance.messenger = registrar.messenger() - instance.api = PersonalizationHostApiImpl() + instance.api = PersonalizationHostApiImpl( + popupApi: PersonalizationPopupFlutterApi(binaryMessenger: registrar.messenger()) + ) instance.flutterApi = PersonalizationFlutterApi(binaryMessenger: registrar.messenger()) let storiesApi = PersonalizationStoriesFlutterApi(binaryMessenger: registrar.messenger()) instance.storiesApi = storiesApi @@ -117,6 +119,15 @@ extension Rees46FlutterSdkPlugin { } final class PersonalizationHostApiImpl: PersonalizationHostApi { + private let popupApi: PersonalizationPopupFlutterApi + + /// One per shop: the SDK holds its popup delegate weakly. + private var popupForwarders: [String: PopupForwarder] = [:] + + init(popupApi: PersonalizationPopupFlutterApi) { + self.popupApi = popupApi + } + /// Resolves the SDK instance a call targets via the multi-instance `Rees46` /// facade. `shopId == nil` resolves the single default instance; an unknown or /// (with no id) ambiguous shop throws, which `try?` turns into `nil` — the @@ -143,7 +154,7 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { // F3: initialize (and register) the instance through the multi-instance // `Rees46` facade so it is reachable by `shopId` via `Rees46.instance(for:)`. - let sdk = Rees46.initialize( + var sdk = Rees46.initialize( Rees46Config( shopId: config.shopId, apiDomain: config.apiDomain, @@ -162,6 +173,13 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { } } + // Dart draws popups with the UI kit: every popup is kept back from the native SDK + // (nil — not shown, not reported, not remembered) and handed over. Dart decides + // whether to show it, and reports it once it is on screen. + let forwarder = PopupForwarder(shopId: config.shopId, api: popupApi) + popupForwarders[config.shopId] = forwarder + sdk.popupPresentationDelegate = forwarder + // Kept for the AppDelegate push path (device token / remote notification), // which still uses the last-initialized instance until F4 routes by shop. Rees46FlutterSdkPlugin.sdk = sdk @@ -1117,6 +1135,34 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { } } + func trackPopupShown( + popupId: Int64, + shopId: String?, + completion: @escaping (Result) -> Void + ) { + guard let sdk = sdk(shopId) else { + completion( + .failure( + PigeonError(code: "not_initialized", message: "SDK is not initialized", details: nil))) + return + } + sdk.trackPopupShown(popupId: Int(popupId)) { self.report($0, completion) } + } + + func openNotificationSettings() throws { + // The app's notification settings where iOS has a link to them, its Settings page before. + let target: String + if #available(iOS 16.0, *) { + target = UIApplication.openNotificationSettingsURLString + } else { + target = UIApplication.openSettingsURLString + } + guard let url = URL(string: target) else { return } + DispatchQueue.main.async { + UIApplication.shared.open(url, options: [:], completionHandler: nil) + } + } + func trackSetSource(source: TrackingSourceWire, shopId: String?) throws { guard let sdk = sdk(shopId) else { throw PigeonError(code: "not_initialized", message: "SDK is not initialized", details: nil) @@ -1330,3 +1376,40 @@ extension TrackingSourceWire { return TrackingSource(type: type, code: code) } } + +/// Keeps every popup of one shop back from the native SDK and hands it to Dart. +final class PopupForwarder: PopupPresentationDelegate { + private let shopId: String + private let api: PersonalizationPopupFlutterApi + + init(shopId: String, api: PersonalizationPopupFlutterApi) { + self.shopId = shopId + self.api = api + } + + func sdk(_ sdk: PersonalizationSDK, shouldPresentPopup popup: Popup) -> UIViewController? { + if let json = Self.json(popup) { + // The SDK asks from its own queue; the Pigeon channel is called on the main thread. + DispatchQueue.main.async { [api, shopId] in + api.onPopup(shopId: shopId, popupJson: json) { _ in } + } + } + return nil + } + + /// The popup as the server sends it. `Popup` carries `popup_actions` as a JSON string; + /// it goes out as an object, like on Android. + static func json(_ popup: Popup) -> String? { + guard let data = try? JSONEncoder().encode(popup), + var object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + else { return nil } + if let actions = object["popup_actions"] as? String, + let actionsData = actions.data(using: .utf8), + let parsed = try? JSONSerialization.jsonObject(with: actionsData) { + object["popup_actions"] = parsed + } + guard let out = try? JSONSerialization.data(withJSONObject: object) else { return nil } + return String(data: out, encoding: .utf8) + } +} + diff --git a/ios/Classes/pigeon/PersonalizationApi.g.swift b/ios/Classes/pigeon/PersonalizationApi.g.swift index 5744ec3..79ec05b 100644 --- a/ios/Classes/pigeon/PersonalizationApi.g.swift +++ b/ios/Classes/pigeon/PersonalizationApi.g.swift @@ -719,6 +719,14 @@ protocol PersonalizationHostApi { func trackSetSource(source: TrackingSourceWire, shopId: String?) throws /// [customJson] and [recommendedSourceJson] are JSON object strings or null. func trackPurchase(orderId: String, orderPrice: Double, items: [PurchaseLineItemWire], deliveryType: String?, deliveryAddress: String?, paymentType: String?, isTaxFree: Bool, isGiftPackage: Bool, promocode: String?, orderCash: Double?, orderBonuses: Double?, orderDelivery: Double?, orderDiscount: Double?, channel: String?, customJson: String?, recommendedSourceJson: String?, stream: String?, segment: String?, shopId: String?, completion: @escaping (Result) -> Void) + /// Reports popup [popupId] as shown (`popup/showed`) — native `tracking.popupShown` + /// (Android) / `trackPopupShown` (iOS). The native SDKs never show a popup themselves + /// under the plugin, so they never report one either: Dart does, once it is on screen. + func trackPopupShown(popupId: Int64, shopId: 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. + func openNotificationSettings() throws } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. @@ -1546,6 +1554,85 @@ class PersonalizationHostApiSetup { } else { trackPurchaseChannel.setMessageHandler(nil) } + /// Reports popup [popupId] as shown (`popup/showed`) — native `tracking.popupShown` + /// (Android) / `trackPopupShown` (iOS). The native SDKs never show a popup themselves + /// under the plugin, so they never report one either: Dart does, once it is on screen. + let trackPopupShownChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackPopupShown\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + trackPopupShownChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let popupIdArg = args[0] as! Int64 + let shopIdArg: String? = nilOrValue(args[1]) + api.trackPopupShown(popupId: popupIdArg, shopId: shopIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + trackPopupShownChannel.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. + let openNotificationSettingsChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openNotificationSettings\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + openNotificationSettingsChannel.setMessageHandler { _, reply in + do { + try api.openNotificationSettings() + reply(wrapResult(nil)) + } catch { + reply(wrapError(error)) + } + } + } else { + openNotificationSettingsChannel.setMessageHandler(nil) + } + } +} +/// Server popups, handed over instead of being shown natively: the plugin sets the native +/// presentation listener (Android) / delegate (iOS), which keeps every popup back and +/// forwards it here. Separate from [PersonalizationFlutterApi], which the push dispatcher +/// owns. +/// +/// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. +protocol PersonalizationPopupFlutterApiProtocol { + /// A popup arrived for [shopId]. [popupJson] is the popup as the server sends it: + /// `id`, `position`, `delay`, `components` and `popup_actions` (an object). + func onPopup(shopId shopIdArg: String, popupJson popupJsonArg: String, completion: @escaping (Result) -> Void) +} +class PersonalizationPopupFlutterApi: PersonalizationPopupFlutterApiProtocol { + private let binaryMessenger: FlutterBinaryMessenger + private let messageChannelSuffix: String + init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") { + self.binaryMessenger = binaryMessenger + self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" + } + var codec: PersonalizationApiPigeonCodec { + return PersonalizationApiPigeonCodec.shared + } + /// A popup arrived for [shopId]. [popupJson] is the popup as the server sends it: + /// `id`, `position`, `delay`, `components` and `popup_actions` (an object). + func onPopup(shopId shopIdArg: String, popupJson popupJsonArg: String, completion: @escaping (Result) -> Void) { + let channelName: String = "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationPopupFlutterApi.onPopup\(messageChannelSuffix)" + let channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([shopIdArg, popupJsonArg] as [Any?]) { response in + guard let listResponse = response as? [Any?] else { + completion(.failure(createConnectionError(withChannelName: channelName))) + return + } + if listResponse.count > 1 { + let code: String = listResponse[0] as! String + let message: String? = nilOrValue(listResponse[1]) + let details: String? = nilOrValue(listResponse[2]) + completion(.failure(PigeonError(code: code, message: message, details: details))) + } else { + completion(.success(())) + } + } } } /// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. diff --git a/lib/rees46_sdk.dart b/lib/rees46_sdk.dart index 05b281a..1e30d1f 100644 --- a/lib/rees46_sdk.dart +++ b/lib/rees46_sdk.dart @@ -4,6 +4,7 @@ export 'src/multi_instance/rees46.dart'; export 'src/multi_instance/rees46_config.dart'; export 'src/multi_instance/push_event.dart'; export 'src/multi_instance/sdk_exceptions.dart'; +export 'src/popups/in_app_popup.dart'; export 'src/loyalty/loyalty_response.dart'; export 'src/category/category_response.dart'; export 'src/collection/collection_response.dart'; @@ -21,3 +22,14 @@ export 'src/subscriptions/manage_subscription_params.dart'; export 'src/tracking/purchase_line_item.dart'; export 'src/tracking/tracking_api.dart'; export 'src/tracking/tracking_models.dart'; +// The first widget of the UI kit open to apps: the server popup, for apps that draw +// popups themselves (`onPopup`), and the theme the SDK's UI is drawn in — brand +// colours, font, radii and the light/dark mode. The rest of the kit stays internal +// until its release. +export 'src/ui/components/personalization_in_app_popup.dart'; +export 'src/ui/personalization_colors.dart' show PersonalizationColors; +export 'src/ui/personalization_theme.dart' + show + PersonalizationTheme, + PersonalizationFontFamily, + PersonalizationRadiusScale; diff --git a/lib/src/multi_instance/rees46_config.dart b/lib/src/multi_instance/rees46_config.dart index 1abbebc..ea13d1a 100644 --- a/lib/src/multi_instance/rees46_config.dart +++ b/lib/src/multi_instance/rees46_config.dart @@ -29,6 +29,9 @@ class REES46Config { final bool? enableLogs; final bool? autoSendPushToken; final bool? sendAdvertisingId; + + /// Whether the SDK shows server popups itself while no `onPopup` is set on the + /// instance. Off — and without `onPopup` — popups are not shown. Defaults to true. final bool? enableAutoPopupPresentation; final bool? needReInitialization; diff --git a/lib/src/personalization_sdk.dart b/lib/src/personalization_sdk.dart index 401daea..ccfad8a 100644 --- a/lib/src/personalization_sdk.dart +++ b/lib/src/personalization_sdk.dart @@ -7,6 +7,9 @@ import 'init/sdk_init_handler.dart'; import 'loyalty/loyalty_response.dart'; import 'multi_instance/push_dispatcher.dart'; import 'multi_instance/push_event.dart'; +import 'popups/in_app_popup.dart'; +import 'popups/popup_dispatcher.dart'; +import 'popups/popup_presenter.dart'; import 'products/product_counters_response.dart'; import 'profile/profile_params.dart'; import 'profile/profile_response.dart'; @@ -27,6 +30,11 @@ class PersonalizationSdk { final pigeon.PersonalizationHostApi _api; final SdkInitHandler _initHandler; final PushNotificationCallbacks _pushCallbacks = PushNotificationCallbacks(); + late final PopupPresenter _popups = PopupPresenter( + trackShown: (popupId) => _api.trackPopupShown(popupId, shopId), + openUrl: _api.openUrl, + openNotificationSettings: _api.openNotificationSettings, + ); /// The shop this handle is bound to, or `null` for the legacy default /// instance. Set by [REES46.initialize] / [REES46.getInstance]. Reserved for @@ -41,7 +49,11 @@ class PersonalizationSdk { PersonalizationSdk({pigeon.PersonalizationHostApi? api, this.shopId}) : _api = api ?? pigeon.PersonalizationHostApi(), _initHandler = SdkInitHandler(api: api) { - tracking = TrackingApi(_api, shopId); + tracking = TrackingApi( + _api, + shopId, + onPopupShown: (popupId) => _popups.markShown(popupId), + ); // One process-global dispatcher owns the Pigeon push channel and routes each // inbound push (by shopId) to the right handle — register this handle's // callbacks with it instead of claiming the channel per instance. @@ -92,9 +104,32 @@ class PersonalizationSdk { } Future initialize(SdkInitConfig config) { + _popups.autoPresentation = config.enableAutoPopupPresentation ?? true; + // The native side reports popups under the shop id it was initialized with. + PopupDispatcher.instance.register(config.shopId, _popups); return _initHandler.initialize(config); } + /// Takes the server popups (in-app messages) instead of the SDK showing them. + /// + /// Popups arrive with the responses to init and tracking calls. Without a handler the + /// SDK shows each over the app's root navigator, unless + /// `enableAutoPopupPresentation` is off. With one, the SDK shows nothing: the handler + /// gets every popup once its delay has passed and decides — draw it (for instance with + /// `PersonalizationInAppPopup`) and report it with `tracking.popupShown(popup.id)`, + /// let the SDK show it with [presentPopup], or drop it. A popup shown within the last + /// minute is not handed over again. Called on the main isolate. + void Function(InAppPopup popup)? get onPopup => _popups.onPopup; + + set onPopup(void Function(InAppPopup popup)? handler) => + _popups.onPopup = handler; + + /// Shows [popup] the way the SDK shows server popups — over the app's root navigator, + /// after any popup already on screen — and reports it as shown. For a popup taken with + /// [onPopup] and held back. Completes when the popup closes, or at once when it cannot + /// be shown. + Future presentPopup(InAppPopup popup) => _popups.present(popup); + Future setProfile(ProfileParams params) { return _api.setProfile(params.toWire(), shopId); } diff --git a/lib/src/pigeon/personalization_api.g.dart b/lib/src/pigeon/personalization_api.g.dart index df816ce..1be9487 100644 --- a/lib/src/pigeon/personalization_api.g.dart +++ b/lib/src/pigeon/personalization_api.g.dart @@ -15,7 +15,11 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { +List wrapResponse({ + Object? result, + PlatformException? error, + bool empty = false, +}) { if (empty) { return []; } @@ -24,21 +28,25 @@ List wrapResponse({Object? result, PlatformException? error, bool empty } return [error.code, error.message, error.details]; } + bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every( + ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), + ); } if (a is Map && b is Map) { - return a.length == b.length && a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + return a.length == b.length && + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); } return a == b; } - class InitConfig { InitConfig({ required this.shopId, @@ -81,7 +89,8 @@ class InitConfig { } Object encode() { - return _toList(); } + return _toList(); + } static InitConfig decode(Object result) { result as List; @@ -111,8 +120,7 @@ class InitConfig { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()) -; + int get hashCode => Object.hashAll(_toList()); } /// Wire format for one purchase line (maps to native `PurchaseItemRequest`). @@ -139,17 +147,12 @@ class PurchaseLineItemWire { String? fashionSize; List _toList() { - return [ - id, - amount, - price, - lineId, - fashionSize, - ]; + return [id, amount, price, lineId, fashionSize]; } Object encode() { - return _toList(); } + return _toList(); + } static PurchaseLineItemWire decode(Object result) { result as List; @@ -176,8 +179,7 @@ class PurchaseLineItemWire { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()) -; + int get hashCode => Object.hashAll(_toList()); } /// Wire format for profile fields sent to native SDK. @@ -275,7 +277,8 @@ class ProfileParamsWire { } Object encode() { - return _toList(); } + return _toList(); + } static ProfileParamsWire decode(Object result) { result as List; @@ -317,8 +320,7 @@ class ProfileParamsWire { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()) -; + int get hashCode => Object.hashAll(_toList()); } /// Wire format for `subscriptions/manage`: contacts that identify the client and one flag per @@ -441,7 +443,8 @@ class ManageSubscriptionParamsWire { } Object encode() { - return _toList(); } + return _toList(); + } static ManageSubscriptionParamsWire decode(Object result) { result as List; @@ -479,7 +482,8 @@ class ManageSubscriptionParamsWire { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! ManageSubscriptionParamsWire || other.runtimeType != runtimeType) { + if (other is! ManageSubscriptionParamsWire || + other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -490,8 +494,7 @@ class ManageSubscriptionParamsWire { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()) -; + int get hashCode => Object.hashAll(_toList()); } /// Wire format for one product line in a tracking event (maps to native `TrackingItem`). @@ -514,16 +517,12 @@ class TrackingItemWire { String? fashionSize; List _toList() { - return [ - id, - quantity, - price, - fashionSize, - ]; + return [id, quantity, price, fashionSize]; } Object encode() { - return _toList(); } + return _toList(); + } static TrackingItemWire decode(Object result) { result as List; @@ -549,8 +548,7 @@ class TrackingItemWire { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()) -; + int get hashCode => Object.hashAll(_toList()); } /// Wire format for event attribution (maps to native `TrackingSource`). @@ -559,24 +557,19 @@ class TrackingItemWire { /// `transactional`, `instant_search`, `full_search`, `stories`. Dart only ever sends what its /// `TrackingSourceType` enum produces; the bridges reject anything else. class TrackingSourceWire { - TrackingSourceWire({ - required this.type, - required this.code, - }); + TrackingSourceWire({required this.type, required this.code}); String type; String code; List _toList() { - return [ - type, - code, - ]; + return [type, code]; } Object encode() { - return _toList(); } + return _toList(); + } static TrackingSourceWire decode(Object result) { result as List; @@ -600,11 +593,9 @@ class TrackingSourceWire { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()) -; + int get hashCode => Object.hashAll(_toList()); } - class _PigeonCodec extends StandardMessageCodec { const _PigeonCodec(); @override @@ -612,22 +603,22 @@ class _PigeonCodec extends StandardMessageCodec { if (value is int) { buffer.putUint8(4); buffer.putInt64(value); - } else if (value is InitConfig) { + } else if (value is InitConfig) { buffer.putUint8(129); writeValue(buffer, value.encode()); - } else if (value is PurchaseLineItemWire) { + } else if (value is PurchaseLineItemWire) { buffer.putUint8(130); writeValue(buffer, value.encode()); - } else if (value is ProfileParamsWire) { + } else if (value is ProfileParamsWire) { buffer.putUint8(131); writeValue(buffer, value.encode()); - } else if (value is ManageSubscriptionParamsWire) { + } else if (value is ManageSubscriptionParamsWire) { buffer.putUint8(132); writeValue(buffer, value.encode()); - } else if (value is TrackingItemWire) { + } else if (value is TrackingItemWire) { buffer.putUint8(133); writeValue(buffer, value.encode()); - } else if (value is TrackingSourceWire) { + } else if (value is TrackingSourceWire) { buffer.putUint8(134); writeValue(buffer, value.encode()); } else { @@ -638,17 +629,17 @@ class _PigeonCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 129: + case 129: return InitConfig.decode(readValue(buffer)!); - case 130: + case 130: return PurchaseLineItemWire.decode(readValue(buffer)!); - case 131: + case 131: return ProfileParamsWire.decode(readValue(buffer)!); - case 132: + case 132: return ManageSubscriptionParamsWire.decode(readValue(buffer)!); - case 133: + case 133: return TrackingItemWire.decode(readValue(buffer)!); - case 134: + case 134: return TrackingSourceWire.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -660,9 +651,13 @@ class PersonalizationHostApi { /// Constructor for [PersonalizationHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - PersonalizationHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) - : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + PersonalizationHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -670,13 +665,17 @@ class PersonalizationHostApi { final String pigeonVar_messageChannelSuffix; Future initialize(InitConfig config) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.initialize$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.initialize$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [config], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([config]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -693,12 +692,14 @@ class PersonalizationHostApi { } Future getPlatformVersion() async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getPlatformVersion$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getPlatformVersion$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -722,13 +723,17 @@ class PersonalizationHostApi { /// Returns the push token stored by the native SDK (if any). Future getStoredPushToken(String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStoredPushToken$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStoredPushToken$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -745,14 +750,26 @@ class PersonalizationHostApi { } /// [customFieldsJson] is JSON object string or null (maps to native custom fields map). - Future trackEvent(String event, int? time, String? category, String? label, int? value, String? customFieldsJson, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackEvent$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future trackEvent( + String event, + int? time, + String? category, + String? label, + int? value, + String? customFieldsJson, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackEvent$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [event, time, category, label, value, customFieldsJson, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([event, time, category, label, value, customFieldsJson, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -769,13 +786,17 @@ class PersonalizationHostApi { } Future setProfile(ProfileParamsWire params, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.setProfile$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.setProfile$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [params, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([params, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -791,14 +812,21 @@ class PersonalizationHostApi { } } - Future manageSubscription(ManageSubscriptionParamsWire params, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.manageSubscription$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future manageSubscription( + ManageSubscriptionParamsWire params, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.manageSubscription$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [params, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([params, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -817,14 +845,22 @@ class PersonalizationHostApi { /// Returns the recommendation block as a JSON string. /// [paramsJson] is a JSON object string with optional filter parameters. /// Dart layer parses the result into [RecommendationResponse]. - Future getRecommendation(String code, String? paramsJson, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getRecommendation$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future getRecommendation( + String code, + String? paramsJson, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getRecommendation$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [code, paramsJson, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([code, paramsJson, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -847,13 +883,17 @@ class PersonalizationHostApi { /// Returns the current session ID from the native SDK. Future getSid(String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getSid$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getSid$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -876,13 +916,17 @@ class PersonalizationHostApi { /// Returns the device ID assigned by the native SDK, or null before first sync. Future getDid(String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getDid$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getDid$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -901,13 +945,17 @@ class PersonalizationHostApi { /// Returns a single product's details as a JSON string. /// Dart layer parses the result into [Product]. Future getProductInfo(String itemId, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getProductInfo$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getProductInfo$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [itemId, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemId, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -932,13 +980,17 @@ class PersonalizationHostApi { /// [paramsJson] is a JSON object with optional filter fields. /// Dart layer parses the result into [ProductsListResponse]. Future getProductsList(String? paramsJson, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getProductsList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getProductsList$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [paramsJson, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([paramsJson, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -963,13 +1015,17 @@ class PersonalizationHostApi { /// No parameters — the native SDK decides what to return based on shop config. /// Dart layer parses the result into [SearchBlankResponse]. Future searchBlank(String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.searchBlank$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.searchBlank$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -993,14 +1049,22 @@ class PersonalizationHostApi { /// Returns instant (typeahead) search results as a JSON string. /// [paramsJson] may contain optional "locations" (String) and "excluded_brands" ([String]). /// Dart layer parses the result into [SearchInstantResponse]. - Future searchInstant(String query, String? paramsJson, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.searchInstant$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future searchInstant( + String query, + String? paramsJson, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.searchInstant$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [query, paramsJson, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([query, paramsJson, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1024,14 +1088,22 @@ class PersonalizationHostApi { /// Returns full search results as a JSON string. /// [paramsJson] is a JSON object string with optional search parameters. /// Dart layer parses the result into [SearchFullResponse]. - Future searchFull(String query, String? paramsJson, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.searchFull$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future searchFull( + String query, + String? paramsJson, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.searchFull$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [query, paramsJson, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([query, paramsJson, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1056,14 +1128,24 @@ class PersonalizationHostApi { /// response envelope as a JSON string `{ "status": ..., "payload": { ... } }`. /// The shop is identified by the SDK's configured `shop_id`; [phone] is required. /// Dart layer parses the result into [LoyaltyJoinResponse]. - Future joinLoyalty(String phone, String? email, String? firstName, String? lastName, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.joinLoyalty$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future joinLoyalty( + String phone, + String? email, + String? firstName, + String? lastName, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.joinLoyalty$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [phone, email, firstName, lastName, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([phone, email, firstName, lastName, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1089,13 +1171,17 @@ class PersonalizationHostApi { /// [identifier] is the member identifier (phone). /// Dart layer parses the result into [LoyaltyStatusResponse]. Future getLoyaltyStatus(String identifier, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getLoyaltyStatus$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getLoyaltyStatus$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [identifier, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([identifier, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1119,13 +1205,17 @@ class PersonalizationHostApi { /// Returns the current user's profile as a JSON string. /// Dart layer parses the result into [ProfileResponse]. Future getProfile(String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getProfile$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getProfile$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1149,13 +1239,17 @@ class PersonalizationHostApi { /// Returns view / cart / purchase counters for [item] as a JSON string. /// Dart layer parses the result into [ProductCountersResponse]. Future getProductCounters(String item, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getProductCounters$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getProductCounters$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [item, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([item, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1179,14 +1273,23 @@ class PersonalizationHostApi { /// Returns a category product listing as a JSON string. /// [limit] and [page] paginate the result; both are optional. /// Dart layer parses the result into [CategoryResponse]. - Future getCategory(String category, int? limit, int? page, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCategory$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future getCategory( + String category, + int? limit, + int? page, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCategory$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [category, limit, page, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([category, limit, page, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1210,13 +1313,17 @@ class PersonalizationHostApi { /// Returns a merchandised collection's products as a JSON string. /// Dart layer parses the result into [CollectionResponse]. Future getCollection(String collectionId, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCollection$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCollection$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [collectionId, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([collectionId, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1242,13 +1349,17 @@ class PersonalizationHostApi { /// over the same raw payload, so Dart parses one shape. /// Dart layer parses the result into [StoriesBlock]. Future getStories(String code, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStories$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStories$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [code, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([code, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1272,13 +1383,17 @@ class PersonalizationHostApi { /// Opens [url] with the system handler (browser or the app that claims the link). /// Returns false when nothing could open it. Future openUrl(String url) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openUrl$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openUrl$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [url], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1305,13 +1420,17 @@ class PersonalizationHostApi { /// hands nested lists over as `List`, and a typed `List` here /// generates a lazy cast that throws on the first read. Future>> getStoriesSeen(String shop) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStoriesSeen$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStoriesSeen$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [shop], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([shop]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1328,19 +1447,28 @@ class PersonalizationHostApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as Map?)!.cast>(); + return (pigeonVar_replyList[0] as Map?)! + .cast>(); } } /// Records [slideId] of story [storyId] as seen for [shop]. - Future setStorySlideSeen(String shop, String storyId, String slideId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.setStorySlideSeen$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future setStorySlideSeen( + String shop, + String storyId, + String slideId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.setStorySlideSeen$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [shop, storyId, slideId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([shop, storyId, slideId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1359,12 +1487,14 @@ class PersonalizationHostApi { /// The app's cache directory: Android `Context.cacheDir`, iOS `Library/Caches`. The /// stories viewer keeps its video cache under it. Future getCacheDirectory() async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCacheDirectory$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCacheDirectory$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1390,12 +1520,14 @@ class PersonalizationHostApi { /// so [endStoriesAudio] can put it back. iOS only; a no-op on Android, where a muted /// video never takes the audio focus (`mixWithOthers`). Future beginStoriesAudio() async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.beginStoriesAudio$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.beginStoriesAudio$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1417,13 +1549,17 @@ class PersonalizationHostApi { /// hardware volume (see [PersonalizationStoriesFlutterApi.onStoriesVolumeUp]). iOS /// only; a no-op on Android. Future updateStoriesAudio(bool muted) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.updateStoriesAudio$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.updateStoriesAudio$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [muted], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([muted]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1442,12 +1578,14 @@ class PersonalizationHostApi { /// The viewer closed: restores the session saved by [beginStoriesAudio] and stops /// watching the volume. iOS only; a no-op on Android. Future endStoriesAudio() async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.endStoriesAudio$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.endStoriesAudio$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1469,13 +1607,17 @@ class PersonalizationHostApi { /// `PushEvent` enum: 0 = received, 1 = delivered, 2 = clicked. The native side /// maps it to its own vocabulary (Android `PushEventType`, iOS `PushEvent`). Future handlePush(Map payload, int event) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.handlePush$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.handlePush$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [payload, event], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([payload, event]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1491,14 +1633,22 @@ class PersonalizationHostApi { } } - Future trackProductView(String itemId, TrackingSourceWire? source, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackProductView$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future trackProductView( + String itemId, + TrackingSourceWire? source, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackProductView$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [itemId, source, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemId, source, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1515,13 +1665,17 @@ class PersonalizationHostApi { } Future trackCategoryView(String categoryId, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackCategoryView$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackCategoryView$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [categoryId, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([categoryId, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1537,14 +1691,22 @@ class PersonalizationHostApi { } } - Future trackSearch(String query, List? results, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSearch$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future trackSearch( + String query, + List? results, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSearch$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [query, results, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([query, results, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1560,14 +1722,22 @@ class PersonalizationHostApi { } } - Future trackAddToCart(TrackingItemWire item, TrackingSourceWire? source, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToCart$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future trackAddToCart( + TrackingItemWire item, + TrackingSourceWire? source, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToCart$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [item, source, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([item, source, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1583,14 +1753,21 @@ class PersonalizationHostApi { } } - Future trackSyncCart(List items, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncCart$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future trackSyncCart( + List items, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncCart$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [items, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([items, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1607,13 +1784,17 @@ class PersonalizationHostApi { } Future trackRemoveFromCart(String itemId, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromCart$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromCart$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [itemId, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemId, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1629,14 +1810,22 @@ class PersonalizationHostApi { } } - Future trackAddToFavorites(String itemId, TrackingSourceWire? source, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToFavorites$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future trackAddToFavorites( + String itemId, + TrackingSourceWire? source, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackAddToFavorites$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [itemId, source, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemId, source, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1653,13 +1842,17 @@ class PersonalizationHostApi { } Future trackSyncFavorites(List itemIds, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncFavorites$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSyncFavorites$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [itemIds, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemIds, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1676,13 +1869,17 @@ class PersonalizationHostApi { } Future trackRemoveFromFavorites(String itemId, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromFavorites$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackRemoveFromFavorites$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [itemId, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemId, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1698,14 +1895,23 @@ class PersonalizationHostApi { } } - Future trackStoryView(String storyId, String slideId, String? code, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryView$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future trackStoryView( + String storyId, + String slideId, + String? code, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryView$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [storyId, slideId, code, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([storyId, slideId, code, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1721,14 +1927,23 @@ class PersonalizationHostApi { } } - Future trackStoryClick(String storyId, String slideId, String? code, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryClick$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future trackStoryClick( + String storyId, + String slideId, + String? code, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackStoryClick$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [storyId, slideId, code, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([storyId, slideId, code, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1746,13 +1961,17 @@ class PersonalizationHostApi { /// Stores the attribution source natively for the next event. Future trackSetSource(TrackingSourceWire source, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSetSource$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackSetSource$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [source, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([source, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1769,14 +1988,87 @@ class PersonalizationHostApi { } /// [customJson] and [recommendedSourceJson] are JSON object strings or null. - Future trackPurchase(String orderId, double orderPrice, List items, String? deliveryType, String? deliveryAddress, String? paymentType, bool isTaxFree, bool isGiftPackage, String? promocode, double? orderCash, double? orderBonuses, double? orderDelivery, double? orderDiscount, String? channel, String? customJson, String? recommendedSourceJson, String? stream, String? segment, String? shopId) async { - final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackPurchase$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, + Future trackPurchase( + String orderId, + double orderPrice, + List items, + String? deliveryType, + String? deliveryAddress, + String? paymentType, + bool isTaxFree, + bool isGiftPackage, + String? promocode, + double? orderCash, + double? orderBonuses, + double? orderDelivery, + double? orderDiscount, + String? channel, + String? customJson, + String? recommendedSourceJson, + String? stream, + String? segment, + String? shopId, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackPurchase$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([ + orderId, + orderPrice, + items, + deliveryType, + deliveryAddress, + paymentType, + isTaxFree, + isGiftPackage, + promocode, + orderCash, + orderBonuses, + orderDelivery, + orderDiscount, + channel, + customJson, + recommendedSourceJson, + stream, + segment, + shopId, + ]); + 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; + } + } + + /// Reports popup [popupId] as shown (`popup/showed`) — native `tracking.popupShown` + /// (Android) / `trackPopupShown` (iOS). The native SDKs never show a popup themselves + /// under the plugin, so they never report one either: Dart does, once it is on screen. + Future trackPopupShown(int popupId, String? shopId) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackPopupShown$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [popupId, shopId], ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send([orderId, orderPrice, items, deliveryType, deliveryAddress, paymentType, isTaxFree, isGiftPackage, promocode, orderCash, orderBonuses, orderDelivery, orderDiscount, channel, customJson, recommendedSourceJson, stream, segment, shopId]); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1791,6 +2083,95 @@ class PersonalizationHostApi { return; } } + + /// 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. + Future openNotificationSettings() async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openNotificationSettings$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + 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; + } + } +} + +/// Server popups, handed over instead of being shown natively: the plugin sets the native +/// presentation listener (Android) / delegate (iOS), which keeps every popup back and +/// forwards it here. Separate from [PersonalizationFlutterApi], which the push dispatcher +/// owns. +abstract class PersonalizationPopupFlutterApi { + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + /// A popup arrived for [shopId]. [popupJson] is the popup as the server sends it: + /// `id`, `position`, `delay`, `components` and `popup_actions` (an object). + void onPopup(String shopId, String popupJson); + + static void setUp( + PersonalizationPopupFlutterApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; + { + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationPopupFlutterApi.onPopup$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); + if (api == null) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationPopupFlutterApi.onPopup was null.', + ); + final List args = (message as List?)!; + final String? arg_shopId = (args[0] as String?); + assert( + arg_shopId != null, + 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationPopupFlutterApi.onPopup was null, expected non-null String.', + ); + final String? arg_popupJson = (args[1] as String?); + assert( + arg_popupJson != null, + 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationPopupFlutterApi.onPopup was null, expected non-null String.', + ); + try { + api.onPopup(arg_shopId!, arg_popupJson!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString()), + ); + } + }); + } + } + } } abstract class PersonalizationFlutterApi { @@ -1802,82 +2183,118 @@ abstract class PersonalizationFlutterApi { void onPushClicked(String? shopId, Map payload); - static void setUp(PersonalizationFlutterApi? api, {BinaryMessenger? binaryMessenger, String messageChannelSuffix = '',}) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + static void setUp( + PersonalizationFlutterApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; { - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushReceived$messageChannelSuffix', pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushReceived$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushReceived was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushReceived was null.', + ); final List args = (message as List?)!; final String? arg_shopId = (args[0] as String?); - final Map? arg_payload = (args[1] as Map?)?.cast(); - assert(arg_payload != null, - 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushReceived was null, expected non-null Map.'); + final Map? arg_payload = + (args[1] as Map?)?.cast(); + assert( + arg_payload != null, + 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushReceived was null, expected non-null Map.', + ); try { api.onPushReceived(arg_shopId, arg_payload!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); - } catch (e) { - return wrapResponse(error: PlatformException(code: 'error', message: e.toString())); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushDelivered$messageChannelSuffix', pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushDelivered$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushDelivered was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushDelivered was null.', + ); final List args = (message as List?)!; final String? arg_shopId = (args[0] as String?); - final Map? arg_payload = (args[1] as Map?)?.cast(); - assert(arg_payload != null, - 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushDelivered was null, expected non-null Map.'); + final Map? arg_payload = + (args[1] as Map?)?.cast(); + assert( + arg_payload != null, + 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushDelivered was null, expected non-null Map.', + ); try { api.onPushDelivered(arg_shopId, arg_payload!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); - } catch (e) { - return wrapResponse(error: PlatformException(code: 'error', message: e.toString())); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushClicked$messageChannelSuffix', pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushClicked$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushClicked was null.'); + assert( + message != null, + 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushClicked was null.', + ); final List args = (message as List?)!; final String? arg_shopId = (args[0] as String?); - final Map? arg_payload = (args[1] as Map?)?.cast(); - assert(arg_payload != null, - 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushClicked was null, expected non-null Map.'); + final Map? arg_payload = + (args[1] as Map?)?.cast(); + assert( + arg_payload != null, + 'Argument for dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationFlutterApi.onPushClicked was null, expected non-null Map.', + ); try { api.onPushClicked(arg_shopId, arg_payload!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); - } catch (e) { - return wrapResponse(error: PlatformException(code: 'error', message: e.toString())); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1894,12 +2311,21 @@ abstract class PersonalizationStoriesFlutterApi { /// `outputVolume` grew). Android delivers the volume key to Flutter itself. void onStoriesVolumeUp(); - static void setUp(PersonalizationStoriesFlutterApi? api, {BinaryMessenger? binaryMessenger, String messageChannelSuffix = '',}) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + static void setUp( + PersonalizationStoriesFlutterApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; { - final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationStoriesFlutterApi.onStoriesVolumeUp$messageChannelSuffix', pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationStoriesFlutterApi.onStoriesVolumeUp$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { pigeonVar_channel.setMessageHandler(null); } else { @@ -1909,8 +2335,10 @@ abstract class PersonalizationStoriesFlutterApi { return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); - } catch (e) { - return wrapResponse(error: PlatformException(code: 'error', message: e.toString())); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/lib/src/popups/in_app_popup.dart b/lib/src/popups/in_app_popup.dart new file mode 100644 index 0000000..d51831f --- /dev/null +++ b/lib/src/popups/in_app_popup.dart @@ -0,0 +1,122 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; + +/// Where the shop placed a popup in the admin. +enum InAppPopupPosition { + center, + top, + bottom, + + /// No position, or one this SDK does not know. Shown fullscreen, as the native SDKs do. + unknown, +} + +/// A server popup (in-app message). Popups arrive with the responses to init and tracking +/// calls; see `PersonalizationSdk.onPopup` for how they reach the screen. +@immutable +class InAppPopup { + const InAppPopup({ + required this.id, + this.position = InAppPopupPosition.unknown, + this.delay = Duration.zero, + this.title, + this.text, + this.imageUrl, + this.linkText, + this.linkUrl, + this.pushSubscribeText, + this.closeText, + this.json = const {}, + }); + + /// Parses the popup as the server sends it. [platform] picks the link for this platform + /// (`link_android` / `link_ios`), falling back to the web one. + factory InAppPopup.fromJson( + Map json, { + TargetPlatform? platform, + }) { + final components = _map(json['components']); + final actions = _map(json['popup_actions']); + final link = _map(actions['link']); + final ios = (platform ?? defaultTargetPlatform) == TargetPlatform.iOS; + final own = _text(link[ios ? 'link_ios' : 'link_android']); + final other = _text(link[ios ? 'link_android' : 'link_ios']); + + return InAppPopup( + id: _int(json['id']) ?? 0, + position: switch (json['position']) { + 'centered' => InAppPopupPosition.center, + 'top' => InAppPopupPosition.top, + 'fixed_bottom' => InAppPopupPosition.bottom, + _ => InAppPopupPosition.unknown, + }, + delay: Duration(seconds: _int(json['delay']) ?? 0), + title: _text(components['header']), + text: _text(components['text']), + imageUrl: _text(components['image']), + linkText: _text(link['button_text']), + linkUrl: own ?? _text(link['link_web']) ?? other, + pushSubscribeText: _text( + _map(actions['system_mobile_push_subscribe'])['button_text'], + ), + closeText: _text(_map(actions['close'])['button_text']), + json: json, + ); + } + + final int id; + final InAppPopupPosition position; + + /// How long after it arrives the shop wants the popup shown. + final Duration delay; + + final String? title; + final String? text; + final String? imageUrl; + + /// The link button: [linkText] opens [linkUrl]. + final String? linkText; + final String? linkUrl; + + /// The push-subscription button. When the shop turned it on it takes the place of the + /// link button, as in the native SDKs: tapping it opens the notification settings. + final String? pushSubscribeText; + + /// The secondary button that closes the popup. Empty — only the cross closes it. + final String? closeText; + + /// The popup as the server sent it, for fields this class does not cover. + final Map json; + + /// The main button's caption: the push subscription, else the link. + String? get actionText => pushSubscribeText ?? linkText; + + /// Whether there is anything to show: a title, a text or a picture. + bool get hasContent => title != null || text != null || imageUrl != null; + + // The server sends `components` and `popup_actions` as JSON inside a string; the + // plugin hands them over as objects, but either reads. + static Map _map(Object? value) { + if (value is String && value.isNotEmpty) { + try { + value = jsonDecode(value); + } on FormatException { + return const {}; + } + } + return value is Map + ? value.cast() + : const {}; + } + + static String? _text(Object? value) => + value is String && value.trim().isNotEmpty ? value : null; + + static int? _int(Object? value) => switch (value) { + final int v => v, + final num v => v.toInt(), + final String v => int.tryParse(v), + _ => null, + }; +} diff --git a/lib/src/popups/popup_dispatcher.dart b/lib/src/popups/popup_dispatcher.dart new file mode 100644 index 0000000..de171a5 --- /dev/null +++ b/lib/src/popups/popup_dispatcher.dart @@ -0,0 +1,47 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; + +import '../pigeon/personalization_api.g.dart' as pigeon; +import 'in_app_popup.dart'; +import 'popup_presenter.dart'; + +/// Process-global sink for the popups the native SDKs hand over. +/// +/// There is one Pigeon `PersonalizationPopupFlutterApi` channel per plugin, so one +/// dispatcher owns it and routes each popup by the shop it came for to that handle's +/// [PopupPresenter]. A handle registers when it initializes, under the shop id it +/// initialized the native SDK with — the id the native side reports back. +class PopupDispatcher implements pigeon.PersonalizationPopupFlutterApi { + PopupDispatcher._() { + pigeon.PersonalizationPopupFlutterApi.setUp(this); + } + + static final PopupDispatcher instance = PopupDispatcher._(); + + final Map _byShop = {}; + + /// Registers [presenter] as the sink for [shopId]'s popups. + void register(String shopId, PopupPresenter presenter) { + _byShop[shopId] = presenter; + } + + @override + void onPopup(String shopId, String popupJson) { + final presenter = _byShop[shopId]; + if (presenter == null) return; // a shop no handle initialized + final Object? decoded; + try { + decoded = jsonDecode(popupJson); + } on FormatException catch (error) { + debugPrint('PersonalizationPopup: unreadable popup — $error'); + return; + } + if (decoded is! Map) return; + presenter.receive(InAppPopup.fromJson(decoded.cast())); + } + + /// Test-only: drops all registrations. + @visibleForTesting + void reset() => _byShop.clear(); +} diff --git a/lib/src/popups/popup_presenter.dart b/lib/src/popups/popup_presenter.dart new file mode 100644 index 0000000..24936d9 --- /dev/null +++ b/lib/src/popups/popup_presenter.dart @@ -0,0 +1,456 @@ +import 'dart:async'; +import 'dart:collection'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; + +import '../ui/components/personalization_in_app_popup.dart'; +import '../ui/personalization_theme.dart'; +import 'in_app_popup.dart'; + +/// Hands server popups of one SDK handle to the host, or shows them over the app's root +/// navigator. +/// +/// Follows the native SDKs: a popup shown within the last minute is dropped when the +/// server sends it again, one popup is on screen at a time, and a popup that never reached +/// the screen is neither reported nor remembered. Unlike them it waits out the delay the +/// shop set, as the React Native SDK does. +class PopupPresenter { + PopupPresenter({ + required Future Function(int popupId) trackShown, + required Future Function(String url) openUrl, + required Future Function() openNotificationSettings, + DateTime Function()? now, + ImageProvider Function(String url)? image, + }) : _trackShown = trackShown, + _openUrl = openUrl, + _openNotificationSettings = openNotificationSettings, + _now = now ?? DateTime.now, + _imageFor = image ?? NetworkImage.new; + + final Future Function(int popupId) _trackShown; + final Future Function(String url) _openUrl; + final Future Function() _openNotificationSettings; + final DateTime Function() _now; + final ImageProvider Function(String url) _imageFor; + + /// Whether popups are shown while no [onPopup] is set. + bool autoPresentation = true; + + /// Takes every popup instead of the SDK showing it. + void Function(InAppPopup popup)? onPopup; + + /// A popup shown within this window is not shown again. + static const Duration repeatWindow = Duration(minutes: 1); + + /// How long a popup waits for the app's navigator, which is not there yet when the + /// init response comes before the app's first frame. + static const Duration navigatorWait = Duration(seconds: 10); + + static const Duration _navigatorPoll = Duration(milliseconds: 100); + + final Map _shownAt = {}; + final Set _delayed = {}; + final Queue<_Request> _queue = Queue<_Request>(); + _Request? _current; + + /// A popup from the server: waits out its delay, then goes to [onPopup] or on screen. + void receive(InAppPopup popup) { + // An init response without a popup still gives one on iOS: the SDK builds it from an + // empty object, so it carries the model's defaults (id 0, no position, no + // components). Its own views skip it for want of a title; here a popup with nothing + // to show is dropped as well. + if (!popup.hasContent) return; + if (_isRepeat(popup.id) || !_delayed.add(popup.id)) return; + Timer(popup.delay, () { + _delayed.remove(popup.id); + if (_isRepeat(popup.id)) return; + final handler = onPopup; + if (handler != null) { + try { + handler(popup); + } catch (error, stack) { + _log('popup ${popup.id}: onPopup failed — $error\n$stack'); + } + return; + } + if (!autoPresentation) { + _log('popup ${popup.id} not shown: automatic presentation is off'); + return; + } + unawaited(present(popup)); + }); + } + + /// Shows [popup] after the one on screen, if any. Completes when the popup closes, or + /// at once when it cannot be shown. + Future present(InAppPopup popup) { + final same = <_Request>[ + ?_current, + ..._queue, + ].where((request) => request.popup.id == popup.id); + if (same.isNotEmpty) return same.first.done.future; + + final request = _Request(popup); + _queue.add(request); + _next(); + return request.done.future; + } + + /// Remembers [popupId] as shown, so a repeat within [repeatWindow] is dropped. + void markShown(int popupId) => _shownAt[popupId] = _now(); + + bool _isRepeat(int popupId) { + final shown = _shownAt[popupId]; + if (shown == null) return false; + if (_now().difference(shown) < repeatWindow) return true; + _shownAt.remove(popupId); + return false; + } + + void _next() { + if (_current != null || _queue.isEmpty) return; + final request = _current = _queue.removeFirst(); + _show(request) + .catchError((Object error, StackTrace stack) { + _log('popup ${request.popup.id} not shown: $error\n$stack'); + }) + .whenComplete(() { + if (!request.done.isCompleted) request.done.complete(); + _current = null; + _next(); + }); + } + + Future _show(_Request request) async { + final popup = request.popup; + final navigator = await _navigator(); + if (navigator == null) { + _log('popup ${popup.id} not shown: the app has no navigator'); + return; + } + // No repeat check here: server repeats are dropped on arrival, and a popup the app + // asks for is shown even if it was shown a moment ago. + final navigatorContext = navigator.context; + if (!navigatorContext.mounted) return; + + final picture = await _loadImage(popup.imageUrl, navigatorContext); + if (!navigatorContext.mounted) return; + + final route = _route(popup, picture, navigatorContext); + unawaited(navigator.push(route)); + markShown(popup.id); + _run('popup ${popup.id}: shown, not reported', () => _trackShown(popup.id)); + // Not the future push returns: it never completes when the navigator goes away with + // the popup on screen, and the queue would stand still for the rest of the session. + await route.gone; + } + + Future _navigator() async { + for ( + var waited = Duration.zero; + waited < navigatorWait; + waited += _navigatorPoll + ) { + final navigator = rootNavigator(); + if (navigator != null) return navigator; + await Future.delayed(_navigatorPoll); + } + return rootNavigator(); + } + + /// The app's root navigator: the first one down the widget tree. `MaterialApp`, + /// `CupertinoApp` and `WidgetsApp` build it, and so does the router of + /// `MaterialApp.router`; nested navigators (tabs) sit inside it, so the walk reaches the + /// root one first. The one `showDialog` uses by default. + @visibleForTesting + static NavigatorState? rootNavigator() { + NavigatorState? found; + void visit(Element element) { + if (found != null) return; + if (element is StatefulElement && element.state is NavigatorState) { + found = element.state as NavigatorState; + return; + } + element.visitChildElements(visit); + } + + WidgetsBinding.instance.rootElement?.visitChildElements(visit); + return found; + } + + /// The popup's picture and its width to height, loaded before the popup shows so it + /// does not pop in later. One that fails to load leaves the popup without a picture, + /// as on iOS. + Future<_Picture?> _loadImage(String? url, BuildContext context) async { + if (url == null) return null; + final image = _imageFor(url); + final loaded = Completer(); + final stream = image.resolve(createLocalImageConfiguration(context)); + late final ImageStreamListener listener; + listener = ImageStreamListener( + (info, _) { + if (!loaded.isCompleted) { + loaded.complete( + Size(info.image.width.toDouble(), info.image.height.toDouble()), + ); + } + // As precacheImage does: hold the image until the popup that shows it is built. + SchedulerBinding.instance.addPostFrameCallback((_) { + info.dispose(); + stream.removeListener(listener); + }); + }, + onError: (error, _) { + _log('popup image $url — $error'); + if (!loaded.isCompleted) loaded.complete(null); + }, + ); + stream.addListener(listener); + final size = await loaded.future.timeout( + const Duration(seconds: 10), + onTimeout: () { + _log('popup image $url — timed out'); + return null; + }, + ); + if (size == null || size.isEmpty) return null; + return (image: image, aspect: size.width / size.height); + } + + /// Width to height of the picture on top of a modal popup: the picture's own, so it + /// shows whole, but no wider than 2:1, no taller than 4:5, and no taller than 45% of + /// the height the popup has. + @visibleForTesting + static double imageAspect( + double own, { + required double width, + required double availableHeight, + }) { + const widest = 2.0; + const tallest = 0.8; + final byScreen = width / (availableHeight * 0.45); + final lowest = math.min(widest, math.max(tallest, byScreen)); + return own.clamp(lowest, widest); + } + + _PopupRoute _route( + InAppPopup popup, + _Picture? picture, + BuildContext navigatorContext, + ) { + final fullscreen = popup.position == InAppPopupPosition.unknown; + final buttons = + (popup.actionText ?? '').isNotEmpty || + (popup.closeText ?? '').isNotEmpty; + late final _PopupRoute route; + + void close() { + final navigator = route.navigator; + if (navigator == null || !route.isActive) return; + if (route.isCurrent) { + navigator.pop(); + } else { + navigator.removeRoute(route); + } + } + + void action() { + close(); + if (popup.pushSubscribeText != null) { + _run('notification settings', _openNotificationSettings); + } else if (popup.linkUrl != null) { + _run('link ${popup.linkUrl}', () => _openUrl(popup.linkUrl!)); + } + } + + route = _PopupRoute( + // A tap past the popup closes it only when it has no buttons, as on iOS. + barrierDismissible: !fullscreen && !buttons, + // Material wording when the app has it; CupertinoApp and WidgetsApp do not, and + // MaterialLocalizations.of would throw there. + barrierLabel: + Localizations.of( + navigatorContext, + MaterialLocalizations, + )?.modalBarrierDismissLabel ?? + 'Dismiss', + barrierColor: fullscreen ? Colors.transparent : const Color(0x80000000), + transitionDuration: const Duration(milliseconds: 220), + pageBuilder: (context, _, _) => _PopupPage( + popup: popup, + picture: picture, + onAction: action, + onClose: close, + ), + transitionBuilder: (context, animation, _, child) => + _transition(popup.position, animation, child), + ); + return route; + } + + static Widget _transition( + InAppPopupPosition position, + Animation animation, + Widget child, + ) { + final curved = CurvedAnimation( + parent: animation, + curve: Curves.easeOutCubic, + reverseCurve: Curves.easeInCubic, + ); + final faded = FadeTransition(opacity: curved, child: child); + Widget slide(double from) => SlideTransition( + position: Tween( + begin: Offset(0, from), + end: Offset.zero, + ).animate(curved), + child: faded, + ); + return switch (position) { + InAppPopupPosition.center => ScaleTransition( + scale: Tween(begin: 0.95, end: 1).animate(curved), + child: faded, + ), + InAppPopupPosition.top => slide(-0.1), + InAppPopupPosition.bottom => slide(0.1), + InAppPopupPosition.unknown => slide(0.04), + }; + } + + /// Runs a platform call nobody waits for; a failure is logged instead of escaping as an + /// uncaught error, which crash reporters count as a crash. + static void _run(String what, Future Function() call) { + unawaited( + Future.sync( + call, + ).then((_) {}, onError: (Object error) => _log('$what — $error')), + ); + } + + static void _log(String message) => + debugPrint('PersonalizationPopup: $message'); +} + +/// The dialog route a popup is shown in. [gone] completes when the popup leaves the +/// screen for any reason: closed, removed, or dropped with its navigator. +class _PopupRoute extends RawDialogRoute { + _PopupRoute({ + required super.pageBuilder, + super.barrierDismissible, + super.barrierColor, + super.barrierLabel, + super.transitionDuration, + super.transitionBuilder, + }); + + final Completer _gone = Completer(); + + Future get gone => _gone.future; + + @override + void didComplete(void result) { + super.didComplete(result); + if (!_gone.isCompleted) _gone.complete(); + } + + @override + void dispose() { + if (!_gone.isCompleted) _gone.complete(); + super.dispose(); + } +} + +typedef _Picture = ({ImageProvider image, double aspect}); + +class _Request { + _Request(this.popup); + + final InAppPopup popup; + final Completer done = Completer(); +} + +/// The popup as the server described it: centred, at the top or at the bottom with a +/// 16 margin, or fullscreen when the position is unknown. +class _PopupPage extends StatelessWidget { + const _PopupPage({ + required this.popup, + required this.picture, + required this.onAction, + required this.onClose, + }); + + final InAppPopup popup; + final _Picture? picture; + final VoidCallback onAction; + final VoidCallback onClose; + + static const double _margin = 16; + static const double _maxWidth = 370; + + @override + Widget build(BuildContext context) { + final fullscreen = popup.position == InAppPopupPosition.unknown; + final size = MediaQuery.sizeOf(context); + final padding = MediaQuery.paddingOf(context); + final width = math.min(_maxWidth, size.width - 2 * _margin); + final picture = this.picture; + final card = PersonalizationInAppPopup( + view: picture == null + ? PersonalizationInAppPopupView.text + : PersonalizationInAppPopupView.image, + presentation: fullscreen + ? PersonalizationInAppPopupPresentation.fullscreen + : PersonalizationInAppPopupPresentation.modal, + title: popup.title, + text: popup.text, + actionText: popup.actionText, + closeText: popup.closeText, + image: picture?.image, + imageAspectRatio: picture == null + ? null + : PopupPresenter.imageAspect( + picture.aspect, + width: width, + availableHeight: size.height - padding.vertical - 2 * _margin, + ), + onAction: onAction, + onClose: onClose, + ); + + // The kit sets its own text styles; the transparent material only keeps the app's + // error text style (the yellow underline) from leaking into them. + if (fullscreen) { + // The status bar lies on the card (the picture starts below it), so its icons + // follow the popup's brightness. + final light = + PersonalizationTheme.brightnessOf(context) == Brightness.dark; + return AnnotatedRegion( + value: light ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark, + child: Material(type: MaterialType.transparency, child: card), + ); + } + + return Padding( + padding: padding + const EdgeInsets.all(_margin), + child: Align( + alignment: switch (popup.position) { + InAppPopupPosition.top => Alignment.topCenter, + InAppPopupPosition.bottom => Alignment.bottomCenter, + _ => Alignment.center, + }, + child: SizedBox( + width: width, + // Taller than the screen only with a very long text; it scrolls then. No clip: + // it would cut the popup's shadow. + child: SingleChildScrollView( + clipBehavior: Clip.none, + child: Material(type: MaterialType.transparency, child: card), + ), + ), + ), + ); + } +} diff --git a/lib/src/tracking/tracking_api.dart b/lib/src/tracking/tracking_api.dart index 064324b..28bcdf8 100644 --- a/lib/src/tracking/tracking_api.dart +++ b/lib/src/tracking/tracking_api.dart @@ -10,13 +10,20 @@ import 'tracking_models.dart'; /// Every method routes to the native namespace of the same name, so an event fired from Dart /// is the same request the native SDKs send. class TrackingApi { - TrackingApi(this._api, this._shopId); + TrackingApi( + this._api, + this._shopId, { + void Function(int popupId)? onPopupShown, + }) : _onPopupShown = onPopupShown; final pigeon.PersonalizationHostApi _api; /// The shop this namespace tracks for; `null` is the legacy default instance. final String? _shopId; + /// Tells the popup presenter a popup the host drew is on screen. + final void Function(int popupId)? _onPopupShown; + /// Product page opened (`view`). Future productView(String itemId, {TrackingSource? source}) { _requireNonEmpty(itemId, 'itemId'); @@ -101,6 +108,16 @@ class TrackingApi { return _api.trackStoryClick(storyId, slideId, code, _shopId); } + /// A server popup the app drew itself is on screen (`popup/showed`). + /// + /// Only for popups taken with `onPopup` and drawn by the app: the ones the SDK shows + /// are reported by the SDK. A reported popup is not handed over again for a minute, + /// even when the server sends it again. + Future popupShown(int popupId) { + _onPopupShown?.call(popupId); + return _api.trackPopupShown(popupId, _shopId); + } + /// Stores the attribution source for subsequent events. /// /// Use it when the source outlives a single call — a user entering the catalog from a diff --git a/lib/src/ui/components/personalization_in_app_popup.dart b/lib/src/ui/components/personalization_in_app_popup.dart index 0bf65d3..b97614c 100644 --- a/lib/src/ui/components/personalization_in_app_popup.dart +++ b/lib/src/ui/components/personalization_in_app_popup.dart @@ -30,7 +30,11 @@ enum PersonalizationInAppPopupPresentation { modal, fullscreen } /// картинки: в макете виды «только текст» и «иконка» картинки не имеют, но /// крестик у них нарисован. Он круглый (компонент Close: кнопка MD с радиусом /// Rounded) и во всех видах лежит поверх содержимого в правом верхнем углу, на -/// отступе попапа; над фотографией — в тёмном варианте. Текстовая кнопка +/// отступе попапа. Над фотографией макет рисует его в тёмном варианте (белая +/// иконка на белой подложке 5%), но на светлом фото — а фото товара почти всегда на +/// белом — такой крестик пропадает. Поэтому крестик везде обычный вторичный и лежит +/// на круге цвета карточки: на любом фото виден либо круг, либо иконка. Текстовая +/// кнопка /// закрытия ([closeText]) в макете не нарисована — её даёт админка отдельным /// тумблером рядом с кнопкой действия, поэтому она здесь вторичной кнопкой под /// основной, на шаге 12 у модалки и 16 у полноэкранного. Пустой текст — кнопки @@ -40,20 +44,23 @@ enum PersonalizationInAppPopupPresentation { modal, fullscreen } /// Padding/Gap Full Screen (24), скругление модалки — радиус Modal, фон — /// Background/Card. У модалки тень Elevation 3 цветом Shadow/Heavy темы, у /// полноэкранного тени нет. -// TODO: связать виджет с данными SDK. Сейчас попап приходит только в натив, а через -// pigeon едет один булев флаг enableAutoPopupPresentation — payload до Dart не доходит, -// поэтому виджет пока только свёрстан и показывается в витрине примера. -// Чтобы включить: -// 1. android-sdk: точка перехвата вышла в v2.39.0, плагин на ней — -// SDK.popupPresentationListener (контракт тот же, что у iOS -// PopupPresentationDelegate: вернул null — натив не показывает). -// 2. pigeon: PopupWire (id, position, delay, components, popupActions) и -// onPopup(shopId, popup) в PersonalizationFlutterApi. -// 3. Плагины: поставить листенер / делегат, возвращать null, payload переслать в -// Dart. Флаг enableAutoPopupPresentation на Android уже доходит до Rees46Config. -// 4. Показ трекает Dart, когда виджет действительно на экране: придержанный попап -// натив не трекает и не запоминает (так и на iOS). Значит, дедуп на 60 секунд -// тоже на стороне Dart, иначе повтор с сервера покажется дважды. +/// +/// Высоту задаёт тот, кто показывает. Ограничена — картинка и текст делят её как в +/// макете; не ограничена (попап в прокрутке или колонке) — попап берёт высоту по +/// содержимому: картинка сверху в пропорции [imageAspectRatio] (без неё 16:10), +/// картинка фоном — вся карточка 4:5. +/// +/// Картинка сверху показывается целиком: по содержимому — в своей пропорции +/// ([imageAspectRatio]), при заданной высоте — вписана в оставшееся место, поля +/// цвета карточки. Фото товара почти всегда на белом, и обрезка срезала бы сам товар. +/// Картинка фоном заполняет попап и обрезается — на то она и фон. +/// +/// Полноэкранный учитывает безопасные зоны: крестик, текст и кнопки остаются внутри, +/// а картинка сверху начинается под строкой состояния — иконки той лежат на +/// карточке, а не на светлом фото, где их не видно. +/// +/// Без [iconBuilder] крестик рисуется самим пакетом, так что попап можно показать и +/// без библиотеки SVG; SDK так и показывает попапы с сервера. class PersonalizationInAppPopup extends StatelessWidget { const PersonalizationInAppPopup({ super.key, @@ -64,6 +71,7 @@ class PersonalizationInAppPopup extends StatelessWidget { this.actionText, this.closeText, this.image, + this.imageAspectRatio, this.icon, this.iconBuilder, this.onAction, @@ -85,6 +93,11 @@ class PersonalizationInAppPopup extends StatelessWidget { /// Картинку даёт хост — кит не тянет сеть. final ImageProvider? image; + /// Ширина к высоте картинки сверху, когда высоту попап берёт по содержимому. Дайте + /// пропорцию самой картинки — она войдёт целиком; без неё 16:10, и картинка другой + /// формы обрезается. + final double? imageAspectRatio; + /// Иконка вида [PersonalizationInAppPopupView.icon]. final Widget? icon; @@ -110,7 +123,12 @@ class PersonalizationInAppPopup extends StatelessWidget { view == PersonalizationInAppPopupView.icon; @override - Widget build(BuildContext context) { + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) => + _build(context, hug: !constraints.hasBoundedHeight), + ); + + Widget _build(BuildContext context, {required bool hug}) { final theme = PersonalizationTheme.of(context); final colors = theme.colors; final pad = _modal @@ -119,6 +137,15 @@ class PersonalizationInAppPopup extends StatelessWidget { final gapSection = _modal ? PersonalizationSpacing.gapModal : PersonalizationSpacing.gapFullScreen; + // Полноэкранный лежит под строкой состояния и индикатором «Домой»: фон и фото + // уходят под них, всё, что нажимают и читают, — нет. + final insets = _modal ? EdgeInsets.zero : MediaQuery.paddingOf(context); + final inner = EdgeInsets.fromLTRB( + pad + insets.left, + pad + insets.top, + pad + insets.right, + pad + insets.bottom, + ); final surface = colors.backgroundCard; final radius = _modal @@ -128,38 +155,52 @@ class PersonalizationInAppPopup extends StatelessWidget { Widget content; switch (view) { case PersonalizationInAppPopupView.image: + final card = Container( + color: surface, + padding: inner.copyWith(top: pad), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + _textBlock(context), + SizedBox( + height: _modal + ? PersonalizationSpacing.xl + : PersonalizationSpacing.xl3, + ), + _buttons(context), + ], + ), + ); content = Column( crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: hug ? MainAxisSize.min : MainAxisSize.max, children: [ - // Картинка забирает всё, что остаётся над карточкой с текстом. - Expanded(child: _image()), - Container( - color: surface, - padding: EdgeInsets.all(pad), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisSize: MainAxisSize.min, - children: [ - _textBlock(context), - SizedBox( - height: _modal - ? PersonalizationSpacing.xl - : PersonalizationSpacing.xl3, - ), - _buttons(context), - ], + // Картинка забирает всё, что остаётся над карточкой с текстом; по + // содержимому — свою пропорцию. + if (hug) + AspectRatio( + aspectRatio: imageAspectRatio ?? 16 / 10, + child: _image(BoxFit.contain), + ) + else + Expanded( + child: Padding( + padding: EdgeInsets.only(top: insets.top), + child: _image(BoxFit.contain), + ), ), - ), + card, ], ); case PersonalizationInAppPopupView.imageBackground: - content = Stack( + final stack = Stack( fit: StackFit.expand, children: [ - _image(), + _image(BoxFit.cover), Padding( - padding: EdgeInsets.all(pad), + padding: inner, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -177,35 +218,41 @@ class PersonalizationInAppPopup extends StatelessWidget { ), ], ); + content = hug ? AspectRatio(aspectRatio: 4 / 5, child: stack) : stack; case PersonalizationInAppPopupView.text: case PersonalizationInAppPopupView.icon: - final centre = [ - if (view == PersonalizationInAppPopupView.icon && - icon != null) ...[ - SizedBox( - width: _modal ? 100 : 120, - height: _modal ? 100 : 120, - child: icon, - ), - const SizedBox(height: PersonalizationSpacing.xl3), + final centre = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (view == PersonalizationInAppPopupView.icon && + icon != null) ...[ + Center( + child: SizedBox( + width: _modal ? 100 : 120, + height: _modal ? 100 : 120, + child: icon, + ), + ), + const SizedBox(height: PersonalizationSpacing.xl3), + ], + _textBlock(context), ], - _textBlock(context), - ]; + ); content = Padding( - padding: EdgeInsets.all(pad), + padding: inner, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: hug ? MainAxisSize.min : MainAxisSize.max, children: [ - Expanded( - child: Center( - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: centre, - ), - ), - ), + // По содержимому текст начинается под крестиком, а не рядом с ним. + if (hug) ...[ + const SizedBox(height: _closeSize), + SizedBox(height: gapSection), + centre, + ] else + Expanded(child: Center(child: centre)), SizedBox(height: gapSection), _buttons(context), ], @@ -231,10 +278,16 @@ class PersonalizationInAppPopup extends StatelessWidget { color: surface, child: Stack( children: [ - Positioned.fill(child: content), + // По содержимому размер попапа задаёт само содержимое, иначе — тот, + // кто показывает. + if (hug) content else Positioned.fill(child: content), // Крестик всегда на месте — у видов без картинки тоже, накладкой // поверх содержимого. - Positioned(top: pad, right: pad, child: _closeIcon(context)), + Positioned( + top: pad + insets.top, + right: pad + insets.right, + child: _closeIcon(context), + ), ], ), ), @@ -242,9 +295,8 @@ class PersonalizationInAppPopup extends StatelessWidget { ); } - Widget _image() => image == null - ? const SizedBox.shrink() - : Image(image: image!, fit: BoxFit.cover); + Widget _image(BoxFit fit) => + image == null ? const SizedBox.shrink() : Image(image: image!, fit: fit); Widget _textBlock(BuildContext context) { final colors = PersonalizationTheme.of(context).colors; @@ -317,15 +369,61 @@ class PersonalizationInAppPopup extends StatelessWidget { ); } - // Над фотографией — и фоном, и сверху — крестик в тёмной палитре: в макете у - // него там тёмный режим. - Widget _closeIcon(BuildContext context) => PersonalizationButton( - size: PersonalizationButtonSize.md, - view: PersonalizationButtonView.secondary, - onDark: _overImage || view == PersonalizationInAppPopupView.image, - rounded: true, - iconStart: PersonalizationIcons.crossLarge, - iconBuilder: iconBuilder, - onPressed: onClose, + // Круг цвета карточки под полупрозрачной вторичной кнопкой: крестик виден на любом + // фото, в отличие от тёмного варианта из макета (см. описание класса). Над самой + // карточкой круг сливается с ней. + Widget _closeIcon(BuildContext context) => DecoratedBox( + decoration: BoxDecoration( + color: PersonalizationTheme.of(context).colors.backgroundCard, + shape: BoxShape.circle, + ), + child: PersonalizationButton( + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.secondary, + rounded: true, + iconStart: PersonalizationIcons.crossLarge, + iconBuilder: iconBuilder ?? _crossIcon, + onPressed: onClose, + ), ); + + /// Сторона кнопки-крестика: иконка MD 24 и по 8 с каждой стороны. + static const double _closeSize = 40; + + static Widget _crossIcon( + BuildContext context, + String asset, + double size, + Color color, + ) => CustomPaint(size: Size.square(size), painter: _CrossPainter(color)); +} + +/// Иконка cross-large без SVG: два штриха 2/32 от 6/32 до 26/32, концы скруглены. +class _CrossPainter extends CustomPainter { + const _CrossPainter(this.color); + + final Color color; + + @override + void paint(Canvas canvas, Size size) { + final unit = size.width / 32; + final paint = Paint() + ..color = color + ..strokeWidth = 2 * unit + ..strokeCap = StrokeCap.round; + canvas + ..drawLine( + Offset(6 * unit, 6 * unit), + Offset(26 * unit, 26 * unit), + paint, + ) + ..drawLine( + Offset(26 * unit, 6 * unit), + Offset(6 * unit, 26 * unit), + paint, + ); + } + + @override + bool shouldRepaint(_CrossPainter oldDelegate) => oldDelegate.color != color; } diff --git a/lib/src/ui/personalization_colors.dart b/lib/src/ui/personalization_colors.dart index f008be2..0c1aec8 100644 --- a/lib/src/ui/personalization_colors.dart +++ b/lib/src/ui/personalization_colors.dart @@ -313,112 +313,4 @@ class PersonalizationColors { shadowHeavy: shadowHeavy ?? this.shadowHeavy, ); } - - PersonalizationColors lerp(PersonalizationColors other, double t) { - return PersonalizationColors( - brandPrimary: Color.lerp(brandPrimary, other.brandPrimary, t)!, - neutral50: Color.lerp(neutral50, other.neutral50, t)!, - neutral100: Color.lerp(neutral100, other.neutral100, t)!, - semanticWarning: Color.lerp(semanticWarning, other.semanticWarning, t)!, - semanticDanger: Color.lerp(semanticDanger, other.semanticDanger, t)!, - semanticInfo: Color.lerp(semanticInfo, other.semanticInfo, t)!, - neutralSubtle: Color.lerp(neutralSubtle, other.neutralSubtle, t)!, - backgroundGeneric: Color.lerp( - backgroundGeneric, - other.backgroundGeneric, - t, - )!, - backgroundCard: Color.lerp(backgroundCard, other.backgroundCard, t)!, - backgroundFloat: Color.lerp(backgroundFloat, other.backgroundFloat, t)!, - backgroundModal: Color.lerp(backgroundModal, other.backgroundModal, t)!, - backgroundInput: Color.lerp(backgroundInput, other.backgroundInput, t)!, - backgroundTransparent: Color.lerp( - backgroundTransparent, - other.backgroundTransparent, - t, - )!, - backgroundInputDisabled: Color.lerp( - backgroundInputDisabled, - other.backgroundInputDisabled, - t, - )!, - buttonPrimary: Color.lerp(buttonPrimary, other.buttonPrimary, t)!, - buttonPrimaryFocus: Color.lerp( - buttonPrimaryFocus, - other.buttonPrimaryFocus, - t, - )!, - buttonSecondary: Color.lerp(buttonSecondary, other.buttonSecondary, t)!, - buttonSecondaryOnDark: Color.lerp( - buttonSecondaryOnDark, - other.buttonSecondaryOnDark, - t, - )!, - buttonSecondaryFocus: Color.lerp( - buttonSecondaryFocus, - other.buttonSecondaryFocus, - t, - )!, - buttonPrimaryDisabled: Color.lerp( - buttonPrimaryDisabled, - other.buttonPrimaryDisabled, - t, - )!, - buttonSecondaryDisabled: Color.lerp( - buttonSecondaryDisabled, - other.buttonSecondaryDisabled, - t, - )!, - buttonGhost: Color.lerp(buttonGhost, other.buttonGhost, t)!, - lineBrand: Color.lerp(lineBrand, other.lineBrand, t)!, - lineGeneric: Color.lerp(lineGeneric, other.lineGeneric, t)!, - lineGenericSubtle: Color.lerp( - lineGenericSubtle, - other.lineGenericSubtle, - t, - )!, - lineInput: Color.lerp(lineInput, other.lineInput, t)!, - lineInputFocus: Color.lerp(lineInputFocus, other.lineInputFocus, t)!, - textPrimary: Color.lerp(textPrimary, other.textPrimary, t)!, - textSecondary: Color.lerp(textSecondary, other.textSecondary, t)!, - textHint: Color.lerp(textHint, other.textHint, t)!, - textDarkPrimary: Color.lerp(textDarkPrimary, other.textDarkPrimary, t)!, - textDarkSecondary: Color.lerp( - textDarkSecondary, - other.textDarkSecondary, - t, - )!, - textDarkHint: Color.lerp(textDarkHint, other.textDarkHint, t)!, - textLightPrimary: Color.lerp( - textLightPrimary, - other.textLightPrimary, - t, - )!, - textLightSecondary: Color.lerp( - textLightSecondary, - other.textLightSecondary, - t, - )!, - textLightHint: Color.lerp(textLightHint, other.textLightHint, t)!, - textInvertedPrimary: Color.lerp( - textInvertedPrimary, - other.textInvertedPrimary, - t, - )!, - textInvertedSecondary: Color.lerp( - textInvertedSecondary, - other.textInvertedSecondary, - t, - )!, - textInvertedHint: Color.lerp( - textInvertedHint, - other.textInvertedHint, - t, - )!, - textBrand: Color.lerp(textBrand, other.textBrand, t)!, - textLink: Color.lerp(textLink, other.textLink, t)!, - textLinkVisited: Color.lerp(textLinkVisited, other.textLinkVisited, t)!, - shadowHeavy: Color.lerp(shadowHeavy, other.shadowHeavy, t)!, - ); - } } diff --git a/lib/src/ui/personalization_theme.dart b/lib/src/ui/personalization_theme.dart index bc45796..bc58f6d 100644 --- a/lib/src/ui/personalization_theme.dart +++ b/lib/src/ui/personalization_theme.dart @@ -1,4 +1,6 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; import 'personalization_colors.dart'; import 'personalization_radius.dart'; @@ -119,62 +121,29 @@ class PersonalizationRadiusScale { PersonalizationRadiusToken.toast => toast, PersonalizationRadiusToken.modal => modal, }; - - PersonalizationRadiusScale lerp(PersonalizationRadiusScale other, double t) => - PersonalizationRadiusScale( - xs: lerpDouble(xs, other.xs, t), - sm: lerpDouble(sm, other.sm, t), - md: lerpDouble(md, other.md, t), - lg: lerpDouble(lg, other.lg, t), - xl: lerpDouble(xl, other.xl, t), - xl2: lerpDouble(xl2, other.xl2, t), - xl3: lerpDouble(xl3, other.xl3, t), - xl4: lerpDouble(xl4, other.xl4, t), - xl5: lerpDouble(xl5, other.xl5, t), - xl6: lerpDouble(xl6, other.xl6, t), - xl7: lerpDouble(xl7, other.xl7, t), - rounded: lerpDouble(rounded, other.rounded, t), - buttonLg: lerpDouble(buttonLg, other.buttonLg, t), - buttonMd: lerpDouble(buttonMd, other.buttonMd, t), - buttonSm: lerpDouble(buttonSm, other.buttonSm, t), - segmentedLg: lerpDouble(segmentedLg, other.segmentedLg, t), - segmentedMd: lerpDouble(segmentedMd, other.segmentedMd, t), - segmentedSm: lerpDouble(segmentedSm, other.segmentedSm, t), - card: lerpDouble(card, other.card, t), - toast: lerpDouble(toast, other.toast, t), - modal: lerpDouble(modal, other.modal, t), - ); - - static double lerpDouble(double a, double b, double t) => a + (b - a) * t; } /// Тема дизайн-системы: то, что хост может подменить под свой бренд. /// -/// Подключается расширением к теме приложения: +/// Задаётся один раз на старте, обычно в `main`, и действует во всём приложении — +/// в `MaterialApp`, `CupertinoApp` и без них: /// /// ```dart -/// MaterialApp( -/// theme: ThemeData(extensions: >[ -/// PersonalizationTheme.light.copyWith( -/// colors: PersonalizationColors.light.copyWith(brandPrimary: Color(0xFF7C3AED)), -/// fontFamily: PersonalizationFontFamily( -/// regular: 'Inter', emphasized: 'Inter', -/// ), -/// ), -/// ]), -/// darkTheme: ThemeData.dark().copyWith(extensions: >[ -/// PersonalizationTheme.dark, -/// ]), -/// ) +/// PersonalizationTheme.configure( +/// lightColors: PersonalizationColors.light.copyWith(brandPrimary: Color(0xFF7C3AED)), +/// darkColors: PersonalizationColors.dark.copyWith(brandPrimary: Color(0xFFA78BFA)), +/// fontFamily: PersonalizationFontFamily(regular: 'Inter', emphasized: 'Inter'), +/// ); +/// PersonalizationTheme.mode = ThemeMode.system; /// ``` /// -/// Расширение можно переопределить и на поддереве через `Theme(data: ...)`: -/// разным магазинам в одном приложении можно дать разный брендинг. +/// Цвета задаются на каждую схему, шрифт и радиусы — одни на обе, как в остальных +/// SDK. Темизуются цвета, радиусы и шрифт — поверхность брендирования. Отступы, +/// тени и кегли остаются константами: это шкала макета, менять её не предполагается. /// -/// Темизуются цвета, радиусы и шрифт — поверхность брендирования. Отступы, тени -/// и кегли остаются константами: это шкала макета, менять её не предполагается. +/// Светлую или тёмную выбирает [mode]: по умолчанию как у приложения, или жёстко одну. @immutable -class PersonalizationTheme extends ThemeExtension { +class PersonalizationTheme { const PersonalizationTheme({ required this.colors, this.radius = const PersonalizationRadiusScale(), @@ -185,24 +154,104 @@ class PersonalizationTheme extends ThemeExtension { final PersonalizationRadiusScale radius; final PersonalizationFontFamily fontFamily; + /// Светлая тема из макета. static const PersonalizationTheme light = PersonalizationTheme( colors: PersonalizationColors.light, ); + /// Тёмная тема из макета. static const PersonalizationTheme dark = PersonalizationTheme( colors: PersonalizationColors.dark, ); - /// Тема из контекста. Расширение не подключено — берётся набор по яркости темы - /// приложения, поэтому компоненты работают и у хоста, которому тема не нужна, и - /// в тёмной схеме не остаются светлыми. - static PersonalizationTheme of(BuildContext context) { - final theme = Theme.of(context); - return theme.extension() ?? - (theme.brightness == Brightness.dark ? dark : light); + static PersonalizationTheme _light = light; + static PersonalizationTheme _dark = dark; + + /// Тема бренда для всего UI SDK. Незаданное остаётся из макета, а повторный вызов + /// задаёт тему целиком заново. + /// + /// Цвета обычно берутся частично: `PersonalizationColors.light.copyWith(...)`. Без + /// [darkColors] тёмная схема берёт из [lightColors] цвета бренда — основной и кнопки + /// Primary, — а остальное из макета: тёмные поверхности светлой темы не выводятся. + static void configure({ + PersonalizationColors? lightColors, + PersonalizationColors? darkColors, + PersonalizationFontFamily fontFamily = PersonalizationFontFamily.system, + PersonalizationRadiusScale radius = const PersonalizationRadiusScale(), + }) { + _light = PersonalizationTheme( + colors: lightColors ?? PersonalizationColors.light, + radius: radius, + fontFamily: fontFamily, + ); + _dark = PersonalizationTheme( + colors: + darkColors ?? + (lightColors == null + ? PersonalizationColors.dark + : _withBrand(PersonalizationColors.dark, lightColors)), + radius: radius, + fontFamily: fontFamily, + ); + _rebuildOnScreen(); + } + + /// Светлая или тёмная тема UI SDK. + /// + /// [ThemeMode.system] (по умолчанию) — как у приложения: по его теме Material, иначе + /// Cupertino, иначе по настройке устройства. [ThemeMode.light] и [ThemeMode.dark] — + /// всегда эта, что бы ни стояло в приложении. Задаётся один раз, обычно в `main`; + /// смена на лету перерисовывает то, что на экране. + static ThemeMode get mode => _mode; + + static set mode(ThemeMode value) { + if (value == _mode) return; + _mode = value; + _rebuildOnScreen(); + } + + static ThemeMode _mode = ThemeMode.system; + + /// Яркость, в которой рисуется UI SDK: заданная [mode], а в [ThemeMode.system] — + /// яркость приложения. + static Brightness brightnessOf(BuildContext context) => + PersonalizationBrightness._of(context) ?? + switch (_mode) { + ThemeMode.light => Brightness.light, + ThemeMode.dark => Brightness.dark, + // Тема Material ставит под собой CupertinoTheme со своей яркостью, у CupertinoApp + // она своя, а без обеих CupertinoTheme отдаёт настройку устройства. + ThemeMode.system => + CupertinoTheme.maybeBrightnessOf(context) ?? Brightness.light, + }; + + /// Тема из контекста: заданная [configure], нужной яркости ([brightnessOf]). Без + /// настройки — значения из макета, поэтому компоненты работают и у хоста, которому + /// тема не нужна, и в тёмной схеме не остаются светлыми. + static PersonalizationTheme of(BuildContext context) => + brightnessOf(context) == Brightness.dark ? _dark : _light; + + // Компоненты читают режим при сборке, а подписаться им не на что: при смене + // перестраивается всё дерево приложения — один раз на изменение настройки. + static void _rebuildOnScreen() { + final binding = WidgetsFlutterBinding.ensureInitialized(); + void rebuild([Duration? _]) { + void visit(Element element) { + element.markNeedsBuild(); + element.visitChildren(visit); + } + + binding.rootElement?.visitChildren(visit); + } + + // Посреди сборки кадра помечать нельзя — тогда сразу после него. + if (binding.schedulerPhase == SchedulerPhase.persistentCallbacks) { + binding.addPostFrameCallback(rebuild); + } else { + rebuild(); + } } - @override PersonalizationTheme copyWith({ PersonalizationColors? colors, PersonalizationRadiusScale? radius, @@ -214,18 +263,39 @@ class PersonalizationTheme extends ThemeExtension { fontFamily: fontFamily ?? this.fontFamily, ); } +} + +/// [base] с цветами бренда из [brand]: основной цвет, кнопки Primary, линия и текст +/// бренда. +PersonalizationColors _withBrand( + PersonalizationColors base, + PersonalizationColors brand, +) => base.copyWith( + brandPrimary: brand.brandPrimary, + buttonPrimary: brand.buttonPrimary, + buttonPrimaryDisabled: brand.buttonPrimaryDisabled, + lineBrand: brand.lineBrand, + textBrand: brand.textBrand, +); + +/// Принудительная яркость UI кита на поддереве — для мест, где фон задаёт не тема, а +/// содержимое: слайды сторис с фото и видео всегда тёмные. Цвета берутся из темы +/// нужной яркости, заданной [PersonalizationTheme.configure]. Внутреннее: наружу из +/// пакета не экспортируется. +class PersonalizationBrightness extends InheritedWidget { + const PersonalizationBrightness({ + super.key, + required this.brightness, + required super.child, + }); + + final Brightness brightness; + + static Brightness? _of(BuildContext context) => context + .dependOnInheritedWidgetOfExactType() + ?.brightness; @override - PersonalizationTheme lerp( - ThemeExtension? other, - double t, - ) { - if (other is! PersonalizationTheme) return this; - return PersonalizationTheme( - colors: colors.lerp(other.colors, t), - radius: radius.lerp(other.radius, t), - // Шрифт не интерполируется: переключается разом на середине перехода. - fontFamily: t < 0.5 ? fontFamily : other.fontFamily, - ); - } + bool updateShouldNotify(PersonalizationBrightness oldWidget) => + brightness != oldWidget.brightness; } diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index a105698..8f11ef4 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -12,7 +12,6 @@ import '../components/personalization_story_price.dart'; import '../components/personalization_story_sound_button.dart'; import '../components/personalization_story_used_products.dart'; import '../components/personalization_toast.dart'; -import '../personalization_colors.dart'; import '../personalization_theme.dart'; import 'personalization_story_viewer.dart'; import 'stories_gif_player.dart'; @@ -102,42 +101,11 @@ class StorySlideView extends StatelessWidget { Widget build(BuildContext context) { final slide = this.slide; final media = storyMediaOf(slide) != StoryMedia.none; - final base = Theme.of(context); - return Theme( - data: media ? _mediaTheme(base) : base, - child: Builder(builder: (context) => _body(context, slide, media)), - ); - } - - /// Тема слайдов с медиа: тёмные токены кита. Тема хоста уже тёмная — берётся она, - /// иначе тёмный набор кита с брендом, радиусами и шрифтом хоста. - static ThemeData _mediaTheme(ThemeData base) { - final host = base.extension(); - final PersonalizationTheme dark; - if (host != null && base.brightness == Brightness.dark) { - dark = host; - } else { - final source = host ?? PersonalizationTheme.light; - final brand = source.colors; - dark = PersonalizationTheme.dark.copyWith( - radius: source.radius, - fontFamily: source.fontFamily, - colors: PersonalizationColors.dark.copyWith( - brandPrimary: brand.brandPrimary, - buttonPrimary: brand.buttonPrimary, - buttonPrimaryDisabled: brand.buttonPrimaryDisabled, - lineBrand: brand.lineBrand, - textBrand: brand.textBrand, - ), - ); - } - return base.copyWith( - extensions: [ - for (final extension in base.extensions.values) - if (extension is! PersonalizationTheme) extension, - dark, - ], - ); + final body = Builder(builder: (context) => _body(context, slide, media)); + // Слайды с медиа — тёмные токены кита: текст и кнопки лежат на фото или видео. + return media + ? PersonalizationBrightness(brightness: Brightness.dark, child: body) + : body; } Widget _body(BuildContext context, StorySlide slide, bool media) { diff --git a/pigeons/personalization_api.dart b/pigeons/personalization_api.dart index 0cd0de3..45adef9 100644 --- a/pigeons/personalization_api.dart +++ b/pigeons/personalization_api.dart @@ -448,6 +448,28 @@ abstract class PersonalizationHostApi { String? segment, String? shopId, ); + + /// Reports popup [popupId] as shown (`popup/showed`) — native `tracking.popupShown` + /// (Android) / `trackPopupShown` (iOS). The native SDKs never show a popup themselves + /// under the plugin, so they never report one either: Dart does, once it is on screen. + @async + void trackPopupShown(int popupId, String? shopId); + + /// 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. + void openNotificationSettings(); +} + +/// Server popups, handed over instead of being shown natively: the plugin sets the native +/// presentation listener (Android) / delegate (iOS), which keeps every popup back and +/// forwards it here. Separate from [PersonalizationFlutterApi], which the push dispatcher +/// owns. +@FlutterApi() +abstract class PersonalizationPopupFlutterApi { + /// A popup arrived for [shopId]. [popupJson] is the popup as the server sends it: + /// `id`, `position`, `delay`, `components` and `popup_actions` (an object). + void onPopup(String shopId, String popupJson); } // Multi-instance: each inbound push callback carries the `shopId` the push diff --git a/test/popups/in_app_popup_test.dart b/test/popups/in_app_popup_test.dart new file mode 100644 index 0000000..1d58984 --- /dev/null +++ b/test/popups/in_app_popup_test.dart @@ -0,0 +1,167 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +Map _popup({ + Object? position = 'centered', + Map? components, + Map? actions, +}) => { + 'id': 42, + 'position': position, + 'delay': 3, + 'components': ?components, + 'popup_actions': ?actions, +}; + +void main() { + test('positions from the admin; anything else is unknown', () { + InAppPopupPosition position(Object? value) => + InAppPopup.fromJson(_popup(position: value)).position; + + expect(position('centered'), InAppPopupPosition.center); + expect(position('top'), InAppPopupPosition.top); + expect(position('fixed_bottom'), InAppPopupPosition.bottom); + expect(position(''), InAppPopupPosition.unknown); + expect(position('slide_left'), InAppPopupPosition.unknown); + expect(position(null), InAppPopupPosition.unknown); + }); + + test('id, delay and components', () { + final popup = InAppPopup.fromJson( + _popup( + components: { + 'header': 'Sale', + 'text': 'Up to 50%', + 'image': 'https://example.com/a.jpg', + }, + ), + ); + + expect(popup.id, 42); + expect(popup.delay, const Duration(seconds: 3)); + expect(popup.title, 'Sale'); + expect(popup.text, 'Up to 50%'); + expect(popup.imageUrl, 'https://example.com/a.jpg'); + }); + + test('blank texts count as missing', () { + final popup = InAppPopup.fromJson( + _popup( + components: {'header': ' ', 'image': ''}, + actions: { + 'close': {'button_text': ''}, + }, + ), + ); + + expect(popup.title, isNull); + expect(popup.imageUrl, isNull); + expect(popup.closeText, isNull); + }); + + group('link', () { + final json = _popup( + actions: { + 'link': { + 'button_text': 'Open', + 'link_android': 'app://android', + 'link_ios': 'app://ios', + 'link_web': 'https://example.com', + }, + 'close': {'button_text': 'Later'}, + }, + ); + + test('this platform first', () { + expect( + InAppPopup.fromJson(json, platform: TargetPlatform.android).linkUrl, + 'app://android', + ); + expect( + InAppPopup.fromJson(json, platform: TargetPlatform.iOS).linkUrl, + 'app://ios', + ); + }); + + test('then the web one, then the other platform', () { + final web = _popup( + actions: { + 'link': { + 'link_ios': 'app://ios', + 'link_web': 'https://example.com', + }, + }, + ); + final otherOnly = _popup( + actions: { + 'link': {'link_ios': 'app://ios'}, + }, + ); + + expect( + InAppPopup.fromJson(web, platform: TargetPlatform.android).linkUrl, + 'https://example.com', + ); + expect( + InAppPopup.fromJson( + otherOnly, + platform: TargetPlatform.android, + ).linkUrl, + 'app://ios', + ); + }); + + test('buttons', () { + final popup = InAppPopup.fromJson(json); + + expect(popup.linkText, 'Open'); + expect(popup.actionText, 'Open'); + expect(popup.closeText, 'Later'); + expect(popup.pushSubscribeText, isNull); + }); + }); + + test('the push subscription takes the place of the link button', () { + final popup = InAppPopup.fromJson( + _popup( + actions: { + 'link': {'button_text': 'Open'}, + 'system_mobile_push_subscribe': { + 'button_text': 'Subscribe', + }, + }, + ), + ); + + expect(popup.pushSubscribeText, 'Subscribe'); + expect(popup.actionText, 'Subscribe'); + }); + + test('numbers sent as strings and unexpected types', () { + final popup = InAppPopup.fromJson({ + 'id': '7', + 'delay': 2.0, + 'components': 'not a map', + 'popup_actions': {'link': 5}, + }); + + expect(popup.id, 7); + expect(popup.delay, const Duration(seconds: 2)); + expect(popup.title, isNull); + expect(popup.linkUrl, isNull); + }); + + test('components and actions sent as JSON inside a string', () { + final popup = InAppPopup.fromJson({ + 'id': 3, + 'components': '{"header":"Sale","text":"Up to 50%"}', + 'popup_actions': '{"close":{"button_text":"Later"}}', + }); + + expect(popup.title, 'Sale'); + expect(popup.closeText, 'Later'); + expect(popup.hasContent, isTrue); + expect(InAppPopup.fromJson({'id': 0}).hasContent, isFalse); + }); +} diff --git a/test/popups/popup_presenter_test.dart b/test/popups/popup_presenter_test.dart new file mode 100644 index 0000000..45faa16 --- /dev/null +++ b/test/popups/popup_presenter_test.dart @@ -0,0 +1,569 @@ +import 'package:flutter/cupertino.dart'; +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/popups/popup_presenter.dart'; +import 'package:rees46_sdk/src/ui/components/personalization_button.dart'; +import 'package:rees46_sdk/src/ui/personalization_icons.dart'; + +// A 1x1 transparent PNG: a picture that loads without the network. +final Uint8List _pixel = Uint8List.fromList([ + 0x89, + 0x50, + 0x4E, + 0x47, + 0x0D, + 0x0A, + 0x1A, + 0x0A, + 0x00, + 0x00, + 0x00, + 0x0D, + 0x49, // + 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, + 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, + 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, + 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, + 0x60, 0x82, +]); + +class _Harness { + final List tracked = []; + final List opened = []; + int settingsOpened = 0; + bool failLinks = false; + DateTime clock = DateTime(2026, 10, 15, 12); + late final PopupPresenter presenter = PopupPresenter( + trackShown: (id) async => tracked.add(id), + openUrl: (url) async { + if (failLinks) throw StateError('no browser'); + opened.add(url); + return true; + }, + openNotificationSettings: () async => settingsOpened++, + now: () => clock, + image: (url) => url == 'broken' ? NetworkImage(url) : MemoryImage(_pixel), + ); +} + +Future<_Harness> _pumpApp( + WidgetTester tester, { + EdgeInsets padding = EdgeInsets.zero, +}) async { + tester.view + ..physicalSize = const Size(400, 800) + ..devicePixelRatio = 1 + ..padding = FakeViewPadding(top: padding.top, bottom: padding.bottom); + addTearDown(tester.view.reset); + final harness = _Harness(); + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: Text('home'))), + ); + return harness; +} + +InAppPopup _popup({ + int id = 1, + InAppPopupPosition position = InAppPopupPosition.center, + Duration delay = Duration.zero, + String? imageUrl, + String? linkText, + String? linkUrl, + String? pushSubscribeText, + String? closeText, +}) => InAppPopup( + id: id, + position: position, + delay: delay, + title: 'Title $id', + text: 'Text $id', + imageUrl: imageUrl, + linkText: linkText, + linkUrl: linkUrl, + pushSubscribeText: pushSubscribeText, + closeText: closeText, +); + +final Finder _cross = find.byWidgetPredicate( + (widget) => + widget is PersonalizationButton && + widget.iconStart == PersonalizationIcons.crossLarge, +); + +void main() { + testWidgets('shows a popup over the navigator and reports it once', ( + tester, + ) async { + final h = await _pumpApp(tester); + + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + + expect(find.text('Title 1'), findsOneWidget); + expect(find.text('Text 1'), findsOneWidget); + expect(h.tracked, [1]); + + await tester.tap(_cross); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsNothing); + expect(h.tracked, [1]); + }); + + testWidgets('a popup with nothing to show is dropped', (tester) async { + final h = await _pumpApp(tester); + final taken = []; + + h.presenter.receive(const InAppPopup(id: 0)); + h.presenter.onPopup = taken.add; + h.presenter.receive(const InAppPopup(id: 0)); + await tester.pumpAndSettle(); + + expect(find.byType(PersonalizationInAppPopup), findsNothing); + expect(taken, isEmpty); + expect(h.tracked, isEmpty); + }); + + testWidgets('waits out the delay the shop set', (tester) async { + final h = await _pumpApp(tester); + + h.presenter.receive(_popup(delay: const Duration(seconds: 3))); + await tester.pump(const Duration(seconds: 2)); + expect(find.text('Title 1'), findsNothing); + + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsOneWidget); + }); + + testWidgets('a repeat within a minute is dropped, a later one is shown', ( + tester, + ) async { + final h = await _pumpApp(tester); + + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + await tester.tap(_cross); + await tester.pumpAndSettle(); + + h.clock = h.clock.add(const Duration(seconds: 59)); + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsNothing); + + h.clock = h.clock.add(const Duration(seconds: 2)); + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsOneWidget); + expect(h.tracked, [1, 1]); + }); + + testWidgets('one popup at a time; the next follows when it closes', ( + tester, + ) async { + final h = await _pumpApp(tester); + + h.presenter + ..receive(_popup(id: 1)) + ..receive(_popup(id: 2)) + ..receive(_popup(id: 2)); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsOneWidget); + expect(find.text('Title 2'), findsNothing); + + await tester.tap(_cross); + await tester.pumpAndSettle(); + expect(find.text('Title 2'), findsOneWidget); + expect(h.tracked, [1, 2]); + }); + + testWidgets('onPopup takes the popup; the SDK neither shows nor reports it', ( + tester, + ) async { + final h = await _pumpApp(tester); + final taken = []; + h.presenter.onPopup = taken.add; + + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + + expect(taken.map((popup) => popup.id), [1]); + expect(find.text('Title 1'), findsNothing); + expect(h.tracked, isEmpty); + + // Not reported by the app — the server's repeat comes through again. + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + expect(taken, hasLength(2)); + + // Reported — a repeat within a minute is dropped. + h.presenter + ..markShown(1) + ..receive(_popup()); + await tester.pumpAndSettle(); + expect(taken, hasLength(2)); + }); + + testWidgets('a popup held back is shown on request', (tester) async { + final h = await _pumpApp(tester); + InAppPopup? held; + h.presenter.onPopup = (popup) => held = popup; + + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsNothing); + + final closed = h.presenter.present(held!); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsOneWidget); + expect(h.tracked, [1]); + + var done = false; + closed.then((_) => done = true); + await tester.tap(_cross); + await tester.pumpAndSettle(); + expect(done, isTrue); + }); + + testWidgets('a popup the app asks for is shown again within the minute', ( + tester, + ) async { + final h = await _pumpApp(tester); + + for (var i = 0; i < 2; i++) { + h.presenter.present(_popup()); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsOneWidget); + await tester.tap(_cross); + await tester.pumpAndSettle(); + } + expect(h.tracked, [1, 1]); + }); + + testWidgets('automatic presentation off: nothing is shown', (tester) async { + final h = await _pumpApp(tester); + h.presenter.autoPresentation = false; + + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + + expect(find.text('Title 1'), findsNothing); + expect(h.tracked, isEmpty); + }); + + testWidgets('no navigator: dropped after the wait, not reported', ( + tester, + ) async { + final h = await _pumpApp(tester); + await tester.pumpWidget(const SizedBox()); + + h.presenter.receive(_popup()); + await tester.pump(PopupPresenter.navigatorWait); + await tester.pump(const Duration(milliseconds: 200)); + + expect(find.byType(PersonalizationInAppPopup), findsNothing); + expect(h.tracked, isEmpty); + }); + + testWidgets('shown over the root navigator, past a nested one', ( + tester, + ) async { + final h = await _pumpApp(tester); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Navigator( + onGenerateRoute: (_) => + MaterialPageRoute(builder: (_) => const Text('tab')), + ), + ), + ), + ); + + final navigators = tester.stateList(find.byType(Navigator)); + expect(navigators, hasLength(2)); + expect(PopupPresenter.rootNavigator(), same(navigators.first)); + + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + expect( + find.descendant( + of: find.byWidget(navigators.last.widget), + matching: find.byType(PersonalizationInAppPopup), + ), + findsNothing, + ); + expect(find.byType(PersonalizationInAppPopup), findsOneWidget); + }); + + testWidgets('the link button opens the link and closes the popup', ( + tester, + ) async { + final h = await _pumpApp(tester); + + h.presenter.receive( + _popup(linkText: 'Open', linkUrl: 'https://example.com'), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + + expect(h.opened, ['https://example.com']); + expect(find.text('Title 1'), findsNothing); + }); + + testWidgets('a link that fails to open is logged, not thrown', ( + tester, + ) async { + final h = await _pumpApp(tester) + ..failLinks = true; + + h.presenter.receive(_popup(linkText: 'Open', linkUrl: 'https://x.test')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + + // An uncaught error would fail the test on its own. + expect(find.text('Title 1'), findsNothing); + }); + + testWidgets('the push subscription opens the notification settings', ( + tester, + ) async { + final h = await _pumpApp(tester); + + h.presenter.receive( + _popup( + linkText: 'Open', + linkUrl: 'https://example.com', + pushSubscribeText: 'Subscribe', + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Open'), findsNothing); + await tester.tap(find.text('Subscribe')); + await tester.pumpAndSettle(); + + expect(h.settingsOpened, 1); + expect(h.opened, isEmpty); + }); + + testWidgets('the close button closes', (tester) async { + final h = await _pumpApp(tester); + + h.presenter.receive(_popup(closeText: 'Later')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Later')); + await tester.pumpAndSettle(); + + expect(find.text('Title 1'), findsNothing); + }); + + testWidgets('a tap past the popup closes it only when it has no buttons', ( + tester, + ) async { + final h = await _pumpApp(tester); + + h.presenter.receive(_popup(id: 1, closeText: 'Later')); + await tester.pumpAndSettle(); + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsOneWidget); + + await tester.tap(find.text('Later')); + await tester.pumpAndSettle(); + + h.presenter.receive(_popup(id: 2)); + await tester.pumpAndSettle(); + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + expect(find.text('Title 2'), findsNothing); + }); + + testWidgets( + 'positions: centred, at the top and at the bottom with 16 margin', + (tester) async { + final h = await _pumpApp(tester); + + Future shown(InAppPopupPosition position, int id) async { + h.presenter.receive(_popup(id: id, position: position)); + await tester.pumpAndSettle(); + final rect = tester.getRect(find.byType(PersonalizationInAppPopup)); + await tester.tap(_cross); + await tester.pumpAndSettle(); + return rect; + } + + final centre = await shown(InAppPopupPosition.center, 1); + final top = await shown(InAppPopupPosition.top, 2); + final bottom = await shown(InAppPopupPosition.bottom, 3); + + expect(centre.width, 368); // 400 - 2 * 16, under the 370 cap + expect(centre.center.dy, closeTo(400, 0.5)); + expect(top.top, 16); + expect(bottom.bottom, 800 - 16); + }, + ); + + testWidgets( + 'an unknown position is fullscreen, its cross below the status bar', + (tester) async { + final h = await _pumpApp( + tester, + padding: const EdgeInsets.only(top: 47, bottom: 34), + ); + + h.presenter.receive( + _popup(position: InAppPopupPosition.unknown, closeText: 'Later'), + ); + await tester.pumpAndSettle(); + + final popup = tester.getRect(find.byType(PersonalizationInAppPopup)); + expect(popup, const Rect.fromLTWH(0, 0, 400, 800)); + expect(tester.getRect(_cross).top, 47 + 24); + expect( + tester.getRect(find.text('Later')).bottom, + lessThan(800 - 34 - 24), + ); + }, + ); + + testWidgets('a picture that loads makes the image view', (tester) async { + final h = await _pumpApp(tester); + // Decoding runs outside the fake clock: decode the picture up front, so the + // presenter finds it in the image cache. + await tester.runAsync( + () => precacheImage( + MemoryImage(_pixel), + PopupPresenter.rootNavigator()!.context, + ), + ); + + h.presenter.receive(_popup(imageUrl: 'https://example.com/a.png')); + await tester.pumpAndSettle(); + + final popup = tester.widget( + find.byType(PersonalizationInAppPopup), + ); + expect(popup.view, PersonalizationInAppPopupView.image); + expect(popup.image, isA()); + // A square picture shows whole: its own 1:1, nudged to 45% of the screen height + // (368 / (0.45 * (800 - 32))). + expect(popup.imageAspectRatio, closeTo(368 / (0.45 * 768), 0.001)); + }); + + group('picture proportion', () { + double aspect(double own, {double height = 800}) => + PopupPresenter.imageAspect(own, width: 370, availableHeight: height); + + test('its own when it fits', () { + expect(aspect(1.5), 1.5); + expect(aspect(1.2), 1.2); + }); + + test('no wider than 2:1', () => expect(aspect(4), 2)); + + test('no taller than 4:5', () => expect(aspect(0.5, height: 2000), 0.8)); + + test('no taller than 45% of the height', () { + // 370 / (0.45 * 600) ≈ 1.37: a square picture is cropped a little. + expect(aspect(1, height: 600), closeTo(1.37, 0.01)); + }); + + test('a very short screen never asks for wider than 2:1', () { + expect(aspect(1, height: 200), 2); + }); + }); + + testWidgets('a picture that fails leaves the popup without it', ( + tester, + ) async { + final h = await _pumpApp(tester); + + h.presenter.receive(_popup(imageUrl: 'broken')); + await tester.runAsync(() => Future.delayed(Duration.zero)); + await tester.pumpAndSettle(); + + final popup = tester.widget( + find.byType(PersonalizationInAppPopup), + ); + expect(popup.view, PersonalizationInAppPopupView.text); + expect(popup.image, isNull); + expect(h.tracked, [1]); + }); + + testWidgets('a CupertinoApp gets popups too', (tester) async { + final h = await _pumpApp(tester); + await tester.pumpWidget(const CupertinoApp(home: Text('home'))); + + h.presenter.receive(_popup()); + await tester.pumpAndSettle(); + + expect(find.text('Title 1'), findsOneWidget); + expect(h.tracked, [1]); + }); + + testWidgets('the queue goes on after the navigator goes away under a popup', ( + tester, + ) async { + final h = await _pumpApp(tester); + + h.presenter.receive(_popup(id: 1)); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsOneWidget); + + // The app swaps its root MaterialApp, say after a login: the old navigator and the + // popup on it are gone without being closed. + await tester.pumpWidget( + MaterialApp(key: UniqueKey(), home: const Text('signed in')), + ); + await tester.pumpAndSettle(); + + h.presenter.receive(_popup(id: 2)); + await tester.pumpAndSettle(); + expect(find.text('Title 2'), findsOneWidget); + expect(h.tracked, [1, 2]); + }); + + testWidgets('the queue goes on when the app clears the stack under a popup', ( + tester, + ) async { + final h = await _pumpApp(tester); + + h.presenter + ..receive(_popup(id: 1)) + ..receive(_popup(id: 2)); + await tester.pumpAndSettle(); + expect(find.text('Title 1'), findsOneWidget); + + PopupPresenter.rootNavigator()!.popUntil((route) => route.isFirst); + await tester.pumpAndSettle(); + + expect(find.text('Title 1'), findsNothing); + expect(find.text('Title 2'), findsOneWidget); + }); + + testWidgets( + 'fullscreen: the status bar icons follow the popup, not the photo', + (tester) async { + final h = await _pumpApp(tester); + await tester.runAsync( + () => precacheImage( + MemoryImage(_pixel), + PopupPresenter.rootNavigator()!.context, + ), + ); + + h.presenter.receive( + _popup(position: InAppPopupPosition.unknown, imageUrl: 'x'), + ); + await tester.pumpAndSettle(); + + final region = tester.widget>( + find.byType(AnnotatedRegion).last, + ); + expect(region.value, SystemUiOverlayStyle.dark); + }, + ); +} diff --git a/test/popups/popup_sdk_test.dart b/test/popups/popup_sdk_test.dart new file mode 100644 index 0000000..1790c85 --- /dev/null +++ b/test/popups/popup_sdk_test.dart @@ -0,0 +1,72 @@ +import 'dart:convert'; + +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/popups/popup_dispatcher.dart'; + +class _FakeApi extends pigeon.PersonalizationHostApi { + final List<(int, String?)> tracked = <(int, String?)>[]; + + @override + Future initialize(pigeon.InitConfig config) async {} + + @override + Future trackPopupShown(int popupId, String? shopId) async => + tracked.add((popupId, shopId)); +} + +String _json(int id) => jsonEncode({ + 'id': id, + 'position': 'centered', + 'delay': 0, + 'components': {'header': 'Popup $id'}, +}); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + tearDown(PopupDispatcher.instance.reset); + + Future<(PersonalizationSdk, _FakeApi, List)> initialized( + String shopId, + ) async { + final api = _FakeApi(); + final sdk = PersonalizationSdk(api: api, shopId: shopId); + final taken = []; + sdk.onPopup = taken.add; + await sdk.initialize(SdkInitConfig(shopId: shopId)); + return (sdk, api, taken); + } + + testWidgets('a popup reaches the handle of the shop it came for', ( + tester, + ) async { + final (_, _, takenA) = await initialized('shop-a'); + final (_, _, takenB) = await initialized('shop-b'); + + PopupDispatcher.instance + ..onPopup('shop-b', _json(2)) + ..onPopup('shop-c', _json(3)) + ..onPopup('shop-a', 'not json'); + await tester.pump(Duration.zero); + + expect(takenA, isEmpty); + expect(takenB.map((popup) => popup.title), ['Popup 2']); + }); + + testWidgets('tracking.popupShown reports for the shop and stops a repeat', ( + tester, + ) async { + final (sdk, api, taken) = await initialized('shop-a'); + + PopupDispatcher.instance.onPopup('shop-a', _json(5)); + await tester.pump(Duration.zero); + await sdk.tracking.popupShown(taken.single.id); + PopupDispatcher.instance.onPopup('shop-a', _json(5)); + await tester.pump(Duration.zero); + + expect(api.tracked, <(int, String?)>[(5, 'shop-a')]); + expect(taken, hasLength(1)); + }); +} diff --git a/test/ui/personalization_in_app_popup_test.dart b/test/ui/personalization_in_app_popup_test.dart index 371530a..8b09b8c 100644 --- a/test/ui/personalization_in_app_popup_test.dart +++ b/test/ui/personalization_in_app_popup_test.dart @@ -1,3 +1,6 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rees46_sdk/src/ui/personalization_ui.dart'; @@ -77,14 +80,25 @@ void main() { } }); - testWidgets('the cross takes the dark palette over a photo', (tester) async { + testWidgets('the cross keeps its solid backing over a photo too', ( + tester, + ) async { + // The design's dark cross over a photo (white on white 5%) vanishes on the light + // product photos shops send; the plain secondary one shows on any picture. for (final view in PersonalizationInAppPopupView.values) { await tester.pumpWidget(_host(PersonalizationInAppPopup(view: view))); expect( tester.widget(_cross).onDark, - view == PersonalizationInAppPopupView.image || - view == PersonalizationInAppPopupView.imageBackground, + isFalse, + reason: '$view', + ); + final backing = tester.widget( + find.ancestor(of: _cross, matching: find.byType(DecoratedBox)).first, + ); + expect( + (backing.decoration as BoxDecoration).color, + PersonalizationColors.light.backgroundCard, reason: '$view', ); } @@ -164,4 +178,192 @@ void main() { expect(_shadows(tester), isEmpty); }); + + group('height by content', () { + // In a scroll view the height is unbounded: the popup sizes to its content. + Widget scrolling(PersonalizationInAppPopupView view) => MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 370, + height: 800, + child: SingleChildScrollView( + child: PersonalizationInAppPopup( + view: view, + title: 'Title', + text: 'Text', + actionText: 'Open', + closeText: 'Later', + image: const _NoImage(), + ), + ), + ), + ), + ); + + for (final view in PersonalizationInAppPopupView.values) { + testWidgets('$view lays out without overflow', (tester) async { + await tester.pumpWidget(scrolling(view)); + + expect(tester.takeException(), isNull); + final size = tester.getSize(find.byType(PersonalizationInAppPopup)); + expect(size.width, 370); + expect(size.height, inExclusiveRange(100, 800)); + }); + } + + testWidgets('the picture on top keeps 16:10', (tester) async { + await tester.pumpWidget(scrolling(PersonalizationInAppPopupView.image)); + + final image = tester.getSize(find.byType(Image)); + expect(image.width / image.height, closeTo(1.6, 0.01)); + }); + + testWidgets('the picture on top takes the proportion given', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 370, + child: SingleChildScrollView( + child: PersonalizationInAppPopup( + title: 'Title', + image: const _NoImage(), + imageAspectRatio: 1, + ), + ), + ), + ), + ), + ); + + final image = tester.getSize(find.byType(Image)); + expect(image.width, 370); + expect(image.height, 370); + }); + + testWidgets('the picture behind is a 4:5 card', (tester) async { + await tester.pumpWidget( + scrolling(PersonalizationInAppPopupView.imageBackground), + ); + + final size = tester.getSize(find.byType(PersonalizationInAppPopup)); + expect(size.width / size.height, closeTo(0.8, 0.01)); + }); + + testWidgets('the text starts below the cross', (tester) async { + await tester.pumpWidget(scrolling(PersonalizationInAppPopupView.text)); + + expect( + tester.getRect(find.text('Title')).top, + greaterThanOrEqualTo(tester.getRect(_cross).bottom), + ); + }); + }); + + testWidgets('a fullscreen popup keeps its controls inside the safe area', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: MediaQuery( + data: const MediaQueryData( + size: Size(400, 800), + padding: EdgeInsets.only(top: 47, bottom: 34), + ), + child: SizedBox( + width: 400, + height: 800, + child: PersonalizationInAppPopup( + view: PersonalizationInAppPopupView.imageBackground, + presentation: PersonalizationInAppPopupPresentation.fullscreen, + title: 'Title', + actionText: 'Open', + image: const _NoImage(), + ), + ), + ), + ), + ); + + expect(tester.getRect(_cross).top, 47 + 24); + expect(tester.getRect(find.text('Open')).bottom, lessThan(800 - 34 - 24)); + }); + + testWidgets('without an icon builder the cross draws itself', (tester) async { + await tester.pumpWidget( + _host(const PersonalizationInAppPopup(title: 'Title')), + ); + + expect( + find.descendant( + of: _cross, + matching: find.byWidgetPredicate( + (widget) => + widget is CustomPaint && + widget.painter.runtimeType.toString() == '_CrossPainter', + ), + ), + findsOneWidget, + ); + }); + + testWidgets('the top picture is never cropped; a background one fills', ( + tester, + ) async { + Future fit(PersonalizationInAppPopupView view) async { + await tester.pumpWidget( + _host(PersonalizationInAppPopup(view: view, image: const _NoImage())), + ); + return tester.widget(find.byType(Image)).fit; + } + + expect(await fit(PersonalizationInAppPopupView.image), BoxFit.contain); + expect( + await fit(PersonalizationInAppPopupView.imageBackground), + BoxFit.cover, + ); + }); + + testWidgets('a fullscreen top picture starts below the status bar', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: MediaQuery( + data: const MediaQueryData( + size: Size(400, 800), + padding: EdgeInsets.only(top: 47, bottom: 34), + ), + child: SizedBox( + width: 400, + height: 800, + child: PersonalizationInAppPopup( + presentation: PersonalizationInAppPopupPresentation.fullscreen, + title: 'Title', + image: const _NoImage(), + ), + ), + ), + ), + ); + + expect(tester.getRect(find.byType(Image)).top, 47); + }); +} + +/// A picture that never loads: these tests only lay the popup out. +class _NoImage extends ImageProvider<_NoImage> { + const _NoImage(); + + @override + Future<_NoImage> obtainKey(ImageConfiguration configuration) => + SynchronousFuture<_NoImage>(this); + + @override + ImageStreamCompleter loadImage(_NoImage key, ImageDecoderCallback decode) => + OneFrameImageStreamCompleter(Completer().future); } diff --git a/test/ui/personalization_theme_mode_test.dart b/test/ui/personalization_theme_mode_test.dart new file mode 100644 index 0000000..b866d62 --- /dev/null +++ b/test/ui/personalization_theme_mode_test.dart @@ -0,0 +1,211 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +/// Captures what [PersonalizationTheme] resolves to where it is built. +class _Probe extends StatelessWidget { + const _Probe(); + + static PersonalizationTheme? theme; + static Brightness? brightness; + + @override + Widget build(BuildContext context) { + theme = PersonalizationTheme.of(context); + brightness = PersonalizationTheme.brightnessOf(context); + return const SizedBox(); + } +} + +void main() { + tearDown(() { + PersonalizationTheme.mode = ThemeMode.system; + PersonalizationTheme.configure(); + }); + + group('system: follows the app', () { + testWidgets('MaterialApp in light and in dark', (tester) async { + await tester.pumpWidget(const MaterialApp(home: _Probe())); + expect(_Probe.brightness, Brightness.light); + expect(_Probe.theme!.colors, PersonalizationColors.light); + + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(), + darkTheme: ThemeData(brightness: Brightness.dark), + themeMode: ThemeMode.dark, + home: const _Probe(), + ), + ); + await tester.pumpAndSettle(); // MaterialApp animates a theme change + expect(_Probe.brightness, Brightness.dark); + expect(_Probe.theme!.colors, PersonalizationColors.dark); + }); + + testWidgets('CupertinoApp with a dark theme', (tester) async { + await tester.pumpWidget( + const CupertinoApp( + theme: CupertinoThemeData(brightness: Brightness.dark), + home: _Probe(), + ), + ); + expect(_Probe.brightness, Brightness.dark); + expect(_Probe.theme!.colors, PersonalizationColors.dark); + }); + + testWidgets('CupertinoApp without a brightness takes the device setting', ( + tester, + ) async { + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + + await tester.pumpWidget(const CupertinoApp(home: _Probe())); + expect(_Probe.brightness, Brightness.dark); + }); + + testWidgets('no app theme at all takes the device setting', (tester) async { + await tester.pumpWidget( + const MediaQuery( + data: MediaQueryData(platformBrightness: Brightness.dark), + child: _Probe(), + ), + ); + expect(_Probe.brightness, Brightness.dark); + }); + }); + + testWidgets('a fixed mode wins over the app', (tester) async { + PersonalizationTheme.mode = ThemeMode.dark; + await tester.pumpWidget(const MaterialApp(home: _Probe())); + expect(_Probe.brightness, Brightness.dark); + expect(_Probe.theme!.colors, PersonalizationColors.dark); + + PersonalizationTheme.mode = ThemeMode.light; + await tester.pumpWidget( + const CupertinoApp( + theme: CupertinoThemeData(brightness: Brightness.dark), + home: _Probe(), + ), + ); + expect(_Probe.brightness, Brightness.light); + expect(_Probe.theme!.colors, PersonalizationColors.light); + }); + + group('configure', () { + const purple = Color(0xFF7C3AED); + const lilac = Color(0xFFA78BFA); + const font = PersonalizationFontFamily( + regular: 'Brand', + emphasized: 'Brand', + ); + + testWidgets('a partial override keeps the rest of the design', ( + tester, + ) async { + PersonalizationTheme.configure( + lightColors: PersonalizationColors.light.copyWith(brandPrimary: purple), + fontFamily: font, + ); + await tester.pumpWidget(const MaterialApp(home: _Probe())); + + final theme = _Probe.theme!; + expect(theme.colors.brandPrimary, purple); + expect( + theme.colors.backgroundCard, + PersonalizationColors.light.backgroundCard, + ); + expect(theme.fontFamily, font); + expect(theme.radius.modal, const PersonalizationRadiusScale().modal); + }); + + testWidgets('dark colours of the brand under a forced dark mode', ( + tester, + ) async { + PersonalizationTheme.configure( + lightColors: PersonalizationColors.light.copyWith(brandPrimary: purple), + darkColors: PersonalizationColors.dark.copyWith(brandPrimary: lilac), + fontFamily: font, + ); + PersonalizationTheme.mode = ThemeMode.dark; + await tester.pumpWidget(const MaterialApp(home: _Probe())); + + expect(_Probe.theme!.colors.brandPrimary, lilac); + expect( + _Probe.theme!.colors.backgroundCard, + PersonalizationColors.dark.backgroundCard, + ); + expect(_Probe.theme!.fontFamily, font); + }); + + testWidgets('without dark colours the dark scheme takes the brand', ( + tester, + ) async { + PersonalizationTheme.configure( + lightColors: PersonalizationColors.light.copyWith( + brandPrimary: purple, + buttonPrimary: purple, + ), + ); + PersonalizationTheme.mode = ThemeMode.dark; + await tester.pumpWidget(const MaterialApp(home: _Probe())); + + final colors = _Probe.theme!.colors; + expect(colors.brandPrimary, purple); + expect(colors.buttonPrimary, purple); + expect(colors.backgroundCard, PersonalizationColors.dark.backgroundCard); + expect(colors.textPrimary, PersonalizationColors.dark.textPrimary); + }); + + testWidgets('a CupertinoApp gets the brand too', (tester) async { + PersonalizationTheme.configure( + lightColors: PersonalizationColors.light.copyWith(brandPrimary: purple), + ); + await tester.pumpWidget(const CupertinoApp(home: _Probe())); + + expect(_Probe.theme!.colors.brandPrimary, purple); + }); + + testWidgets('configure() with nothing brings the design back', ( + tester, + ) async { + PersonalizationTheme.configure( + lightColors: PersonalizationColors.light.copyWith(brandPrimary: purple), + ); + PersonalizationTheme.configure(); + await tester.pumpWidget(const MaterialApp(home: _Probe())); + + expect( + _Probe.theme!.colors.brandPrimary, + PersonalizationColors.light.brandPrimary, + ); + }); + }); + + testWidgets('a forced brightness on a subtree wins over the mode', ( + tester, + ) async { + PersonalizationTheme.mode = ThemeMode.light; + await tester.pumpWidget( + const MaterialApp( + home: PersonalizationBrightness( + brightness: Brightness.dark, + child: _Probe(), + ), + ), + ); + + expect(_Probe.brightness, Brightness.dark); + expect(_Probe.theme!.colors, PersonalizationColors.dark); + }); + + testWidgets('a change on the fly redraws what is on screen', (tester) async { + await tester.pumpWidget(const MaterialApp(home: _Probe())); + expect(_Probe.brightness, Brightness.light); + + PersonalizationTheme.mode = ThemeMode.dark; + await tester.pump(); + + expect(_Probe.brightness, Brightness.dark); + }); +} From 4bf0666f109fce095f4b5273d41010cf136262ba Mon Sep 17 00:00:00 2001 From: andreykropotov Date: Tue, 20 Oct 2026 11:33:42 +0400 Subject: [PATCH 2/2] fix(android): native SDK v2.45.0 --- android/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/build.gradle.kts b/android/build.gradle.kts index 9c5c9b0..2d1e69f 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -87,7 +87,7 @@ android { dependencies { // REES46 Android SDK. - val rees46AndroidSdkVersion = "v2.42.0" + val rees46AndroidSdkVersion = "v2.45.0" add("rees46Implementation", "com.github.rees46:android-sdk:$rees46AndroidSdkVersion") // Used directly by the push presenter (NotificationCompat / ContextCompat). The native SDK