diff --git a/.pubignore b/.pubignore index 7b63a9b..160da42 100644 --- a/.pubignore +++ b/.pubignore @@ -35,3 +35,5 @@ migrate_working_dir/ # Maintainer-only release docs, not part of the public API. /doc/ /docs/ +# Live API samples of a demo shop's catalog: test data, not part of the package. +/test/fixtures/ diff --git a/README.md b/README.md index 177af6e..ade47bb 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ repository. The tag is the version the plugin requires — the `REES46` dependen [`ios/rees46_sdk.podspec`](ios/rees46_sdk.podspec): ```ruby -pod 'REES46', :git => 'https://github.com/rees46/ios-sdk.git', :tag => 'v3.36.1' +pod 'REES46', :git => 'https://github.com/rees46/ios-sdk.git', :tag => 'v3.37.0' ``` `pod install` then runs as part of `flutter run`. Update the tag together with the diff --git a/android/build.gradle.kts b/android/build.gradle.kts index 2d1e69f..9957070 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -87,7 +87,7 @@ android { dependencies { // REES46 Android SDK. - val rees46AndroidSdkVersion = "v2.45.0" + val rees46AndroidSdkVersion = "v2.47.0" add("rees46Implementation", "com.github.rees46:android-sdk:$rees46AndroidSdkVersion") // Used directly by the push presenter (NotificationCompat / ContextCompat). The native SDK 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 1896711..3be10ca 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 @@ -8,6 +8,8 @@ import android.os.Build import android.os.Bundle import android.provider.Settings import android.os.SystemClock +import android.view.View +import android.view.ViewTreeObserver import com.rees46.rees46_flutter_sdk.pigeon.FlutterError import com.rees46.rees46_flutter_sdk.pigeon.InitConfig import com.rees46.rees46_flutter_sdk.pigeon.ManageSubscriptionParamsWire @@ -467,6 +469,7 @@ class Rees46FlutterSdkPlugin : category: String, limit: Long?, page: Long?, + paramsJson: String?, shopId: String?, callback: (Result) -> Unit, ) { @@ -475,10 +478,22 @@ class Rees46FlutterSdkPlugin : return } try { + val p = if (!paramsJson.isNullOrBlank()) JSONObject(paramsJson) else null + val filters: Map? = p?.optJSONObject("filters")?.let { obj -> + obj.keys().asSequence().associateWith { key -> obj.get(key) } + }?.takeIf { it.isNotEmpty() } + fun price(key: String): Double? = p?.takeIf { it.has(key) && !it.isNull(key) }?.getDouble(key) sdk(shopId).categoryManager.getCategory( category = category, limit = limit?.toInt(), page = page?.toInt(), + brands = p?.optString("brands")?.takeIf { it.isNotEmpty() }, + locations = p?.optString("locations")?.takeIf { it.isNotEmpty() }, + filters = filters, + priceMin = price("price_min"), + priceMax = price("price_max"), + sortBy = p?.optString("sort_by")?.takeIf { it.isNotEmpty() }, + sortDir = p?.optString("sort_dir")?.takeIf { it.isNotEmpty() }, onSuccess = { response -> callback(Result.success(Gson().toJson(response))) }, @@ -555,6 +570,34 @@ class Rees46FlutterSdkPlugin : } } + override fun shareUrl( + url: String, + anchorX: Double, + anchorY: Double, + anchorWidth: Double, + anchorHeight: Double, + callback: (Result) -> Unit, + ) { + // The anchor is for the iPad popover; the Android chooser has none. + val send = Intent(Intent.ACTION_SEND) + .setType("text/plain") + .putExtra(Intent.EXTRA_TEXT, url) + val chooser = Intent.createChooser(send, null) + val activity = activityBinding?.activity + if (activity == null) chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + try { + (activity ?: applicationContext).startActivity(chooser) + } catch (e: ActivityNotFoundException) { + callback(Result.failure(FlutterError("share_failed", e.message, null))) + return + } + if (activity == null) { + callback(Result.success(Unit)) + return + } + ShareSheetWatcher(activity.window.decorView, callback).start() + } + override fun trackPopupShown(popupId: Long, shopId: String?, callback: (Result) -> Unit) = trackingCall(callback, shopId) { it.popupShown(popupId.toInt(), trackingListener(callback)) @@ -1183,3 +1226,41 @@ private fun NotificationData.toPayload(): Map { } return map } + +/** + * Completes [shareUrl][Rees46FlutterSdkPlugin.shareUrl] when the chooser is gone: the window of + * the activity lost its focus to the chooser and got it back (the user picked a target and came + * back, or closed the chooser). A chooser that never took the focus does not hold the viewer: + * the call completes after [NO_SHEET_MS]. + */ +private class ShareSheetWatcher( + private val view: View, + private val done: (Result) -> Unit, +) : ViewTreeObserver.OnWindowFocusChangeListener { + private var lost = !view.hasWindowFocus() + private var finished = false + + fun start() { + view.viewTreeObserver.addOnWindowFocusChangeListener(this) + view.postDelayed({ if (!lost) finish() }, NO_SHEET_MS) + } + + override fun onWindowFocusChanged(hasFocus: Boolean) { + if (!hasFocus) { + lost = true + } else if (lost) { + finish() + } + } + + private fun finish() { + if (finished) return + finished = true + view.viewTreeObserver.removeOnWindowFocusChangeListener(this) + done(Result.success(Unit)) + } + + private companion object { + const val NO_SHEET_MS = 1500L + } +} 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 83d816c..85f2b59 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 @@ -606,9 +606,13 @@ interface PersonalizationHostApi { /** * Returns a category product listing as a JSON string. * [limit] and [page] paginate the result; both are optional. + * [paramsJson] is a JSON object string with the optional filters: "brands" and + * "locations" (comma-separated strings), "filters" (facet name → [values]), + * "price_min" / "price_max" (numbers), "sort_by" / "sort_dir" (strings). A bridge + * passes on only what its native SDK takes for a category. * Dart layer parses the result into [CategoryResponse]. */ - fun getCategory(category: String, limit: Long?, page: Long?, shopId: String?, callback: (Result) -> Unit) + fun getCategory(category: String, limit: Long?, page: Long?, paramsJson: String?, shopId: String?, callback: (Result) -> Unit) /** * Returns a merchandised collection's products as a JSON string. * Dart layer parses the result into [CollectionResponse]. @@ -626,6 +630,14 @@ interface PersonalizationHostApi { * Returns false when nothing could open it. */ fun openUrl(url: String, callback: (Result) -> Unit) + /** + * Shows the system share sheet with one link [url] — the "Share" button of the stories + * viewer. Completes when the sheet is gone: iOS — `completionWithItemsHandler` of + * `UIActivityViewController`; Android — the window got its focus back after the + * chooser (`Intent.createChooser` of `ACTION_SEND`). The anchor is the button in + * logical pixels of the Flutter view: the popover of the sheet points at it on iPad. + */ + fun shareUrl(url: String, anchorX: Double, anchorY: Double, anchorWidth: Double, anchorHeight: Double, callback: (Result) -> Unit) /** * The slide ids seen per story id for [shop] — the plugin's own store * (SharedPreferences on Android, UserDefaults on iOS), not the native SDK's. It @@ -1075,8 +1087,9 @@ interface PersonalizationHostApi { val categoryArg = args[0] as String val limitArg = args[1] as Long? val pageArg = args[2] as Long? - val shopIdArg = args[3] as String? - api.getCategory(categoryArg, limitArg, pageArg, shopIdArg) { result: Result -> + val paramsJsonArg = args[3] as String? + val shopIdArg = args[4] as String? + api.getCategory(categoryArg, limitArg, pageArg, paramsJsonArg, shopIdArg) { result: Result -> val error = result.exceptionOrNull() if (error != null) { reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) @@ -1152,6 +1165,29 @@ interface PersonalizationHostApi { channel.setMessageHandler(null) } } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.shareUrl$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val urlArg = args[0] as String + val anchorXArg = args[1] as Double + val anchorYArg = args[2] as Double + val anchorWidthArg = args[3] as Double + val anchorHeightArg = args[4] as Double + api.shareUrl(urlArg, anchorXArg, anchorYArg, anchorWidthArg, anchorHeightArg) { 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.getStoriesSeen$separatedMessageChannelSuffix", codec) if (api != null) { diff --git a/assets/icons/share.svg b/assets/icons/share.svg new file mode 100644 index 0000000..08ae490 --- /dev/null +++ b/assets/icons/share.svg @@ -0,0 +1,3 @@ + + + diff --git a/example/README.md b/example/README.md index c106ba1..a4154fa 100644 --- a/example/README.md +++ b/example/README.md @@ -2,6 +2,9 @@ Demonstrates how to use the rees46_flutter_sdk plugin. +The demo shop alone, without the API and UI Kit tabs: `flutter run -t lib/main_shop.dart` +(build: `flutter build apk -t lib/main_shop.dart`, `flutter build ios -t lib/main_shop.dart`). + ## Getting Started This project is a starting point for a Flutter application. diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml index beb2859..fb1c1c5 100644 --- a/example/android/app/src/main/AndroidManifest.xml +++ b/example/android/app/src/main/AndroidManifest.xml @@ -24,6 +24,21 @@ + + + + + + + + + diff --git a/example/android/app/src/main/kotlin/com/rees46/rees46_flutter_sdk_example/MainActivity.kt b/example/android/app/src/main/kotlin/com/rees46/rees46_flutter_sdk_example/MainActivity.kt index bc81312..c2732cc 100644 --- a/example/android/app/src/main/kotlin/com/rees46/rees46_flutter_sdk_example/MainActivity.kt +++ b/example/android/app/src/main/kotlin/com/rees46/rees46_flutter_sdk_example/MainActivity.kt @@ -1,16 +1,46 @@ package com.rees46.rees46_flutter_sdk_example import android.Manifest +import android.content.Intent import android.content.pm.PackageManager import android.os.Build +import android.os.Bundle import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterActivity() { + /** Demo link the activity was started with, until Dart takes it (`getInitialLink`). */ + private var initialLink: String? = null + private var links: MethodChannel? = null + + override fun onCreate(savedInstanceState: Bundle?) { + // A recreated activity (rotation, process restore) does not open the link again. + if (savedInstanceState == null) initialLink = demoLink(intent) + super.onCreate(savedInstanceState) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + // singleTop: a link while the app is open comes here, not to onCreate. + demoLink(intent)?.let { links?.invokeMethod("onLink", it) } + } + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) + links = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, LINKS_CHANNEL) + .apply { + setMethodCallHandler { call, result -> + when (call.method) { + "getInitialLink" -> { + result.success(initialLink) + initialLink = null + } + else -> result.notImplemented() + } + } + } // The Flutter layer asks for the notification permission from a post-frame // callback (see main.dart) instead of from onCreate. Requesting it only after // the engine and first frame are up keeps the system dialog from racing @@ -44,8 +74,20 @@ class MainActivity : FlutterActivity() { } } + /** + * A VIEW link of the demo scheme, whatever its host and path: a stories "Share" link + * (`r46_stories`) or the game's (`rees46flutter://game`). Dart tells them apart. + */ + private fun demoLink(intent: Intent?): String? { + if (intent?.action != Intent.ACTION_VIEW) return null + val data = intent.data ?: return null + return if (data.scheme.equals(DEMO_SCHEME, ignoreCase = true)) data.toString() else null + } + private companion object { const val CHANNEL = "rees46_sdk_example/platform" + const val LINKS_CHANNEL = "rees46_sdk_example/links" + const val DEMO_SCHEME = "rees46flutter" const val REQUEST_CODE_POST_NOTIFICATIONS = 1001 } } diff --git a/example/assets/game/tic-tac-toe.html b/example/assets/game/tic-tac-toe.html new file mode 100644 index 0000000..73ff637 --- /dev/null +++ b/example/assets/game/tic-tac-toe.html @@ -0,0 +1,408 @@ + + + + + +Крестики-нолики + + + + +
+

Ваш ход

+ +
+ + +

Вы — ✕, компьютер — ◯. Первый ход по очереди

+
+ + + + + + diff --git a/example/assets/uikit/stories_polls_feed.json b/example/assets/uikit/stories_polls_feed.json new file mode 100644 index 0000000..8619969 --- /dev/null +++ b/example/assets/uikit/stories_polls_feed.json @@ -0,0 +1,379 @@ +{ + "status": "success", + "payload": { + "id": 1, + "settings": { + "avatar_size": "54", + "avatar_shape": "circle", + "border_not_viewed": "#119400", + "border_viewed": "#a0fdbc", + "pin_background": "#00cc33", + "pin_size": "20", + "background": "#ffffff", + "background_transparency": "100", + "color": "#212529", + "font_family": "-apple-system, Inter, system-ui, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif", + "font_size": "10", + "viewed_transparency": "0", + "progress_background": "#ffffff", + "close_color": "#ffffff", + "button_background": "#3b82f6", + "product_slide_background": "#000000", + "product_title_color": "#ffffff", + "product_price_background": "#f0f0f0", + "product_price_transparency": "0", + "product_price_color": "#18181b", + "product_old_price_color": "#868688", + "product_discount_background": "#f97316", + "product_status_color": "#ffffff", + "product_promo_code_background": "#18181b", + "product_promo_code_title_color": "#ffffff", + "product_notification_background": "#ffffff", + "product_notification_color": "#000000", + "pin_symbol": "📌", + "css_url": "https://storage.yandexcloud.net/r46v8/1/stories/1.css?v=1793634325-19616ad6" + }, + "stories": [ + { + "id": 9001, + "avatar": "https://cdn.stories.rees46.ru/14fcae67-551d-4a7a-828a-afc13fd5146c.jpg", + "name": "Опросы", + "pinned": false, + "share_url": null, + "shareable": false, + "start_position": 0, + "viewed": false, + "slides": [ + { + "id": 900, + "background": "https://cdn.stories.rees46.ru/2e6305ca-06db-4cca-8a75-0f50a0a42a97.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "mini_poll", + "y_offset": 50, + "allow_reanswer": true, + "labels": { + "reanswer": "Ответить заново", + "error": "Не удалось отправить ответ. Попробуйте еще раз" + }, + "poll": { + "code": "demo_single", + "kind": "single_choice", + "question": "Что вам больше нравится?", + "placeholder": null, + "max_length": null, + "submit_label": null, + "thanks_text": "Спасибо за ответ!", + "show_results": true, + "options": [ + { + "id": 1, + "label": "Кроссовки" + }, + { + "id": 2, + "label": "Ботинки" + }, + { + "id": 3, + "label": "Сандалии" + } + ] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 901, + "background": "https://cdn.stories.rees46.ru/5458c2f8-816a-4f53-82bb-89ad7995d4e1.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "mini_poll", + "y_offset": "40", + "allow_reanswer": false, + "labels": null, + "poll": { + "code": "demo_multi", + "kind": "multiple_choice", + "question": "Какие категории вам интересны?", + "placeholder": null, + "max_length": null, + "submit_label": "Отправить ответ", + "thanks_text": "Спасибо!", + "show_results": true, + "options": [ + { + "id": 1, + "label": "Обувь" + }, + { + "id": 2, + "label": "Одежда" + }, + { + "id": 3, + "label": "Аксессуары" + }, + { + "id": 4, + "label": "Спорт" + }, + { + "id": 5, + "label": "Дом" + } + ] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 902, + "background": "https://cdn.stories.rees46.ru/2e6305ca-06db-4cca-8a75-0f50a0a42a97.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "mini_poll", + "y_offset": 30, + "allow_reanswer": true, + "labels": { + "reanswer": "Ответить заново", + "error": "Не удалось отправить ответ. Попробуйте еще раз" + }, + "poll": { + "code": "demo_text", + "kind": "text", + "question": "Что нам улучшить?", + "placeholder": "Ваш ответ", + "max_length": "120", + "submit_label": null, + "thanks_text": "Спасибо за отзыв!", + "show_results": false, + "options": [] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 903, + "background": "https://cdn.stories.rees46.ru/5458c2f8-816a-4f53-82bb-89ad7995d4e1.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "nps", + "y_offset": 60, + "allow_reanswer": true, + "labels": { + "reanswer": "Ответить заново", + "error": "Не удалось отправить ответ. Попробуйте еще раз" + }, + "poll": { + "code": "test", + "channel": "test", + "name": "NPS", + "rate_min": 0, + "rate_max": 10, + "question": "Насколько вероятно, что вы порекомендуете нас друзьям?", + "bands": [ + { + "from": 0, + "to": 6, + "success": "Спасибо, мы станем лучше" + }, + { + "from": 7, + "to": 8, + "success": "Спасибо за оценку" + }, + { + "from": 9, + "to": 10, + "success": "Спасибо, мы рады!" + } + ] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 904, + "background": "https://cdn.stories.rees46.ru/2e6305ca-06db-4cca-8a75-0f50a0a42a97.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "csat", + "y_offset": 90, + "allow_reanswer": false, + "labels": null, + "poll": { + "code": "demo_csat", + "channel": null, + "name": "CSAT", + "rate_min": null, + "rate_max": null, + "question": "Как вам наш магазин?", + "bands": [ + { + "from": 1, + "to": 3, + "success": "Жаль" + }, + { + "from": 4, + "to": 5, + "success": "Ура" + } + ] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 905, + "background": "https://cdn.stories.rees46.ru/5458c2f8-816a-4f53-82bb-89ad7995d4e1.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "ces", + "y_offset": 5, + "allow_reanswer": true, + "labels": null, + "poll": { + "code": "demo_ces", + "channel": "stories", + "name": "CES", + "rate_min": "1", + "rate_max": "7", + "question": "Легко ли было оформить заказ?", + "bands": null + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 906, + "background": "https://cdn.stories.rees46.ru/2e6305ca-06db-4cca-8a75-0f50a0a42a97.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "mini_poll", + "y_offset": 50, + "allow_reanswer": true, + "labels": { + "reanswer": "Ответить заново", + "error": "Не удалось отправить ответ. Попробуйте еще раз" + }, + "poll": { + "code": "demo_answered", + "kind": "single_choice", + "question": "Уже отвечено: выбор с результатами", + "placeholder": null, + "max_length": null, + "submit_label": null, + "thanks_text": "Спасибо за ответ!", + "show_results": true, + "options": [ + { + "id": 1, + "label": "Да" + }, + { + "id": 2, + "label": "Нет" + } + ] + }, + "answer": { + "id": 77, + "option_ids": [ + 2 + ], + "text": null + }, + "results": { + "total": 120, + "options": [ + { + "id": 1, + "percent": 40 + }, + { + "id": 2, + "percent": 60 + } + ] + } + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 907, + "background": "https://cdn.stories.rees46.ru/5458c2f8-816a-4f53-82bb-89ad7995d4e1.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "quiz", + "y_offset": 50, + "allow_reanswer": true, + "labels": null, + "poll": { + "code": "demo_unknown", + "kind": "single_choice", + "question": "Неизвестный вид — не рисуется" + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + } + ] + } + ] + } +} \ No newline at end of file diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift index c30b367..1167f28 100644 --- a/example/ios/Runner/AppDelegate.swift +++ b/example/ios/Runner/AppDelegate.swift @@ -12,5 +12,63 @@ import UIKit func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "DemoLinks") { + DemoLinks.register(with: registrar) + } + } +} + +/// Links in the demo scheme, any host and path: stories "Share" links, +/// `rees46flutter:///?r46_stories=&r46_story=[&r46_slide=]`, and the +/// game's, `rees46flutter://game`. Dart tells them apart. +/// +/// Gets them from the scene (Flutter's deep linking is off in Info.plist: it would push them +/// to the Navigator as routes) and hands them to Dart over `rees46_sdk_example/links`: the +/// link the app was started with on request (`getInitialLink`), later ones as `onLink`. +final class DemoLinks: NSObject, FlutterPlugin, FlutterSceneLifeCycleDelegate { + private static let shared = DemoLinks() + + private var channel: FlutterMethodChannel? + + /// The link of the cold start, until Dart takes it. + private var initialLink: String? + + static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel( + name: "rees46_sdk_example/links", + binaryMessenger: registrar.messenger() + ) + shared.channel = channel + channel.setMethodCallHandler { call, result in + guard call.method == "getInitialLink" else { + result(FlutterMethodNotImplemented) + return + } + result(shared.initialLink) + shared.initialLink = nil + } + registrar.addSceneDelegate(shared) + } + + func scene( + _ scene: UIScene, + willConnectTo session: UISceneSession, + options connectionOptions: UIScene.ConnectionOptions? + ) -> Bool { + if let url = connectionOptions?.urlContexts.map(\.url).first(where: Self.isDemoLink) { + initialLink = url.absoluteString + } + return false + } + + func scene(_ scene: UIScene, openURLContexts URLContexts: Set) -> Bool { + guard let url = URLContexts.map(\.url).first(where: Self.isDemoLink) else { return false } + channel?.invokeMethod("onLink", arguments: url.absoluteString) + return true + } + + /// A link of the demo scheme, whatever its host and path. + private static func isDemoLink(_ url: URL) -> Bool { + url.scheme?.lowercased() == "rees46flutter" } } diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist index e80a01c..2107c74 100644 --- a/example/ios/Runner/Info.plist +++ b/example/ios/Runner/Info.plist @@ -24,6 +24,19 @@ ???? CFBundleVersion $(FLUTTER_BUILD_NUMBER) + CFBundleURLTypes + + + CFBundleURLName + com.rees46.rees46FlutterSdkExample.stories + CFBundleURLSchemes + + rees46flutter + + + + FlutterDeepLinkingEnabled + LSRequiresIPhoneOS UIApplicationSceneManifest diff --git a/example/lib/demo_app.dart b/example/lib/demo_app.dart new file mode 100644 index 0000000..ab7066b --- /dev/null +++ b/example/lib/demo_app.dart @@ -0,0 +1,290 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +// v3 (popups of the new builder, stories over API v3) is not public API; its gate is +// lifted when v3 goes public. The example reaches it directly, which the analyzer +// flags as an implementation import on purpose. +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; + +import 'game/game_screen.dart'; + +// What the full demo (`main.dart`) and the shop-only one (`main_shop.dart`) share: +// the hardcoded shop and its init, the theme, the demo's stories links and the game's. + +/// Hardcoded demo shop: both demos initialize it, the UI Kit and the shop reach it +/// by this id. +const String demoShopId = 'c1140c8254976de297c3caf971701a'; + +const String _demoApiDomain = 'api.rees46.ru'; + +/// Initializes [demoShopId] through the multi-instance [REES46] facade — the same +/// entry point the iOS/Android demos use — and returns its handle. The flags start +/// as the API tab shows them; it re-initializes with the switched ones. +PersonalizationSdk initializeDemoShop({ + bool enableLogs = false, + bool autoSendPushToken = true, + bool sendAdvertisingId = false, + bool enableAutoPopupPresentation = true, + bool needReInitialization = false, +}) => REES46.initialize( + REES46Config( + shopId: demoShopId, + apiDomain: _demoApiDomain, + stream: defaultTargetPlatform == TargetPlatform.android ? 'android' : 'ios', + enableLogs: enableLogs, + autoSendPushToken: autoSendPushToken, + sendAdvertisingId: sendAdvertisingId, + enableAutoPopupPresentation: enableAutoPopupPresentation, + needReInitialization: needReInitialization, + ), +); + +/// Asks the host for the Android 13+ notification permission. Called from a +/// post-frame callback rather than MainActivity.onCreate, so it runs after Patrol's +/// app-service handshake and the system dialog never hangs an integration test. +Future requestDemoNotificationPermission() async { + try { + await const MethodChannel( + 'rees46_sdk_example/platform', + ).invokeMethod('requestNotificationPermission'); + } catch (_) { + // Best-effort: the app still runs without it (pushes just won't be shown + // until the permission is granted), and non-Android hosts ignore it. + } +} + +/// Theme of both demos, on the kit's palette of that [brightness]: its brand is the +/// primary colour, its card the surface, its text colours the text; the tab bar is the +/// kit's card with the open tab in the brand colour and the others in the secondary +/// text colour. +ThemeData demoTheme(Brightness brightness) { + final colors = + (brightness == Brightness.dark + ? PersonalizationTheme.dark + : PersonalizationTheme.light) + .colors; + WidgetStateProperty byTab(T open, T other) => + WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) ? open : other, + ); + return ThemeData( + // The roles the kit has no colour for come from its brand colour. + colorScheme: + ColorScheme.fromSeed( + seedColor: colors.brandPrimary, + brightness: brightness, + ).copyWith( + primary: colors.brandPrimary, + onPrimary: colors.textLightPrimary, + error: colors.semanticDanger, + surface: colors.backgroundCard, + onSurface: colors.textPrimary, + onSurfaceVariant: colors.textSecondary, + outline: colors.lineGeneric, + outlineVariant: colors.lineGenericSubtle, + ), + navigationBarTheme: NavigationBarThemeData( + backgroundColor: colors.backgroundCard, + indicatorColor: colors.buttonSecondary, + iconTheme: byTab( + IconThemeData(color: colors.brandPrimary), + IconThemeData(color: colors.textSecondary), + ), + labelTextStyle: byTab( + PersonalizationTypography.xsEmphasized.copyWith( + color: colors.brandPrimary, + ), + PersonalizationTypography.xsDefault.copyWith( + color: colors.textSecondary, + ), + ), + ), + ); +} + +/// Scheme of the demo's own links. The stories with sharing share +/// `rees46flutter:///?r46_stories=…` instead of `https://`, and the app opens +/// such links (any host and path) from [DemoLinks]. +const String demoLinkScheme = 'rees46flutter'; + +/// Host of the stories API v3 of the demo's stories with sharing and of their links; +/// the global `PersonalizationStoriesV3.apiV3Domain` stays unset. +const String demoStoriesApiV3Domain = 'app.rees46.ru'; + +/// The slide link with the demo scheme instead of `http(s)://`. +String demoShareUrl(String url) => url.replaceFirst( + RegExp(r'^https?://', caseSensitive: false), + '$demoLinkScheme://', +); + +/// Links of the demo scheme, any host and path: stories "Share" links +/// (`rees46flutter:///?r46_stories=…`) and the game's +/// (`rees46flutter://game`). MainActivity / AppDelegate hand them over: the one the app +/// was started with on request (`getInitialLink`), later ones as `onLink`. +abstract final class DemoLinks { + static const MethodChannel _channel = MethodChannel( + 'rees46_sdk_example/links', + ); + + /// Hands [onLink] the link the app was started with (once, after the first frame) + /// and every link that comes while it runs. + static void listen(ValueChanged onLink) { + _channel.setMethodCallHandler((call) async { + if (call.method == 'onLink') onLink(call.arguments as String); + }); + WidgetsBinding.instance.addPostFrameCallback((_) async { + try { + final link = await _channel.invokeMethod('getInitialLink'); + if (link != null) onLink(link); + } catch (_) { + // No host channel (tests): no links. + } + }); + } + + static void cancel() => _channel.setMethodCallHandler(null); +} + +/// Navigator of both demos' apps: the game opens on it, over whatever is open — the +/// tabs and the shop's own navigator included. +final GlobalKey demoNavigatorKey = GlobalKey(); + +/// Schemes of the demos' own links: the Android and iOS demos', this one's +/// ([demoLinkScheme]) and the React Native one's. +const Set _demoSchemes = {'rees46', demoLinkScheme, 'rees46rn'}; + +/// The mini-game's link [url] read; `null` — not its link. +/// +/// The game's link is host `game` in the scheme of any demo — so one link of a story +/// or a popup in the dashboard opens the game in each of them — without +/// `r46_stories`, which makes it a stories link; the path does not matter. Its `url` +/// parameter, an `https` address, is a game of the app's own from its server +/// ([page]); anything else there, or nothing, is the built-in game. +({Uri? page})? readDemoGameLink(String url) { + final uri = Uri.tryParse(url.trim()); + if (uri == null || !_demoSchemes.contains(uri.scheme) || uri.host != 'game') { + return null; + } + // Pair by pair: broken %-encoding of one value spoils only that value. + final params = {}; + for (final pair in uri.query.split('&')) { + if (pair.isEmpty) continue; + final eq = pair.indexOf('='); + final key = _decoded(eq < 0 ? pair : pair.substring(0, eq)); + if (key == null) continue; + params.putIfAbsent( + key, + () => eq < 0 ? '' : _decoded(pair.substring(eq + 1)), + ); + } + if (params.containsKey('r46_stories')) return null; + final page = Uri.tryParse(params['url'] ?? ''); + final own = page != null && page.scheme == 'https' && page.host.isNotEmpty; + return (page: own ? page : null); +} + +String? _decoded(String component) { + try { + return Uri.decodeQueryComponent(component); + } on FormatException { + return null; + } +} + +/// Whether [url] is the mini-game's link ([readDemoGameLink]). +bool isDemoGameLink(String url) => readDemoGameLink(url) != null; + +/// The open game; another link to it while it is open opens nothing new. +Route? _openGame; + +/// Opens the game over the open screen if [url] is its link ([readDemoGameLink]). +/// `false` — not the game's link, or the app has no navigator yet. +/// +/// While the game is open the popups of triggers do not show: the SDK puts a popup +/// over the app's pages, the game's too — an app that the game's link starts would +/// get its `app_start` popups right over the game. +bool openDemoGameLink(String url) { + final link = readDemoGameLink(url); + if (link == null) return false; + final navigator = demoNavigatorKey.currentState; + if (navigator == null) return false; + if (_openGame?.isActive ?? false) return true; + final game = _openGame = MaterialPageRoute( + settings: const RouteSettings(name: DemoScreens.game), + fullscreenDialog: true, + builder: (_) => DemoGameScreen(url: link.page), + ); + final sdk = REES46.isInitialized(demoShopId) + ? REES46.getInstance(demoShopId) + : null; + final popups = sdk?.enableAutoPopupPresentation; + sdk?.enableAutoPopupPresentation = false; + navigator.push(game).whenComplete(() { + if (popups != null) sdk!.enableAutoPopupPresentation = popups; + }); + return true; +} + +/// Link of a slide's button in the demo's stories of [shopId] (the viewer has closed +/// by then): the game's opens the game here; the rest go to the system, as they would +/// without the handler. +ValueChanged demoStoriesLinkClick(String shopId) => (url) { + if (openDemoGameLink(url) || !REES46.isInitialized(shopId)) return; + REES46.getInstance(shopId).openUrl(url).catchError((Object error) { + debugPrint('Demo: cannot open $url — $error'); + return false; + }); +}; + +/// Screen codes the demos report to popups v3 — what the marketer puts in +/// `target_screens` of a popup in the editor. +abstract final class DemoScreens { + /// The full demo's tabs. + static const String api = 'api'; + static const String uiKit = 'ui_kit'; + + /// The shop's screens. + static const String home = 'home'; + static const String category = 'category'; + static const String product = 'product'; + static const String search = 'search'; + + /// The mini-game, over any screen. + static const String game = 'game'; +} + +/// Screen code of a shop route: its name, the navigator's first route ('/') being +/// the shop's home. +String? demoScreenName(Route route) => + route.settings.name == '/' ? DemoScreens.home : route.settings.name; + +/// Popups v3 of the demo shop that the "Show popup" menu of the shop's header shows by +/// hand: id and menu item. A new popup is one more line. +const List<({int id, String label})> demoManualPopups = [ + (id: 181, label: '#181 Banner · top'), + (id: 182, label: '#182 Modal · center'), + (id: 185, label: '#185 Fullscreen'), +]; + +/// Turns popups v3 on for [sdk], on the dashboard host of the demo shop +/// ([demoStoriesApiV3Domain]). The `/init` flag does not reach Flutter yet (the +/// plugin is built against the published native SDKs), so the demo forces the +/// engine on; its decisions and the popup events go to the debug log. A product of a +/// recommendations block in a popup goes to [onProductClick], which opens it in the +/// shop and returns true; the screen that sets it takes it off when it goes. The game's +/// link opens the game here, and the popup goes; the other links go to the system. +void enableDemoPopupsV3( + PersonalizationSdk sdk, { + bool Function(PersonalizationProduct product)? onProductClick, +}) { + sdk.popups + ..appHost = demoStoriesApiV3Domain + ..debug = true + ..onProductClick = onProductClick + // The game's link opened here: the popup goes, without `close`. + ..onLink = openDemoGameLink + ..ignoreInitFlag = true + ..enabled = true; +} diff --git a/example/lib/demo_tabs.dart b/example/lib/demo_tabs.dart new file mode 100644 index 0000000..1cccf5a --- /dev/null +++ b/example/lib/demo_tabs.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +/// The demo's sections as bottom tabs, in the order and under the names of the +/// native demos: "API" — the SDK methods, "UI Kit" — the kit's showcase, "Shop" — +/// the demo shop. "API" is open at start. +/// +/// The tabs keep their state: a tab is built the first time it is opened and stays +/// mounted after that, only the open one is shown — switching back finds it as it +/// was left. Built on first open rather than all at once, so the shop and the kit +/// do not load before the API tab has initialized the SDK. +/// +/// "Shop" has a navigator of its own, like a navigation controller in an iOS tab: +/// its category, product and search screens open inside the tab with the tab bar +/// still in place. System back walks that stack while "Shop" is the open tab; on +/// the shop's home, and on the other tabs, back does what it does anywhere else. +class DemoTabs extends StatefulWidget { + const DemoTabs({ + super.key, + required this.api, + required this.uiKit, + required this.shop, + this.shopObservers = const [], + this.onTab, + }); + + final Widget api; + final Widget uiKit; + + /// Home of the "Shop" tab, the first screen of its navigator. + final Widget shop; + + /// Observers of the "Shop" tab's navigator (its screens for popups v3). + final List shopObservers; + + /// A tab was opened: by the user, or by [DemoTabsState.openInShop]. + final ValueChanged? onTab; + + /// The tabs [context] is in, if any. + static DemoTabsState? of(BuildContext context) => + context.findAncestorStateOfType(); + + @override + State createState() => DemoTabsState(); +} + +class DemoTabsState extends State { + static const int _shopTab = 2; + + int _tab = 0; + + /// Tabs opened at least once; the others are not built yet. + final Set _opened = {0}; + + final GlobalKey _shopNavigator = GlobalKey(); + + void _open(int tab) { + setState(() { + _tab = tab; + _opened.add(tab); + }); + widget.onTab?.call(tab); + } + + /// Switches to "Shop" and hands [open] its navigator — after the next frame when + /// the tab is opened for the first time and its navigator is not built yet. + void openInShop(void Function(NavigatorState shop) open) { + if (_tab != _shopTab) _open(_shopTab); + final shop = _shopNavigator.currentState; + if (shop != null) { + open(shop); + return; + } + WidgetsBinding.instance.addPostFrameCallback((_) { + final shop = _shopNavigator.currentState; + if (shop != null) open(shop); + }); + } + + @override + Widget build(BuildContext context) { + final tabs = [ + widget.api, + widget.uiKit, + // Enabled only while the tab is open: from a hidden tab back would walk a + // stack nobody sees. + NavigatorPopHandler( + enabled: _tab == _shopTab, + onPopWithResult: (_) => _shopNavigator.currentState?.maybePop(), + child: Navigator( + key: _shopNavigator, + observers: widget.shopObservers, + onGenerateRoute: (settings) => MaterialPageRoute( + settings: settings, + builder: (_) => widget.shop, + ), + ), + ), + ]; + return Scaffold( + body: IndexedStack( + index: _tab, + children: [ + for (final (index, tab) in tabs.indexed) + _opened.contains(index) ? tab : const SizedBox.shrink(), + ], + ), + // The bar keeps clear of the bottom safe area itself. Its colours are the + // kit's (see `demoTheme`); a hairline parts it from a panel pinned over it. + bottomNavigationBar: DecoratedBox( + // Over the bar, which paints its own background. + position: DecorationPosition.foreground, + decoration: BoxDecoration( + border: Border( + top: BorderSide( + color: PersonalizationTheme.of(context).colors.lineGenericSubtle, + ), + ), + ), + child: NavigationBar( + selectedIndex: _tab, + onDestinationSelected: _open, + destinations: const [ + NavigationDestination( + key: Key('tab-api'), + icon: Icon(Icons.list), + label: 'API', + ), + NavigationDestination( + key: Key('tab-ui-kit'), + icon: Icon(Icons.grid_view_outlined), + selectedIcon: Icon(Icons.grid_view), + label: 'UI Kit', + ), + NavigationDestination( + key: Key('tab-shop'), + icon: Icon(Icons.shopping_bag_outlined), + selectedIcon: Icon(Icons.shopping_bag), + label: 'Shop', + ), + ], + ), + ), + ); + } +} diff --git a/example/lib/game/game_screen.dart b/example/lib/game/game_screen.dart new file mode 100644 index 0000000..acc7833 --- /dev/null +++ b/example/lib/game/game_screen.dart @@ -0,0 +1,145 @@ +import 'package:flutter/material.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:webview_flutter/webview_flutter.dart'; + +import '../shop/shop.dart'; + +/// The built-in game: tic-tac-toe against the computer as one web page (HTML, CSS and +/// JS, no network) — the same file in every demo. +const String demoGameAsset = 'assets/game/tic-tac-toe.html'; + +/// The demo's mini-game, full screen over the screen the game's link was opened from +/// (see `openDemoGameLink`): a panel with the title and the cross, the game's web page +/// under it. The page is the whole game, "Ещё раз" included; the cross and system back +/// close the screen. The page gets the app's theme through its `setGameTheme`, and +/// stays covered with the kit's background until it has it, so nothing flashes white. +class DemoGameScreen extends StatefulWidget { + const DemoGameScreen({super.key, this.url}); + + /// A game of the app's own from its server (`https`); `null` — the built-in one, + /// [demoGameAsset]. + final Uri? url; + + static const String title = 'Крестики-нолики'; + + @override + State createState() => _DemoGameScreenState(); +} + +class _DemoGameScreenState extends State { + late final WebViewController _page; + + /// The page has loaded and has the theme: the cover goes. + bool _shown = false; + + /// The theme the page has, and the background the view was given. + Brightness? _pageTheme; + Color? _background; + + @override + void initState() { + super.initState(); + _page = WebViewController() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setNavigationDelegate( + NavigationDelegate( + onPageFinished: (_) => _loaded(), + onWebResourceError: (error) { + if (error.isForMainFrame ?? true) _loaded(); + }, + ), + ); + final url = widget.url; + if (url == null) { + _page.loadFlutterAsset(demoGameAsset); + } else { + _page.loadRequest(url); + } + } + + /// A new document knows no theme yet: it gets the app's, then shows. + Future _loaded() async { + _pageTheme = null; + if (!mounted) return; + await _giveTheme(PersonalizationTheme.brightnessOf(context)); + if (mounted && !_shown) setState(() => _shown = true); + } + + Future _giveTheme(Brightness brightness) async { + if (_pageTheme == brightness) return; + _pageTheme = brightness; + final theme = brightness == Brightness.dark ? 'dark' : 'light'; + try { + // A page of another game may have no such function. + await _page.runJavaScript( + "window.setGameTheme && window.setGameTheme('$theme')", + ); + } catch (error) { + debugPrint('Demo game: theme not set — $error'); + } + } + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + final safe = MediaQuery.paddingOf(context); + // The app's theme may change while the game is open. + if (_background != colors.backgroundGeneric) { + _background = colors.backgroundGeneric; + _page.setBackgroundColor(colors.backgroundGeneric); + } + if (_shown) _giveTheme(PersonalizationTheme.brightnessOf(context)); + return ShopScaffold( + body: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: EdgeInsets.fromLTRB( + PersonalizationSpacing.paddingX, + safe.top + PersonalizationSpacing.md, + PersonalizationSpacing.paddingX, + PersonalizationSpacing.md, + ), + child: Row( + children: [ + Expanded( + child: Text( + DemoGameScreen.title, + style: shopTextStyle( + context, + PersonalizationTypography.xlEmphasized, + colors.textPrimary, + ), + ), + ), + ShopRoundButton( + icon: PersonalizationIcons.cross, + label: 'Закрыть', + onPressed: () => Navigator.of(context).maybePop(), + ), + ], + ), + ), + // The page keeps clear of the home indicator. + Expanded( + child: Padding( + padding: EdgeInsets.only(bottom: safe.bottom), + child: Stack( + children: [ + Positioned.fill(child: WebViewWidget(controller: _page)), + if (!_shown) + Positioned.fill( + child: ColoredBox( + color: colors.backgroundGeneric, + child: const Center(child: PersonalizationLoader()), + ), + ), + ], + ), + ), + ), + ], + ), + ); + } +} diff --git a/example/lib/main.dart b/example/lib/main.dart index 5063b03..b8dfb73 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,36 +1,65 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:flutter/foundation.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; +// v3 (popups of the new builder, stories over API v3) is not public API; its gate is +// lifted when v3 goes public. The example reaches it directly, which the analyzer +// flags as an implementation import on purpose. +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; import 'app_theme_mode.dart'; +import 'demo_app.dart'; +import 'demo_tabs.dart'; import 'multi_instance_pane.dart'; +import 'shop/shop_home.dart'; +import 'shop/shop_product.dart'; import 'ui_kit_pane.dart'; +// The shop alone, without the tabs, is `main_shop.dart`. void main() => runApp(const App()); +/// Screens of the "Shop" tab for popups v3. The tabs report their own codes; the +/// shop tab, when it is back, the screen open in it. +final PersonalizationScreenObserver _shopScreens = + PersonalizationScreenObserver( + shopId: demoShopId, + screenName: demoScreenName, + ); + +void _reportTab(int tab) => switch (tab) { + 0 => _shopScreens.reportScreen(DemoScreens.api), + 1 => _shopScreens.reportScreen(DemoScreens.uiKit), + _ => switch (_shopScreens.current) { + final screen? => _shopScreens.reportScreen(screen), + // Opened for the first time: its navigator reports the home itself. + null => null, + }, +}; + class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { - // themeMode is driven by the switch on the UI Kit screen, so the kit's dark + // themeMode is driven by the switch on the UI Kit tab, so the kit's dark // set can be checked without changing the device setting. return ValueListenableBuilder( valueListenable: appThemeMode, builder: (context, mode, _) => MaterialApp( title: 'REES46 Flutter SDK', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), - ), - darkTheme: ThemeData( - colorScheme: ColorScheme.fromSeed( - seedColor: Colors.blue, - brightness: Brightness.dark, - ), - ), + // The game opens on it, over the tabs. + navigatorKey: demoNavigatorKey, + theme: demoTheme(Brightness.light), + darkTheme: demoTheme(Brightness.dark), themeMode: mode, - home: const InitPage(), + // The sections are bottom tabs, as in the native demos. + home: DemoTabs( + api: const InitPage(), + uiKit: const UiKitPane(shopId: demoShopId), + shop: const ShopPane(shopId: demoShopId), + shopObservers: [_shopScreens], + onTab: _reportTab, + ), ), ); } @@ -158,17 +187,6 @@ class _InitPageState extends State { // [_initialize] (rebuilt on re-initialize). late PersonalizationSdk _sdk; - // Platform channel used to ask the host for the Android 13+ notification - // permission. See [_requestNotificationPermission]. - static const _platformChannel = MethodChannel('rees46_sdk_example/platform'); - - // Hardcoded demo credentials — the demo does not need editable init inputs. - static const _shopId = 'c1140c8254976de297c3caf971701a'; - static const _apiDomain = 'api.rees46.ru'; - final _stream = defaultTargetPlatform == TargetPlatform.android - ? 'android' - : 'ios'; - bool _enableLogs = false; bool _autoSendPushToken = true; bool _sendAdvertisingId = false; @@ -255,6 +273,11 @@ class _InitPageState extends State { @override void dispose() { + DemoLinks.cancel(); + // The popups' product handler holds this page; a new one sets its own. + if (REES46.isInitialized(demoShopId)) { + REES46.getInstance(demoShopId).popups.onProductClick = null; + } _recBlockController.dispose(); _productIdController.dispose(); _searchQueryController.dispose(); @@ -274,22 +297,20 @@ class _InitPageState extends State { // first await) and wires the push callbacks. The button below only // re-initializes (e.g. after toggling flags). _initialize(); - // Ask for the notification permission after the first frame. Triggering it from - // Dart (rather than MainActivity.onCreate) guarantees it runs after Patrol's - // app-service handshake, so the system dialog never hangs an integration test. + // After the first frame: see [requestDemoNotificationPermission]. WidgetsBinding.instance.addPostFrameCallback((_) { - _requestNotificationPermission(); + requestDemoNotificationPermission(); }); + // Links of the demo scheme, the one of a cold start included. + DemoLinks.listen(_openLink); } - Future _requestNotificationPermission() async { - try { - await _platformChannel.invokeMethod( - 'requestNotificationPermission', - ); - } catch (_) { - // Best-effort: the app still runs without it (pushes just won't be shown - // until the permission is granted), and non-Android hosts ignore it. + /// Opens the game over the tabs, or the stories campaign of [url] over API v3; the + /// SDK waits for its init. + void _openLink(String url) { + if (!mounted || openDemoGameLink(url)) return; + if (!openStoriesLink(context, url, shopId: demoShopId)) { + debugPrint('Demo: neither the game nor a stories link — $url'); } } @@ -305,20 +326,30 @@ class _InitPageState extends State { // so the Multi-instance screen resolves the very same instance via // REES46.getInstance(shopId). Re-initializing rebuilds the handle with the // current toggles. - _sdk = REES46.initialize( - REES46Config( - shopId: _shopId, - apiDomain: _apiDomain, - stream: _stream, - enableLogs: _enableLogs, - autoSendPushToken: _autoSendPushToken, - sendAdvertisingId: _sendAdvertisingId, - enableAutoPopupPresentation: _enableAutoPopupPresentation, - needReInitialization: _needReInitialization, - ), + _sdk = initializeDemoShop( + enableLogs: _enableLogs, + autoSendPushToken: _autoSendPushToken, + sendAdvertisingId: _sendAdvertisingId, + enableAutoPopupPresentation: _enableAutoPopupPresentation, + needReInitialization: _needReInitialization, ); // Holding popups back: the app takes each one and shows it when the user asks. _sdk.onPopup = _holdPopups ? _holdPopup : null; + // Popups v3: the API tab is the full demo's first screen. A product of a + // popup opens in the shop tab, and the popup goes. + enableDemoPopupsV3( + _sdk, + onProductClick: (product) { + final tabs = mounted ? DemoTabs.of(context) : null; + if (tabs == null) return false; + tabs.openInShop( + (shop) => + shop.push(ShopProductScreen.route(demoShopId, product.id)), + ); + return true; + }, + ); + _sdk.popups.screenOpened(DemoScreens.api); _sdk.setPushNotificationCallbacks( onReceived: (payload) { // In the demo we only surface init/token state; push payloads can be @@ -358,7 +389,7 @@ class _InitPageState extends State { title: 'Weekend sale', text: 'Up to 30% off home appliances until Sunday.', imageUrl: picture - ? 'https://pictures.rees46.ru/resize-images/520/$_shopId/143748.jpg' + ? 'https://pictures.rees46.ru/resize-images/520/$demoShopId/143748.jpg' : null, linkText: 'Shop now', linkUrl: 'https://rees46.com', @@ -776,16 +807,6 @@ class _InitPageState extends State { appBar: AppBar( title: const Text('REES46 SDK init demo'), actions: [ - IconButton( - key: const Key('open-ui-kit'), - tooltip: 'UI Kit', - icon: const Icon(Icons.widgets_outlined), - onPressed: () => Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => const UiKitPane(shopId: _shopId), - ), - ), - ), IconButton( key: const Key('open-multi-instance'), tooltip: 'Multi-instance (two shops)', @@ -824,17 +845,6 @@ class _InitPageState extends State { label: const Text('Open multi-instance demo (two shops)'), ), const SizedBox(height: 12), - FilledButton.tonalIcon( - key: const Key('open-ui-kit-button'), - onPressed: () => Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => const UiKitPane(shopId: _shopId), - ), - ), - icon: const Icon(Icons.widgets_outlined), - label: const Text('Open UI Kit (components and blocks)'), - ), - const SizedBox(height: 12), _PushTokenCard( token: _storedPushToken, updatedAt: _tokenUpdatedAt, diff --git a/example/lib/main_shop.dart b/example/lib/main_shop.dart new file mode 100644 index 0000000..041c127 --- /dev/null +++ b/example/lib/main_shop.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +// v3 (popups of the new builder, stories over API v3) is not public API; its gate is +// lifted when v3 goes public. The example reaches it directly, which the analyzer +// flags as an implementation import on purpose. +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; + +import 'demo_app.dart'; +import 'shop/shop_home.dart'; +import 'shop/shop_product.dart'; + +/// The demo shop alone: home → category → product, search and stories, without the +/// API and UI Kit tabs and their developer tools. Same app, same SDK init and the +/// same stories links as the full demo (`main.dart`): +/// `flutter run -t lib/main_shop.dart`. +void main() => runApp(const ShopApp()); + +class ShopApp extends StatelessWidget { + const ShopApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'REES46 Shop', + theme: demoTheme(Brightness.light), + darkTheme: demoTheme(Brightness.dark), + // The game opens on it, over the shop. + navigatorKey: demoNavigatorKey, + // The shop's screens for popups v3; the home reports itself once the SDK is up. + navigatorObservers: [ + PersonalizationScreenObserver( + shopId: demoShopId, + screenName: demoScreenName, + ), + ], + home: const _ShopHome(), + ); + } +} + +/// Initializes the demo shop, then is its home; the game's link opens the game over +/// the shop, a stories link the campaign. +class _ShopHome extends StatefulWidget { + const _ShopHome(); + + @override + State<_ShopHome> createState() => _ShopHomeState(); +} + +class _ShopHomeState extends State<_ShopHome> { + late final PersonalizationSdk _sdk; + + @override + void initState() { + super.initState(); + // Registers the shop and sends the native init before the shop's first request. + final sdk = _sdk = initializeDemoShop(); + enableDemoPopupsV3( + sdk, + // A product of a popup opens in the shop, and the popup goes. + onProductClick: (product) { + if (!mounted) return false; + ShopProductScreen.open(context, demoShopId, product.id); + return true; + }, + ); + sdk.popups.screenOpened(DemoScreens.home); + WidgetsBinding.instance.addPostFrameCallback((_) { + requestDemoNotificationPermission(); + }); + // Links of the demo scheme, the one of a cold start included. + DemoLinks.listen(_openLink); + } + + @override + void dispose() { + DemoLinks.cancel(); + // The handler holds this screen; a new one sets its own. + _sdk.popups.onProductClick = null; + super.dispose(); + } + + void _openLink(String url) { + if (!mounted || openDemoGameLink(url)) return; + if (!openShopStoriesLink(context, url, demoShopId)) { + debugPrint('Demo: neither the game nor a stories link — $url'); + } + } + + @override + Widget build(BuildContext context) => const ShopPane(shopId: demoShopId); +} diff --git a/example/lib/shop/shop.dart b/example/lib/shop/shop.dart new file mode 100644 index 0000000..6dd776d --- /dev/null +++ b/example/lib/shop/shop.dart @@ -0,0 +1,261 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_svg/flutter_svg.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +/// The recommender block the demo shop serves (api.rees46.ru) that has products: +/// "Популярные" on home and under a product. +const String shopRecommenderCode = 'e6249bb15043644bf25b135006149962'; + +/// Product page blocks driven by the product (`itemId`): "Похожие" and +/// "С этим товаром также покупают". +const String shopSimilarCode = '007b87897f244b2a2a123567b3242a4b'; +const String shopAlsoBoughtCode = 'fa6e8cd83434273dd8d47293329e00dd'; + +/// The Stories V2 block the demo shop serves (API v3): one campaign with a poll of every +/// kind on its slides. +const String shopStoriesCode = '272dd914ea13824a0abb6ef4e776ddaa'; + +/// Label of every "add to cart" button of the shop. +const String shopAddToCartText = 'Add to cart'; + +/// Shown in place of data that did not load, above a Retry button. +const String shopErrorText = + 'Something went wrong. Check your connection and try again.'; + +const String shopRetryText = 'Retry'; + +/// Toast of a promo code a story copied. +const String shopPromoCopiedText = 'Code copied'; + +/// "Add to cart" of the demo shop. There is no cart screen: the kit's toast confirms +/// the tap and the event goes to tracking, whose failure only reaches the log — as in +/// the native demos. A recommender block has already remembered itself as the source +/// when its button was pressed, so the event is attributed to the block. +Future addToShopCart( + BuildContext context, + String shopId, + String itemId, { + double? price, +}) async { + PersonalizationToast.show(context, 'Added to cart'); + try { + await REES46 + .getInstance(shopId) + .tracking + .addToCart(TrackingItem(id: itemId, price: price)); + } catch (error) { + debugPrint('Shop: add to cart not tracked — $error'); + } +} + +/// Text style of the kit: a step of its scale in a colour of its palette, with the +/// font family the kit's theme sets for that weight. +TextStyle shopTextStyle(BuildContext context, TextStyle step, Color color) { + final family = PersonalizationTheme.of(context).fontFamily; + return step.copyWith( + color: color, + fontFamily: family.familyFor(step.fontWeight ?? FontWeight.w400), + package: family.package, + ); +} + +/// A screen of the shop: the kit's generic background and no app bar — the content +/// starts under the status bar, whose icons follow the kit's scheme: dark on the light +/// one, light on the dark one. What scrolls up goes under a shade of the background +/// behind the status bar instead of under its icons. +class ShopScaffold extends StatelessWidget { + const ShopScaffold({super.key, required this.body, this.shadeStatusBar}); + + final Widget body; + + /// When the shade is on; `null` — always. The product page turns it on only once + /// its photo's card is gone from under the status bar. + final ValueListenable? shadeStatusBar; + + static const Duration _shadeFade = Duration(milliseconds: 150); + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + final dark = PersonalizationTheme.brightnessOf(context) == Brightness.dark; + final shade = ColoredBox(color: colors.backgroundGeneric); + final toggle = shadeStatusBar; + return AnnotatedRegion( + value: SystemUiOverlayStyle( + statusBarColor: colors.backgroundTransparent, + // iOS takes the brightness of what is under the bar, Android of its icons. + statusBarBrightness: dark ? Brightness.dark : Brightness.light, + statusBarIconBrightness: dark ? Brightness.light : Brightness.dark, + ), + child: Scaffold( + backgroundColor: colors.backgroundGeneric, + body: Stack( + children: [ + Positioned.fill(child: body), + Positioned( + top: 0, + left: 0, + right: 0, + height: MediaQuery.paddingOf(context).top, + child: IgnorePointer( + child: toggle == null + ? shade + : ValueListenableBuilder( + valueListenable: toggle, + builder: (context, on, child) => AnimatedOpacity( + opacity: on ? 1 : 0, + duration: _shadeFade, + child: child, + ), + child: shade, + ), + ), + ), + ], + ), + ), + ); + } +} + +/// A kit results screen (category, search) as a screen of the shop: its title 8 under +/// the status bar, where the shop's own screens start. The screen's feed pads itself +/// by 16, so the screen goes up by the difference; the bottom keeps clear of the home +/// indicator. +class ShopResultsPage extends StatelessWidget { + const ShopResultsPage({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + final top = MediaQuery.paddingOf(context).top; + return Padding( + padding: EdgeInsets.only( + top: math.max( + 0, + top + PersonalizationSpacing.md - PersonalizationSpacing.xl, + ), + ), + child: MediaQuery.removePadding( + context: context, + removeTop: true, + child: SafeArea(top: false, child: child), + ), + ); + } +} + +/// A round icon button of the shop's screens without a bar: one of the kit's icons on +/// [background] — the kit's card unless given. +class ShopRoundButton extends StatelessWidget { + const ShopRoundButton({ + super.key, + required this.icon, + required this.label, + required this.onPressed, + this.background, + this.mirrored = false, + }); + + /// The kit's icon asset ([PersonalizationIcons]). + final String icon; + + /// What a screen reader calls the button. + final String label; + + final VoidCallback onPressed; + final Color? background; + + /// Flipped left to right: the kit draws its chevron to the right only. + final bool mirrored; + + /// A touch target of the platforms' minimum. + static const double size = 44; + + static const double _iconSize = 24; + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + return Semantics( + button: true, + label: label, + excludeSemantics: true, + child: GestureDetector( + onTap: onPressed, + child: Container( + width: size, + height: size, + alignment: Alignment.center, + decoration: BoxDecoration( + color: background ?? colors.backgroundCard, + shape: BoxShape.circle, + ), + child: Transform.flip( + flipX: mirrored, + child: shopIcon(context, icon, _iconSize, colors.textPrimary), + ), + ), + ), + ); + } +} + +/// Back of a screen without a bar: the round button on the kit's generic background +/// with the kit's chevron turned to the left. +class ShopBackButton extends StatelessWidget { + const ShopBackButton({super.key}); + + @override + Widget build(BuildContext context) { + return ShopRoundButton( + icon: PersonalizationIcons.angleLargeRight, + mirrored: true, + label: 'Back', + background: PersonalizationTheme.of(context).colors.backgroundGeneric, + onPressed: () => Navigator.of(context).maybePop(), + ); + } +} + +/// Data that did not load: the kit's empty state with [shopErrorText] and a Retry +/// button under it — the way the kit's catalog shows a failed first page. +class ShopRetry extends StatelessWidget { + const ShopRetry({super.key, required this.onRetry}); + + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const PersonalizationEmptyState(message: shopErrorText), + PersonalizationButton( + label: shopRetryText, + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.secondary, + iconStart: PersonalizationIcons.arrowRotateCw, + iconBuilder: shopIcon, + onPressed: onRetry, + ), + ], + ); + } +} + +/// The kit hands over the asset and the colour it wants; the host picks the renderer. +Widget shopIcon(BuildContext context, String asset, double size, Color color) { + return SvgPicture.asset( + asset, + width: size, + height: size, + colorFilter: ColorFilter.mode(color, BlendMode.srcIn), + ); +} diff --git a/example/lib/shop/shop_category.dart b/example/lib/shop/shop_category.dart new file mode 100644 index 0000000..4151180 --- /dev/null +++ b/example/lib/shop/shop_category.dart @@ -0,0 +1,88 @@ +import 'package:flutter/material.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +import '../demo_app.dart'; +import 'shop.dart'; +import 'shop_facets.dart'; +import 'shop_product.dart'; +import 'shop_sort.dart'; + +/// Category screen of the demo shop: the kit's category screen as it is — the search +/// is on home. The kit loads, pages, filters and tracks the category view itself; its +/// back button walks the shop's stack, "Add to cart" sends the cart event with a toast. The sort comes from the shop's picker — on Flutter the kit +/// keeps the sort button hidden until the native SDKs sort a category. +class ShopCategoryScreen extends StatefulWidget { + const ShopCategoryScreen({ + super.key, + required this.shopId, + required this.categoryId, + required this.name, + }); + + final String shopId; + final String categoryId; + + /// The title: the category response carries no name, the list it was picked + /// from does. + final String name; + + /// Opens the category on top of the current screen. + static void open( + BuildContext context, + String shopId, + String categoryId, + String name, + ) { + Navigator.of(context).push( + MaterialPageRoute( + settings: const RouteSettings(name: DemoScreens.category), + builder: (_) => ShopCategoryScreen( + shopId: shopId, + categoryId: categoryId, + name: name, + ), + ), + ); + } + + @override + State createState() => _ShopCategoryScreenState(); +} + +class _ShopCategoryScreenState extends State { + ShopSort _sort = ShopSort.relevance; + + Future _pickSort() async { + final sort = await pickShopSort(context, _sort); + if (sort != null && mounted) setState(() => _sort = sort); + } + + @override + Widget build(BuildContext context) { + final shopId = widget.shopId; + return ShopScaffold( + body: ShopResultsPage( + child: PersonalizationCategoryScreen( + shopId: shopId, + categoryId: widget.categoryId, + titleText: widget.name, + sortBy: _sort.sortBy, + sortDir: _sort.sortDir, + productActionText: shopAddToCartText, + emptyText: 'No products in this category yet.', + errorText: shopErrorText, + retryText: shopRetryText, + onBack: () => Navigator.of(context).maybePop(), + onSortTap: _pickSort, + onProductTap: (product) => + ShopProductScreen.open(context, shopId, product.id), + onProductAction: (product) => + addToShopCart(context, shopId, product.id, price: product.price), + facetTitle: shopFacetTitle, + facetValueTitle: shopFacetValueTitle, + iconBuilder: shopIcon, + ), + ), + ); + } +} diff --git a/example/lib/shop/shop_facets.dart b/example/lib/shop/shop_facets.dart new file mode 100644 index 0000000..a395f35 --- /dev/null +++ b/example/lib/shop/shop_facets.dart @@ -0,0 +1,21 @@ +/// Filter labels of the demo shop's feed — what an integrator sets up for their own +/// feed. The kit knows only the shape of the data; facet names and their values are the +/// shop's own, so the shop names them. +library; + +/// Titles of the shop's facets; `null` — the kit's default title. +String? shopFacetTitle(String name) => switch (name) { + 'stickers' || 'stickers_liquid' => 'Стикеры', + 'product_type' => 'Тип товара', + _ => null, +}; + +/// Labels of the values of the shop's facets; `null` — the kit's label (the `title` of +/// an object value, else the value itself). +String? shopFacetValueTitle(String facet, String value) => + switch ((facet, value)) { + ('product_type', 'regular') => 'Обычный', + ('product_type', 'digital') => 'Цифровой', + ('product_type', 'mto') => 'Под заказ', + _ => null, + }; diff --git a/example/lib/shop/shop_home.dart b/example/lib/shop/shop_home.dart new file mode 100644 index 0000000..e3c8f46 --- /dev/null +++ b/example/lib/shop/shop_home.dart @@ -0,0 +1,357 @@ +import 'package:flutter/material.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +// v3 (popups of the new builder, stories over API v3) is not public API; its gate is +// lifted when v3 goes public. The example reaches it directly, which the analyzer +// flags as an implementation import on purpose. +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; + +import '../demo_app.dart'; +import 'shop.dart'; +import 'shop_category.dart'; +import 'shop_product.dart'; +import 'shop_products.dart'; +import 'shop_search_field.dart'; + +/// "Shop" — a demo shop built from the kit and the public SDK methods: the way a +/// host would integrate them. It is the home of the "Shop" tab (see `DemoTabs`) and +/// the whole app of `main_shop.dart`. +/// Home has its header with the popups menu and the search button, the stories bar, +/// the recommender block and the top-level categories; the search button turns home +/// into the instant search. From there the category, product and search screens go on +/// the tab's own navigator, so they open under the tab bar and back walks them in +/// reverse. No screen of the shop has an app bar: each starts under the status bar. +/// "Add to cart" sends the cart event and shows a toast — there is no cart screen. +/// +/// The Android, iOS and React Native demos build the same shop. +class ShopPane extends StatefulWidget { + const ShopPane({super.key, required this.shopId}); + + final String shopId; + + @override + State createState() => _ShopPaneState(); +} + +/// Height of a row of the categories group. +const double _categoryRowHeight = 52; + +class _ShopPaneState extends State { + /// Top-level categories; `null` while they load. + List? _categories; + Object? _categoriesError; + + /// Products of the recommender block: hidden, it takes no room, so its gap goes too. + int _popularCount = 0; + + @override + void initState() { + super.initState(); + _loadCategories(); + } + + Future _loadCategories() async { + try { + // The listing is only read for its categories, which come with it whatever + // the page size: a few products are enough. + final response = await REES46 + .getInstance(widget.shopId) + .getProductsList(params: const ProductsListParams(limit: 10)); + if (mounted) setState(() => _categories = shopTopCategories(response)); + } catch (error) { + if (mounted) setState(() => _categoriesError = error); + } + } + + void _retryCategories() { + setState(() => _categoriesError = null); + _loadCategories(); + } + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + final safe = MediaQuery.paddingOf(context); + return ShopScaffold( + // Search mode puts the field in place of the header and the panel under it. + body: ShopSearchField( + shopId: widget.shopId, + builder: (context, field, searching, search) => SingleChildScrollView( + padding: EdgeInsets.only( + top: safe.top + PersonalizationSpacing.md, + bottom: safe.bottom + PersonalizationSpacing.xl4, + ), + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: PersonalizationSpacing.paddingX, + ), + child: searching + ? field + : Row( + children: [ + Expanded( + child: Text( + 'Shop', + style: shopTextStyle( + context, + PersonalizationTypography.xl3Emphasized, + colors.textPrimary, + ), + ), + ), + _ShopPopupsMenu(shopId: widget.shopId), + const SizedBox(width: PersonalizationSpacing.md), + ShopRoundButton( + icon: PersonalizationIcons.magnifier, + label: 'Search', + onPressed: search, + ), + ], + ), + ), + // Offstage, not removed: the stories and the block keep what they loaded. + Offstage(offstage: searching, child: _home(context)), + ], + ), + ), + ), + ); + } + + Widget _home(BuildContext context) { + final shopId = widget.shopId; + const side = EdgeInsets.symmetric( + horizontal: PersonalizationSpacing.paddingX, + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: PersonalizationSpacing.lg), + // Collapses when the block is empty or fails. The bar runs edge to edge, its + // covers start at the page's margin. A product of a story closes the viewer + // and opens here. Over API v3: slides with a link have "Share", and the link + // goes out in the demo scheme, which opens the campaign in the app. A button's + // link to the game opens the game here. + PersonalizationStoriesV3( + apiV3Domain: demoStoriesApiV3Domain, + shareUrlTransform: demoShareUrl, + child: PersonalizationStories( + code: shopStoriesCode, + shopId: shopId, + padding: side, + promoCopiedText: shopPromoCopiedText, + onLinkClick: demoStoriesLinkClick(shopId), + onProductClick: (product) => + ShopProductScreen.open(context, shopId, product.id), + iconBuilder: shopIcon, + ), + ), + if (_popularCount > 0) + const SizedBox(height: PersonalizationSpacing.xl3), + // Title from the response; hidden until its products arrive. The card button + // remembers the block as the source before the cart event goes out. + Padding( + padding: side, + child: PersonalizationRecommenderBlock( + code: shopRecommenderCode, + shopId: shopId, + actionText: shopAddToCartText, + onLoaded: (count) { + if (mounted && _popularCount != count) { + setState(() => _popularCount = count); + } + }, + onProductTap: (product) => + ShopProductScreen.open(context, shopId, product.id), + onProductAction: (product) => + addToShopCart(context, shopId, product.id), + iconBuilder: shopIcon, + ), + ), + Padding(padding: side, child: _categoriesSection(context)), + ], + ); + } + + /// "Categories": the kit's title over a group of rows. Hidden whole while there + /// are none; a failure shows the shop's retry in place of the group. + Widget _categoriesSection(BuildContext context) { + final categories = _categories; + final Widget content; + if (_categoriesError != null) { + content = ShopRetry(onRetry: _retryCategories); + } else if (categories == null) { + content = const Center(child: PersonalizationLoader()); + } else if (categories.isEmpty) { + return const SizedBox.shrink(); + } else { + content = _ShopCategoryGroup( + shopId: widget.shopId, + categories: categories, + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: PersonalizationSpacing.xl3), + // The same title as the recommender block's. + const PersonalizationTitle(title: 'Categories'), + const SizedBox(height: PersonalizationSpacing.lg), + content, + ], + ); + } +} + +/// "Show popup" of the header: a menu of the demo's popups v3 ([demoManualPopups]) on +/// the kit's floating surface, under the button and level with its right edge. The +/// picked one is shown by hand — no trigger, screens or frequency, and with the +/// automatic presentation off too. +class _ShopPopupsMenu extends StatelessWidget { + const _ShopPopupsMenu({required this.shopId}); + + final String shopId; + + /// The menu's surface over the page. + static const double _elevation = 8; + + Future _open(BuildContext context) async { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final button = context.findRenderObject()! as RenderBox; + final overlay = + Navigator.of(context).overlay!.context.findRenderObject()! as RenderBox; + final left = button.localToGlobal(Offset.zero, ancestor: overlay).dx; + final top = + button + .localToGlobal( + button.size.bottomLeft(Offset.zero), + ancestor: overlay, + ) + .dy + + PersonalizationSpacing.md; + // A line under the button: the menu opens below it, on the side with more room. + final under = Rect.fromLTWH(left, top, button.size.width, 0); + final id = await showMenu( + context: context, + position: RelativeRect.fromRect(under, Offset.zero & overlay.size), + color: colors.backgroundFloat, + shadowColor: colors.shadowHeavy, + elevation: _elevation, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(theme.radius.xl2), + ), + items: [ + for (final popup in demoManualPopups) + PopupMenuItem( + value: popup.id, + child: Text( + popup.label, + style: shopTextStyle( + context, + PersonalizationTypography.baseDefault, + colors.textPrimary, + ), + ), + ), + ], + ); + if (id == null) return; + try { + await REES46.getInstance(shopId).popups.show(id); + } catch (error) { + debugPrint('Shop: popup $id not shown — $error'); + } + } + + @override + Widget build(BuildContext context) { + return ShopRoundButton( + icon: PersonalizationIcons.rosette, + label: 'Show popup', + onPressed: () => _open(context), + ); + } +} + +/// Categories as one group on the kit's card: the kit's category rows, a hairline +/// between them, the whole row opens its category. +class _ShopCategoryGroup extends StatelessWidget { + const _ShopCategoryGroup({required this.shopId, required this.categories}); + + final String shopId; + final List categories; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + return ClipRRect( + borderRadius: BorderRadius.circular(theme.radius.card), + child: ColoredBox( + color: colors.backgroundCard, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final (index, category) in categories.indexed) ...[ + if (index > 0) + SizedBox( + height: 1, + child: ColoredBox(color: colors.lineGenericSubtle), + ), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => ShopCategoryScreen.open( + context, + shopId, + category.id, + category.name, + ), + child: ConstrainedBox( + constraints: const BoxConstraints( + minHeight: _categoryRowHeight, + ), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: PersonalizationSpacing.paddingX, + ), + child: Center( + child: PersonalizationSuggestionRow( + kind: PersonalizationSuggestionKind.category, + title: category.name, + iconBuilder: shopIcon, + ), + ), + ), + ), + ), + ], + ], + ), + ), + ); + } +} + +/// Opens a stories "Share" link over the shop, as its home stories would: over API v3, +/// a story's product opens on the product page, a button's link to the game the game. +/// `false` — not a stories link. +bool openShopStoriesLink(BuildContext context, String url, String shopId) => + PersonalizationStoriesV3.handleLink( + context, + url, + shopId: shopId, + promoCopiedText: shopPromoCopiedText, + onLinkClick: demoStoriesLinkClick(shopId), + onProductClick: (product) => + ShopProductScreen.open(context, shopId, product.id), + onError: (error) => + PersonalizationToast.show(context, 'Stories link error: $error'), + iconBuilder: shopIcon, + apiV3Domain: demoStoriesApiV3Domain, + shareUrlTransform: demoShareUrl, + ); diff --git a/example/lib/shop/shop_product.dart b/example/lib/shop/shop_product.dart new file mode 100644 index 0000000..5145341 --- /dev/null +++ b/example/lib/shop/shop_product.dart @@ -0,0 +1,399 @@ +import 'package:flutter/material.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +import '../demo_app.dart'; +import 'shop.dart'; +import 'shop_products.dart'; + +/// Product screen of the demo shop, put together from the kit's pieces: `getProductInfo`, +/// the product view sent to tracking once per opening, and recommender blocks for this +/// product (`itemId`) — similar, bought with it and popular, each titled by the server +/// and hidden while it has no products. On top the photo's card runs under the status +/// bar with a round back button over it; "Add to cart" is pinned at the bottom with the +/// price. No search and no app bar here. +class ShopProductScreen extends StatefulWidget { + const ShopProductScreen({ + super.key, + required this.shopId, + required this.productId, + }); + + final String shopId; + final String productId; + + /// Opens the product on top of the current screen. + static void open(BuildContext context, String shopId, String productId) { + Navigator.of(context).push(route(shopId, productId)); + } + + /// The product's page, for a navigator not reached through a context. + static Route route(String shopId, String productId) => + MaterialPageRoute( + settings: const RouteSettings(name: DemoScreens.product), + builder: (_) => ShopProductScreen(shopId: shopId, productId: productId), + ); + + @override + State createState() => _ShopProductScreenState(); +} + +const List _productBlocks = [ + shopSimilarCode, + shopAlsoBoughtCode, + shopRecommenderCode, +]; + +class _ShopProductScreenState extends State { + Product? _product; + Object? _error; + + final ScrollController _scroll = ScrollController(); + final GlobalKey _hero = GlobalKey(); + + /// The photo's card has scrolled out from under the status bar: the page shades it. + final ValueNotifier _shadeStatusBar = ValueNotifier(false); + double _statusBar = 0; + double? _heroHeight; + + /// Products each block shows: a hidden block takes no room, so its gap goes too. + final Map _blockCounts = {}; + + @override + void initState() { + super.initState(); + _scroll.addListener(_onScroll); + _trackView(); + _load(); + } + + @override + void dispose() { + _scroll.dispose(); + _shadeStatusBar.dispose(); + super.dispose(); + } + + void _onScroll() { + // The list drops the card once it is far out of view: its last height stands. + final hero = _heroHeight = + _hero.currentContext?.size?.height ?? _heroHeight; + _shadeStatusBar.value = hero != null && _scroll.offset > hero - _statusBar; + } + + /// Once per opening, not per retry. The source a block or the search remembered + /// on the way here rides on this event. + Future _trackView() async { + try { + await REES46 + .getInstance(widget.shopId) + .tracking + .productView(widget.productId); + } catch (error) { + debugPrint('Shop: product view not tracked — $error'); + } + } + + Future _load() async { + try { + final product = await REES46 + .getInstance(widget.shopId) + .getProductInfo(widget.productId); + if (mounted) setState(() => _product = product); + } catch (error) { + if (mounted) setState(() => _error = error); + } + } + + void _retry() { + setState(() => _error = null); + _load(); + } + + @override + Widget build(BuildContext context) { + final product = _product; + _statusBar = MediaQuery.paddingOf(context).top; + return ShopScaffold( + shadeStatusBar: _shadeStatusBar, + body: product != null + ? _details(context, product) + : Stack( + children: [ + Positioned.fill( + child: Center( + child: _error != null + ? SingleChildScrollView( + padding: const EdgeInsets.all( + PersonalizationSpacing.paddingX, + ), + child: ShopRetry(onRetry: _retry), + ) + : const PersonalizationLoader(), + ), + ), + // There is no bar to go back with, loaded or not. + const _ShopProductBack(), + ], + ), + ); + } + + Widget _details(BuildContext context, Product product) { + final card = shopCard(product); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: ListView( + controller: _scroll, + // From the very top: the photo's card goes under the status bar. + padding: const EdgeInsets.only(bottom: PersonalizationSpacing.xl3), + children: [ + _ShopProductHero(key: _hero, product: product, card: card), + // Each block is hidden until its products arrive, and stays hidden + // when there are none. + for (final String code in _productBlocks) ...[ + if ((_blockCounts[code] ?? 0) > 0) + const SizedBox(height: PersonalizationSpacing.xl3), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: PersonalizationSpacing.paddingX, + ), + child: PersonalizationRecommenderBlock( + key: ValueKey(code), + code: code, + itemId: widget.productId, + shopId: widget.shopId, + actionText: shopAddToCartText, + onLoaded: (count) { + if (mounted && _blockCounts[code] != count) { + setState(() => _blockCounts[code] = count); + } + }, + onProductTap: (item) => + ShopProductScreen.open(context, widget.shopId, item.id), + onProductAction: (item) => + addToShopCart(context, widget.shopId, item.id), + iconBuilder: shopIcon, + ), + ), + ], + ], + ), + ), + _ShopBuyBar( + card: card, + onAddToCart: () => addToShopCart( + context, + widget.shopId, + widget.productId, + price: product.price, + ), + ), + ], + ); + } +} + +/// Top of the product page: the photo, the brand, the name and the price on the kit's +/// card, which runs under the status bar and rounds off at the bottom. The back button +/// is over its top and scrolls away with it; the system's back is still there. +class _ShopProductHero extends StatelessWidget { + const _ShopProductHero({ + super.key, + required this.product, + required this.card, + }); + + final Product product; + final PersonalizationProduct card; + + /// Margin of the photo's square on either side. + static const double _photoSide = PersonalizationSpacing.xl4; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + // The page shows the full image; `picture` is the copy resized for lists. + final image = product.imageUrl.isNotEmpty + ? product.imageUrl + : (product.picture ?? ''); + final hero = DecoratedBox( + decoration: BoxDecoration( + color: colors.backgroundCard, + borderRadius: BorderRadius.vertical( + bottom: Radius.circular(theme.radius.modal), + ), + ), + child: Padding( + padding: EdgeInsets.only( + top: MediaQuery.paddingOf(context).top + PersonalizationSpacing.md, + bottom: PersonalizationSpacing.xl2, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // A square of the screen's width less the margins, the photo fitted + // whole into it. + Padding( + padding: const EdgeInsets.symmetric(horizontal: _photoSide), + child: AspectRatio( + aspectRatio: 1, + child: image.isEmpty + ? null + : Image( + image: NetworkImage(image), + fit: BoxFit.contain, + errorBuilder: (_, _, _) => const SizedBox.shrink(), + ), + ), + ), + // 8 under the photo's square and 8 over the text. + const SizedBox(height: PersonalizationSpacing.xl), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: PersonalizationSpacing.xl2, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (card.brand != null) ...[ + Text( + card.brand!, + style: shopTextStyle( + context, + PersonalizationTypography.smDefault, + colors.textSecondary, + ), + ), + const SizedBox(height: PersonalizationSpacing.sm), + ], + Text( + card.name, + style: shopTextStyle( + context, + PersonalizationTypography.xlEmphasized, + colors.textPrimary, + ), + ), + const SizedBox(height: PersonalizationSpacing.lg), + Wrap( + spacing: PersonalizationSpacing.md, + runSpacing: PersonalizationSpacing.sm, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + card.price, + style: shopTextStyle( + context, + PersonalizationTypography.xl2Emphasized, + colors.textPrimary, + ), + ), + if (card.oldPrice != null) + Text( + card.oldPrice!, + style: shopTextStyle( + context, + PersonalizationTypography.baseDefault, + colors.textSecondary, + ).copyWith(decoration: TextDecoration.lineThrough), + ), + if (card.discount != null) + PersonalizationBadge( + label: card.discount!, + size: PersonalizationBadgeSize.md, + view: PersonalizationBadgeView.danger, + ), + ], + ), + ], + ), + ), + ], + ), + ), + ); + return Stack(children: [hero, const _ShopProductBack()]); + } +} + +/// The product page's back: over the top left corner, under the status bar. +class _ShopProductBack extends StatelessWidget { + const _ShopProductBack(); + + @override + Widget build(BuildContext context) { + final safe = MediaQuery.paddingOf(context); + return Positioned( + top: safe.top, + left: safe.left + PersonalizationSpacing.paddingX, + child: const ShopBackButton(), + ); + } +} + +/// The pinned bottom of the product page: the price (and the old one) and the kit's +/// "Add to cart" across the rest of the width, on the kit's card over a hairline. +/// Clear of the home indicator; in the full demo it sits on the tab bar. +class _ShopBuyBar extends StatelessWidget { + const _ShopBuyBar({required this.card, required this.onAddToCart}); + + final PersonalizationProduct card; + final VoidCallback onAddToCart; + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + return DecoratedBox( + decoration: BoxDecoration( + color: colors.backgroundCard, + border: Border(top: BorderSide(color: colors.lineGenericSubtle)), + ), + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: PersonalizationSpacing.paddingX, + vertical: PersonalizationSpacing.lg, + ), + child: Row( + children: [ + Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + card.price, + style: shopTextStyle( + context, + PersonalizationTypography.lgEmphasized, + colors.textPrimary, + ), + ), + if (card.oldPrice != null) + Text( + card.oldPrice!, + style: shopTextStyle( + context, + PersonalizationTypography.smDefault, + colors.textSecondary, + ).copyWith(decoration: TextDecoration.lineThrough), + ), + ], + ), + const SizedBox(width: PersonalizationSpacing.xl), + Expanded( + child: PersonalizationButton( + label: shopAddToCartText, + onPressed: onAddToCart, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/example/lib/shop/shop_products.dart b/example/lib/shop/shop_products.dart new file mode 100644 index 0000000..f8eb66c --- /dev/null +++ b/example/lib/shop/shop_products.dart @@ -0,0 +1,72 @@ +import 'package:flutter/widgets.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +/// Card data of a catalog product (`getCategory`, `getProductInfo`). The kit's data +/// widgets map their products by the same rules, but keep that mapper to themselves, +/// so a host showing its own lists maps them like this: +/// - price: `price_formatted`, else "price currency"; +/// - old price: `oldprice_formatted`, only when `oldprice` is above the price; +/// - discount badge: only next to a shown old price and for a positive number — +/// `discount`, else `discount_percent`. The text is `discount_formatted` when the +/// number came from `discount` (that is what it is made of), else `"N%"`, +/// with exactly one "-" in front; +/// - image: `picture` (the resized copy), else `image_url`. +/// The API has no rating, so the card has none either. +PersonalizationProduct shopCard(Product product, {String? actionText}) { + final hasOldPrice = + (product.oldPrice ?? 0) > product.price && + (product.oldPriceFormatted ?? '').isNotEmpty; + final fromDiscount = (product.discount ?? 0) > 0; + final number = fromDiscount + ? product.discount + : ((product.discountPercent ?? 0) > 0 ? product.discountPercent : null); + String? discount; + if (hasOldPrice && number != null) { + final formatted = fromDiscount + ? (product.discountFormatted ?? '').trim() + : ''; + final text = formatted.isNotEmpty ? formatted : '$number%'; + discount = '-${text.replaceFirst(RegExp(r'^-+'), '')}'; + } + final price = product.priceFormatted ?? ''; + final picture = product.picture ?? ''; + final image = picture.isNotEmpty ? picture : product.imageUrl; + return PersonalizationProduct( + id: product.id, + name: product.name, + price: price.isNotEmpty + ? price + : '${product.price} ${product.currency}'.trim(), + image: image.isEmpty ? null : NetworkImage(image), + brand: product.brand.isEmpty ? null : product.brand, + oldPrice: hasOldPrice ? product.oldPriceFormatted : null, + discount: discount, + actionText: actionText, + url: product.url.isEmpty ? null : product.url, + ); +} + +/// Top-level categories (those without a parent) of a products listing, in the +/// order they come. The listing's own `categories` first; where a bridge does not +/// pass them yet (iOS until its next native release) they are collected from the +/// products: every product lists its whole category path, the top of it included. +List shopTopCategories(ProductsListResponse response) { + final listed = _topLevel(response.categories); + if (listed.isNotEmpty) return listed; + return _topLevel([ + for (final product in response.products) ...product.categories, + ]); +} + +/// Parentless categories with an id and a name, each once. +List _topLevel(Iterable categories) { + final seen = {}; + return [ + for (final category in categories) + if ((category.parentId ?? '').isEmpty && + category.id.isNotEmpty && + category.name.isNotEmpty && + seen.add(category.id)) + category, + ]; +} diff --git a/example/lib/shop/shop_search.dart b/example/lib/shop/shop_search.dart new file mode 100644 index 0000000..01036df --- /dev/null +++ b/example/lib/shop/shop_search.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +import '../demo_app.dart'; +import 'shop.dart'; +import 'shop_facets.dart'; +import 'shop_product.dart'; +import 'shop_sort.dart'; + +/// Search screen of the demo shop: the kit's results screen for [query]. It loads, +/// pages, filters and tracks the search itself; its back button returns home. +class ShopSearchScreen extends StatefulWidget { + const ShopSearchScreen({ + super.key, + required this.shopId, + required this.query, + }); + + final String shopId; + final String query; + + /// Opens the results on top of the current screen. + static void open(BuildContext context, String shopId, String query) { + Navigator.of(context).push( + MaterialPageRoute( + settings: const RouteSettings(name: DemoScreens.search), + builder: (_) => ShopSearchScreen(shopId: shopId, query: query), + ), + ); + } + + @override + State createState() => _ShopSearchScreenState(); +} + +class _ShopSearchScreenState extends State { + ShopSort _sort = ShopSort.relevance; + + /// There is no sort picker in the design file: the shop brings its own sheet. + Future _pickSort() async { + final sort = await pickShopSort(context, _sort); + if (sort != null && mounted) setState(() => _sort = sort); + } + + @override + Widget build(BuildContext context) { + return ShopScaffold( + body: ShopResultsPage( + child: PersonalizationSearchResultsScreen( + shopId: widget.shopId, + query: widget.query, + sortBy: _sort.sortBy, + sortDir: _sort.sortDir, + productActionText: shopAddToCartText, + onBack: () => Navigator.of(context).maybePop(), + onSortTap: _pickSort, + onProductTap: (product) => + ShopProductScreen.open(context, widget.shopId, product.id), + onProductAction: (product) => addToShopCart( + context, + widget.shopId, + product.id, + price: product.price, + ), + facetTitle: shopFacetTitle, + facetValueTitle: shopFacetValueTitle, + iconBuilder: shopIcon, + ), + ), + ); + } +} diff --git a/example/lib/shop/shop_search_field.dart b/example/lib/shop/shop_search_field.dart new file mode 100644 index 0000000..a74a1d1 --- /dev/null +++ b/example/lib/shop/shop_search_field.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +import 'shop.dart'; +import 'shop_category.dart'; +import 'shop_product.dart'; +import 'shop_search.dart'; + +/// The shop's instant search on its home, behind the search button of its header: the +/// button opens the search mode — the kit's field in place of the header, focused, with +/// Cancel, and the field's panel (recent searches, suggestions, categories, products) +/// under it while the rest of the page steps aside. Cancel or back closes it, back with +/// it open does not leave the screen. Submit opens the search results and closes the +/// mode, so back from them finds home as it was; a product of the panel opens its +/// product screen, a category of the panel its category screen. +class ShopSearchField extends StatefulWidget { + const ShopSearchField({ + super.key, + required this.shopId, + required this.builder, + }); + + final String shopId; + + /// Lays the screen out: [field] — the search field with its panel — while + /// [searching], else the screen with [search] behind its search button. While + /// searching the rest of the screen goes offstage, not away: it keeps what it + /// loaded. + final Widget Function( + BuildContext context, + Widget field, + bool searching, + VoidCallback search, + ) + builder; + + @override + State createState() => _ShopSearchFieldState(); +} + +class _ShopSearchFieldState extends State { + /// The search mode is on until Cancel. + bool _searching = false; + + /// Bumped on close: the next field starts with an empty query. + int _searchField = 0; + + /// Holds the field, to focus it: the kit's field keeps its focus node to itself. + final FocusScopeNode _scope = FocusScopeNode(debugLabel: 'Shop search'); + + @override + void dispose() { + _scope.dispose(); + super.dispose(); + } + + void _open() { + setState(() => _searching = true); + // The field is built in the next frame; its text input is the one to focus. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || !_searching) return; + for (final node in _scope.descendants) { + if (node.context?.findAncestorWidgetOfExactType() != + null) { + node.requestFocus(); + return; + } + } + }); + } + + void _close() { + FocusScope.of(context).unfocus(); + setState(() { + _searching = false; + _searchField++; + }); + } + + @override + Widget build(BuildContext context) { + final shopId = widget.shopId; + final field = FocusScope( + node: _scope, + child: PersonalizationInstantSearchField( + key: ValueKey(_searchField), + shopId: shopId, + placeholder: 'Search', + cancelText: 'Cancel', + recentLabel: 'Recent searches', + clearText: 'Clear', + moreText: 'more', + categoriesLabel: 'Categories', + productsLabel: 'Products', + onCancel: _close, + onSubmit: (query) { + _close(); + ShopSearchScreen.open(context, shopId, query); + }, + onProductTap: (product) => + ShopProductScreen.open(context, shopId, product.id), + onCategoryTap: (category) { + // Popular categories of the empty state come without an id. + final id = category.id; + if (id == null || id.isEmpty) return; + ShopCategoryScreen.open(context, shopId, id, category.name); + }, + iconBuilder: shopIcon, + ), + ); + return PopScope( + canPop: !_searching, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) _close(); + }, + child: widget.builder(context, field, _searching, _open), + ); + } +} diff --git a/example/lib/shop/shop_sort.dart b/example/lib/shop/shop_sort.dart new file mode 100644 index 0000000..9b28c4c --- /dev/null +++ b/example/lib/shop/shop_sort.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +import 'shop.dart'; + +/// A sort of the shop's results screens (search and category): what goes into the +/// screen's `sortBy` / `sortDir`. The kit draws no sort picker, the host brings one. +enum ShopSort { + relevance('Relevance', null, null), + priceAsc('Price: low to high', 'price', 'asc'), + priceDesc('Price: high to low', 'price', 'desc'), + discount('Discount', 'discount', 'desc'); + + const ShopSort(this.label, this.sortBy, this.sortDir); + + final String label; + + /// `null` — no sort: the server's relevance. + final String? sortBy; + final String? sortDir; +} + +/// Height of a row of the sort sheet. +const double _sortRowHeight = 52; + +/// The shop's sort picker, the same on both platforms: a bottom sheet on the kit's +/// modal surface, "Sort by" over the sorts, the current one checked; a tap picks and +/// closes. It covers the tab bar too. `null` — dismissed without a choice. +Future pickShopSort(BuildContext context, ShopSort current) { + final theme = PersonalizationTheme.of(context); + return showModalBottomSheet( + context: context, + useRootNavigator: true, + backgroundColor: theme.colors.backgroundModal, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.vertical( + top: Radius.circular(theme.radius.modal), + ), + ), + clipBehavior: Clip.antiAlias, + builder: (context) => _ShopSortSheet(current: current), + ); +} + +class _ShopSortSheet extends StatelessWidget { + const _ShopSortSheet({required this.current}); + + final ShopSort current; + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + const side = PersonalizationSpacing.paddingModal; + return SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: side), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: side), + child: Text( + 'Sort by', + style: shopTextStyle( + context, + PersonalizationTypography.lgEmphasized, + colors.textPrimary, + ), + ), + ), + const SizedBox(height: PersonalizationSpacing.md), + for (final sort in ShopSort.values) + Semantics( + button: true, + selected: sort == current, + child: InkWell( + onTap: () => Navigator.of(context).pop(sort), + child: ConstrainedBox( + constraints: const BoxConstraints( + minHeight: _sortRowHeight, + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: side), + child: Row( + children: [ + Expanded( + child: Text( + sort.label, + style: shopTextStyle( + context, + PersonalizationTypography.baseDefault, + colors.textPrimary, + ), + ), + ), + if (sort == current) + Icon(Icons.check, color: colors.brandPrimary), + ], + ), + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/example/lib/stories_polls_demo.dart b/example/lib/stories_polls_demo.dart new file mode 100644 index 0000000..8f995b9 --- /dev/null +++ b/example/lib/stories_polls_demo.dart @@ -0,0 +1,133 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +// v3 (popups of the new builder, stories over API v3) is not public API; its gate is +// lifted when v3 goes public. The example reaches it directly, which the analyzer +// flags as an implementation import on purpose. +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; + +import 'demo_app.dart'; + +/// "Stories V2 polls (offline)" of the UI Kit showcase: campaign 9001 of the shared poll +/// feed (`assets/uikit/stories_polls_feed.json` — every poll kind, an answered choice +/// with results and an unknown kind that is not drawn) in the V2 viewer over API v3, +/// with [DemoPollsTransport] instead of the network. Slide pictures still come from the +/// CDN. No SDK: nothing is tracked. +Future openStoriesPollsDemo( + BuildContext context, { + required Widget Function( + BuildContext context, + String asset, + double size, + Color color, + ) + iconBuilder, +}) async { + final json = + jsonDecode( + await rootBundle.loadString('assets/uikit/stories_polls_feed.json'), + ) + as Map; + final stories = StoriesBlock.fromJson( + json['payload'] as Map, + ).stories; + if (!context.mounted) return; + await Navigator.of(context, rootNavigator: true).push( + PersonalizationStoryViewer.route( + // API v3 mode turns the polls on; the transport keeps them offline. + PersonalizationStoriesV3( + apiV3Domain: demoStoriesApiV3Domain, + pollsTransport: DemoPollsTransport(stories), + child: PersonalizationStoryViewer( + stories: stories, + iconBuilder: iconBuilder, + ), + ), + ), + ); +} + +/// Poll answers without the network: each one takes [delay]. Mini polls with +/// `show_results` get results (the chosen options get more, 100 in total); the first +/// answer of `demo_text` fails, the next ones go through; scales always go through. +class DemoPollsTransport implements StoryPollsTransport { + DemoPollsTransport(List stories) + : _polls = { + for (final story in stories) + for (final slide in story.slides) + for (final element in slide.elements) + if (element is StoryPollElement) element.code: element, + }; + + static const Duration delay = Duration(milliseconds: 600); + + /// The code of the poll whose first answer fails. + static const String failingCode = 'demo_text'; + + final Map _polls; + bool _failed = false; + + @override + Future answerMiniPoll( + String code, + Map body, + ) async { + await Future.delayed(delay); + if (code == failingCode && !_failed) { + _failed = true; + throw StateError('demo: the first answer of "$code" fails'); + } + final ids = (body['option_ids'] as List?)?.cast(); + final text = body['text'] as String?; + final poll = _polls[code]; + return StoryPollReply( + answer: StoryPollAnswer(optionIds: ids, text: text), + results: + poll != null && + poll.showResults && + poll.options.isNotEmpty && + ids != null + ? _results(poll, ids.toSet()) + : null, + ); + } + + @override + Future review( + StoryPollType kind, + Map body, + ) async { + await Future.delayed(delay); + return const StoryPollReply(); + } + + /// A chosen option weighs 3, the others 1; percents add up to 100 (the rest of the + /// rounding goes to the first chosen one). + StoryPollResults _results(StoryPollElement poll, Set chosen) { + final weights = { + for (final option in poll.options) + option.id: chosen.contains(option.id) ? 3 : 1, + }; + final total = weights.values.fold(0, (sum, weight) => sum + weight); + final percents = { + for (final entry in weights.entries) + entry.key: entry.value * 100 ~/ total, + }; + final rest = + 100 - percents.values.fold(0, (sum, value) => sum + value); + final first = poll.options + .map((option) => option.id) + .firstWhere(chosen.contains, orElse: () => weights.keys.first); + percents[first] = percents[first]! + rest; + return StoryPollResults( + total: total * 10, + options: <({int id, double percent})>[ + for (final entry in percents.entries) + (id: entry.key, percent: entry.value.toDouble()), + ], + ); + } +} diff --git a/example/lib/ui_kit_pane.dart b/example/lib/ui_kit_pane.dart index 9cb0d06..6b7195c 100644 --- a/example/lib/ui_kit_pane.dart +++ b/example/lib/ui_kit_pane.dart @@ -4,23 +4,30 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +// v3 (popups of the new builder, stories over API v3) is not public API; its gate is +// lifted when v3 goes public. The example reaches it directly, which the analyzer +// flags as an implementation import on purpose. +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; import 'app_theme_mode.dart'; -// The kit stays out of the package barrel until its release; the example reaches -// it directly, which the analyzer flags as an implementation import on purpose. -// ignore: implementation_imports -import 'package:rees46_sdk/src/ui/personalization_ui.dart'; +import 'demo_app.dart'; +import 'stories_polls_demo.dart'; -/// "UI Kit" screen — the design system, one exhibit per component. +/// "UI Kit" tab (see `DemoTabs`) — the design system, one exhibit per component. /// /// "Components" walks through the primitives in every size, view and state the /// design file defines; "Blocks" shows the compositions built from them -/// (product cards, recommender layouts, instant search, the catalogue, the filters screen, -/// in-app popups, the toast, the loyalty card); +/// (the live recommender block of the demo shop, product cards, products blocks, +/// instant search, the catalogue, the filters screen, in-app popups, the toast, +/// the loyalty card); /// "Search" runs the two data-bound search widgets against the demo shop: the /// instant search field, and the results screen it opens on submit; /// "Stories" shows the Stories V2 components one by one, a sample viewer that runs -/// offline and the live stories block of the demo shop. +/// offline and the live stories block of the demo shop twice: on the old API, and on the +/// stories API v3 (its own `apiV3Domain`) with the "Share" button; a field opens a +/// "Share" link. /// Mirror of the Android `UiKitPane` / iOS `UIKitShowcaseViewController` / /// React Native `UiKitPane`. /// @@ -31,7 +38,8 @@ import 'package:rees46_sdk/src/ui/personalization_ui.dart'; class UiKitPane extends StatelessWidget { const UiKitPane({super.key, required this.shopId}); - /// Shop the Search and Stories tabs' widgets resolve their SDK instance by. + /// Shop the data-bound widgets of the Blocks, Search and Stories tabs resolve + /// their SDK instance by. final String shopId; @override @@ -54,7 +62,7 @@ class UiKitPane extends StatelessWidget { body: TabBarView( children: [ _Showcase(exhibits: _componentExhibits), - _Showcase(exhibits: _blockExhibits), + _Showcase(exhibits: _blockExhibits(shopId)), _SearchFlow(shopId: shopId), _Showcase(exhibits: _storyExhibits(shopId)), ], @@ -490,7 +498,24 @@ final List<_Exhibit> _componentExhibits = [ }), ]; -final List<_Exhibit> _blockExhibits = [ +List<_Exhibit> _blockExhibits(String shopId) => [ + _Exhibit( + 'Recommender Block — live block $_recommenderCode (demo shop), carousel; ' + 'Reload goes past the cache', + (context) => _LiveRecommender( + shopId: shopId, + layout: PersonalizationProductsLayout.carousel, + ), + ), + _Exhibit( + 'Recommender Block — the same code as a grid of four: one request serves ' + 'both blocks', + (context) => _LiveRecommender( + shopId: shopId, + layout: PersonalizationProductsLayout.grid, + limit: 4, + ), + ), _Exhibit('Product Card — carousel, grid, list', (context) { return _Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -537,22 +562,22 @@ final List<_Exhibit> _blockExhibits = [ ], ); }), - _Exhibit('Recommender Block — carousel', (context) { - return _recommender( + _Exhibit('Products Block — carousel, products from the host', (context) { + return _productsBlock( PersonalizationProductsLayout.carousel, 'Recommended for you', _products, ); }), - _Exhibit('Recommender Block — grid', (context) { - return _recommender( + _Exhibit('Products Block — grid, products from the host', (context) { + return _productsBlock( PersonalizationProductsLayout.grid, 'Similar products', _products.take(4).toList(), ); }), - _Exhibit('Recommender Block — list', (context) { - return _recommender( + _Exhibit('Products Block — list, products from the host', (context) { + return _productsBlock( PersonalizationProductsLayout.list, 'Recently viewed', _products.take(3).toList(), @@ -688,9 +713,117 @@ final List<_Exhibit> _blockExhibits = [ ), ]; -/// The Stories V2 block the demo shop serves (api.rees46.ru). +/// The recommender block the demo shop serves (api.rees46.ru). +const String _recommenderCode = 'e6249bb15043644bf25b135006149962'; + +/// A live [PersonalizationRecommenderBlock] of the demo shop with a caption of what it +/// reported: how many products it shows, or the error. The block takes no space +/// until its products arrive; "Reload" asks for them again past the cache. +class _LiveRecommender extends StatefulWidget { + const _LiveRecommender({ + required this.shopId, + required this.layout, + this.limit, + }); + + final String shopId; + final PersonalizationProductsLayout layout; + final int? limit; + + @override + State<_LiveRecommender> createState() => _LiveRecommenderState(); +} + +class _LiveRecommenderState extends State<_LiveRecommender> { + final PersonalizationRecommenderBlockController _controller = + PersonalizationRecommenderBlockController(); + String _status = 'Loading…'; + + void _report(String status) { + if (mounted) setState(() => _status = status); + } + + @override + Widget build(BuildContext context) { + final caption = Theme.of(context).textTheme.bodySmall; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded(child: Text(_status, style: caption)), + PersonalizationButton( + label: 'Reload', + size: PersonalizationButtonSize.sm, + view: PersonalizationButtonView.secondary, + onPressed: () { + _report('Reloading…'); + _controller.reload(); + }, + ), + ], + ), + const SizedBox(height: 8), + PersonalizationRecommenderBlock( + code: _recommenderCode, + shopId: widget.shopId, + controller: _controller, + layout: widget.layout, + limit: widget.limit, + actionText: 'Add to cart', + showAllText: 'Show all', + onShowAll: () => PersonalizationToast.show(context, 'Show all'), + onProductTap: (product) => PersonalizationToast.show( + context, + 'Product: ${product.name} — ${product.deeplink ?? product.url}', + ), + onProductAction: (product) => PersonalizationToast.show( + context, + 'Add to cart: ${product.name}', + ), + onLoaded: (count) => _report( + count == 0 + ? 'onLoaded(0): the block is hidden' + : 'onLoaded($count)', + ), + onError: (error) => _report('onError: $error'), + iconBuilder: _icon, + ), + ], + ); + } +} + +/// The Stories V2 block the demo shop serves. const String _storiesCode = '115bd0b67cf5989a1b60c841790b2af6'; +/// Opens a stories "Share" link over API v3 ([demoStoriesApiV3Domain]) — from the link +/// field and from the demo's deep links; a button's link to the game opens the game. +/// `false` — not a stories link (no `r46_stories`). +bool openStoriesLink( + BuildContext context, + String url, { + required String shopId, +}) => PersonalizationStoriesV3.handleLink( + context, + url, + shopId: shopId, + promoCopiedText: 'Code copied to clipboard', + onLinkClick: demoStoriesLinkClick(shopId), + onProductClick: (product) => + PersonalizationToast.show(context, 'Product: ${product.name}'), + onError: (error) => _snack(context, 'Stories link error: $error'), + iconBuilder: _icon, + shareUrlTransform: demoShareUrl, + apiV3Domain: demoStoriesApiV3Domain, +); + +/// A "Share" link of the live block: campaign 40 from its second slide (37). The link +/// field starts empty, so a pasted link is never mixed up with it; "Sample link" puts +/// it in. +const String _storiesSampleLink = + 'https://demo.rees46.ru/?r46_stories=$_storiesCode&r46_story=40&r46_slide=37'; + /// End of the timer exhibits: fixed on first use, so a rebuild does not restart them. final DateTime _timerEnd = DateTime.now().add( const Duration(days: 2, hours: 18, minutes: 33, seconds: 24), @@ -702,8 +835,9 @@ final PersonalizationStoriesController _storiesController = List<_Exhibit> _storyExhibits(String shopId) => [ _Exhibit( - 'Stories — live block $_storiesCode (demo shop); ' - 'links open in the system browser. Seen slides survive a restart.', + 'Stories V2 — live block $_storiesCode (demo shop) on the old API: no ' + '"Share" button; links open in the system browser. Seen slides survive a ' + 'restart.', (context) => PersonalizationStories( code: _storiesCode, shopId: shopId, @@ -717,7 +851,34 @@ List<_Exhibit> _storyExhibits(String shopId) => [ ), ), _Exhibit( - 'Stories — programmatic control: open the second story, pause and ' + 'Stories V2 with Sharing — the same block over API v3 ' + '($demoStoriesApiV3Domain): slides with a link have "Share" left of the cross; ' + 'the link is shared with the demo scheme ($demoLinkScheme://), which opens ' + 'the slide in this app', + (context) => PersonalizationStoriesV3( + apiV3Domain: demoStoriesApiV3Domain, + shareUrlTransform: demoShareUrl, + child: PersonalizationStories( + code: _storiesCode, + shopId: shopId, + padding: EdgeInsets.zero, + promoCopiedText: 'Code copied to clipboard', + onProductClick: (product) => + PersonalizationToast.show(context, 'Product: ${product.name}'), + onError: (error) => _snack(context, 'Stories error: $error'), + iconBuilder: _icon, + ), + ), + ), + _Exhibit( + 'Stories link — paste a "Share" link (https:// or $demoLinkScheme://) and open ' + 'it with PersonalizationStoriesV3.handleLink; "Sample link" fills in campaign 40 ' + 'from its second slide. Links in the $demoLinkScheme:// scheme open the app ' + 'too; App Links / Universal Links are not set up', + (context) => _StoriesLinkExhibit(shopId: shopId), + ), + _Exhibit( + 'Stories V2 — programmatic control of the first block: open the second story, pause and ' 'resume it after 3 s, reload the block, show the block without the bar', (context) => Wrap( spacing: 8, @@ -786,6 +947,19 @@ List<_Exhibit> _storyExhibits(String shopId) => [ ); }, ), + _Exhibit( + 'Stories V2 polls (offline) — every poll kind on its slide over API v3 with a fake ' + 'transport: answers take 0.6 s, the text poll fails once, choices get results', + (context) => Align( + alignment: Alignment.centerLeft, + child: PersonalizationButton( + key: const Key('stories-polls-open'), + label: 'Open', + size: PersonalizationButtonSize.sm, + onPressed: () => openStoriesPollsDemo(context, iconBuilder: _icon), + ), + ), + ), _Exhibit('Story Cover — default, pinned, viewed, skeleton', (context) { return _ScrollRow( children: [ @@ -1886,12 +2060,12 @@ Widget _card( ); } -Widget _recommender( +Widget _productsBlock( PersonalizationProductsLayout layout, String title, List products, ) { - return PersonalizationRecommenderBlock( + return PersonalizationProductsBlock( layout: layout, title: title, showAllText: 'Show all', @@ -2008,3 +2182,66 @@ extension on PersonalizationProduct { ); } } + +/// A "Share" link field: [PersonalizationStoriesV3.handleLink] opens the campaign of the +/// link over API v3 ([demoStoriesApiV3Domain]); `false` — not a stories link. +class _StoriesLinkExhibit extends StatefulWidget { + const _StoriesLinkExhibit({required this.shopId}); + + final String shopId; + + @override + State<_StoriesLinkExhibit> createState() => _StoriesLinkExhibitState(); +} + +class _StoriesLinkExhibitState extends State<_StoriesLinkExhibit> { + final TextEditingController _link = TextEditingController(); + + @override + void dispose() { + _link.dispose(); + super.dispose(); + } + + void _open() { + final handled = openStoriesLink(context, _link.text, shopId: widget.shopId); + if (!handled) _snack(context, 'Not a stories link'); + } + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + PersonalizationInputField( + key: const Key('stories-link-field'), + controller: _link, + type: PersonalizationInputFieldType.input, + size: PersonalizationInputFieldSize.md, + placeholder: 'Stories link', + onSubmitted: (_) => _open(), + iconBuilder: _icon, + ), + const SizedBox(height: 8), + Row( + children: [ + PersonalizationButton( + key: const Key('stories-link-open'), + label: 'Open', + size: PersonalizationButtonSize.sm, + onPressed: _open, + ), + const SizedBox(width: 8), + PersonalizationButton( + key: const Key('stories-link-sample'), + label: 'Sample link', + size: PersonalizationButtonSize.sm, + view: PersonalizationButtonView.secondary, + onPressed: () => _link.text = _storiesSampleLink, + ), + ], + ), + ], + ); + } +} diff --git a/example/pubspec.lock b/example/pubspec.lock index 2112ba7..5126221 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -341,7 +341,7 @@ packages: path: ".." relative: true source: path - version: "1.1.0" + version: "1.5.0" shared_preferences: dependency: transitive description: @@ -571,6 +571,38 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.0" + webview_flutter: + dependency: "direct main" + description: + name: webview_flutter + sha256: d53e1ccf5516f25017e3c9d44c39034db352d20fa34fe200674270242c2c5111 + url: "https://pub.dev" + source: hosted + version: "4.14.1" + webview_flutter_android: + dependency: transitive + description: + name: webview_flutter_android + sha256: ad5182eff9a550925330cb9f0cb038eddfdd5712aba8b77aa0f0400e50f6e688 + url: "https://pub.dev" + source: hosted + version: "4.12.0" + webview_flutter_platform_interface: + dependency: "direct dev" + description: + name: webview_flutter_platform_interface + sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04" + url: "https://pub.dev" + source: hosted + version: "2.15.1" + webview_flutter_wkwebview: + dependency: transitive + description: + name: webview_flutter_wkwebview + sha256: "82648217f537573e1ca9ae9952d3eacedca6ab5aee69dc84445fc763766dcea2" + url: "https://pub.dev" + source: hosted + version: "3.25.1" xdg_directories: dependency: transitive description: diff --git a/example/pubspec.yaml b/example/pubspec.yaml index a3b4990..00ceea4 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -32,6 +32,9 @@ dependencies: # The SDK ships its icons as SVG assets and leaves rendering to the host. flutter_svg: ^2.2.0 + # The demo's mini-game is a web page: the game's link opens it in a WebView. + webview_flutter: ^4.14.1 + dev_dependencies: integration_test: sdk: flutter @@ -45,6 +48,8 @@ dev_dependencies: # rules and activating additional ones. flutter_lints: ^6.0.0 patrol: ^4.5.0 + # A WebView of the tests' own: the game screen's page without a platform. + webview_flutter_platform_interface: ^2.15.1 patrol: app_name: rees46_sdk_example @@ -70,6 +75,8 @@ flutter: # demo-only: the SDK does not ship it. assets: - assets/uikit/ + # The mini-game: one web page, the same file in every demo. + - assets/game/ # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/to/resolution-aware-images diff --git a/example/test/demo_game_test.dart b/example/test/demo_game_test.dart new file mode 100644 index 0000000..b336d69 --- /dev/null +++ b/example/test/demo_game_test.dart @@ -0,0 +1,389 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; +import 'package:rees46_sdk_example/demo_app.dart'; +import 'package:rees46_sdk_example/game/game_screen.dart'; +import 'package:rees46_sdk_example/main_shop.dart'; +import 'package:rees46_sdk_example/shop/shop.dart'; +import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; + +void main() { + group('the game link', () { + test('is host game in the scheme of any demo', () { + for (final url in [ + 'rees46://game', + 'rees46flutter://game', + 'rees46rn://game', + 'REES46FLUTTER://GAME', + 'rees46flutter://game/', + 'rees46flutter://game/play?level=2', + ' rees46://game ', + ]) { + expect(isDemoGameLink(url), isTrue, reason: url); + expect(readDemoGameLink(url)!.page, isNull, reason: url); + } + }); + + test( + 'with r46_stories is a stories link, and other links are not the game', + () { + for (final url in [ + 'rees46flutter://game?r46_stories=c&r46_story=40', + 'rees46flutter://game/?url=https%3A%2F%2Fa.example&r46_stories=c', + 'rees46flutter://demo.rees46.ru/?r46_stories=c&r46_story=40&r46_slide=37', + 'rees46flutter://shop', + 'rees46flutter:game', + 'https://game', + 'https://demo.rees46.ru/game', + 'myapp://game', + '', + 'not a link', + ]) { + expect(isDemoGameLink(url), isFalse, reason: url); + } + }, + ); + + test('takes an https url as the page of a game of the app', () { + expect( + readDemoGameLink( + 'rees46://game?url=https%3A%2F%2Fgames.example.com%2Fttt%3Flevel%3D2', + )!.page, + Uri.parse('https://games.example.com/ttt?level=2'), + ); + expect( + readDemoGameLink( + 'rees46flutter://game?url=https://games.example.com/ttt', + )!.page, + Uri.parse('https://games.example.com/ttt'), + ); + }); + + test( + 'opens the built-in game for a url that is not https or is broken', + () { + for (final url in [ + 'rees46flutter://game?url=http%3A%2F%2Fgames.example.com', + 'rees46flutter://game?url=javascript%3Aalert(1)', + 'rees46flutter://game?url=file%3A%2F%2F%2Fetc%2Fhosts', + 'rees46flutter://game?url=https%3Agames.example.com', + 'rees46flutter://game?url=%FF', + 'rees46flutter://game?url=', + 'rees46flutter://game?url', + ]) { + final link = readDemoGameLink(url); + expect(link, isNotNull, reason: url); + expect(link!.page, isNull, reason: url); + } + }, + ); + }); + + group('the game screen', () { + late _FakeWebViewPlatform web; + + setUp(() => WebViewPlatform.instance = web = _FakeWebViewPlatform()); + + testWidgets('loads the built-in page and gives it the app theme', ( + tester, + ) async { + await tester.pumpWidget(_app()); + expect(openDemoGameLink('rees46flutter://game'), isTrue); + await _settle(tester); + + expect(find.text(DemoGameScreen.title), findsOneWidget); + final page = web.controllers.single; + expect(page.asset, demoGameAsset); + expect(page.request, isNull); + expect(page.javaScriptMode, JavaScriptMode.unrestricted); + expect( + page.background, + PersonalizationTheme.light.colors.backgroundGeneric, + ); + // Covered until the page has the theme, so it does not flash in the wrong one. + expect(find.byType(PersonalizationLoader), findsOneWidget); + + page.finish(); + await tester.pump(); + await tester.pump(); + expect(page.scripts, [ + "window.setGameTheme && window.setGameTheme('light')", + ]); + expect(find.byType(PersonalizationLoader), findsNothing); + await _close(tester); + }); + + testWidgets('gives the page the dark theme of the app', (tester) async { + await tester.pumpWidget(_app(brightness: Brightness.dark)); + openDemoGameLink('rees46://game'); + await _settle(tester); + + final page = web.controllers.single; + expect( + page.background, + PersonalizationTheme.dark.colors.backgroundGeneric, + ); + page.finish(); + await tester.pump(); + expect(page.scripts, [ + "window.setGameTheme && window.setGameTheme('dark')", + ]); + await _close(tester); + }); + + testWidgets('loads the https page of the link instead', (tester) async { + await tester.pumpWidget(_app()); + openDemoGameLink( + 'rees46rn://game?url=https%3A%2F%2Fgames.example.com%2Fttt', + ); + await _settle(tester); + + final page = web.controllers.single; + expect(page.asset, isNull); + expect(page.request, Uri.parse('https://games.example.com/ttt')); + // A failed page is not left under the cover. + page.fail(); + await tester.pump(); + await tester.pump(); + expect(find.byType(PersonalizationLoader), findsNothing); + await _close(tester); + }); + + testWidgets('is one: a second link while it is open opens nothing', ( + tester, + ) async { + await tester.pumpWidget(_app()); + expect(openDemoGameLink('rees46flutter://game'), isTrue); + await _settle(tester); + expect(openDemoGameLink('rees46://game'), isTrue); + await _settle(tester); + expect(find.byType(DemoGameScreen), findsOneWidget); + expect(openDemoGameLink('https://rees46.com'), isFalse); + await _close(tester); + }); + + testWidgets('closes with its cross and with back', (tester) async { + await tester.pumpWidget(_app()); + openDemoGameLink('rees46flutter://game'); + await _settle(tester); + await _close(tester); + expect(find.text('home'), findsOneWidget); + + openDemoGameLink('rees46flutter://game'); + await _settle(tester); + expect(await tester.binding.handlePopRoute(), isTrue); + await _settle(tester); + expect(find.byType(DemoGameScreen), findsNothing); + }); + + testWidgets('opens from a stories button link of any demo', (tester) async { + await tester.pumpWidget(_app()); + // The shop is not up here: other links have nothing to open them, and no error. + demoStoriesLinkClick('no-such-shop')('https://rees46.com'); + await _settle(tester); + expect(find.byType(DemoGameScreen), findsNothing); + + demoStoriesLinkClick('no-such-shop')('rees46://game'); + await _settle(tester); + expect(find.byType(DemoGameScreen), findsOneWidget); + await _close(tester); + }); + + testWidgets('a link from outside opens it over the shop-only demo', ( + tester, + ) async { + await tester.pumpWidget(const ShopApp()); + await _linkFromOutside(tester, 'rees46flutter://game'); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.byType(DemoGameScreen), findsOneWidget); + await _unmount(tester); + }); + + testWidgets('the link the shop-only demo started with opens it', ( + tester, + ) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + _links, + (call) async => + call.method == 'getInitialLink' ? 'rees46flutter://game' : null, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + _links, + null, + ), + ); + await tester.pumpWidget(const ShopApp()); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.byType(DemoGameScreen), findsOneWidget); + await _unmount(tester); + }); + + testWidgets('a popup link to it opens it, and the popup goes', ( + tester, + ) async { + await tester.pumpWidget(const ShopApp()); + final popups = REES46.getInstance(demoShopId).popups; + expect(popups.onLink!('https://rees46.com'), isFalse); + expect(find.byType(DemoGameScreen), findsNothing); + + expect(popups.onLink!('rees46://game'), isTrue); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.byType(DemoGameScreen), findsOneWidget); + await _unmount(tester); + }); + + testWidgets('the popups of triggers keep off it while it is open', ( + tester, + ) async { + await tester.pumpWidget(const ShopApp()); + final sdk = REES46.getInstance(demoShopId); + expect(sdk.enableAutoPopupPresentation, isTrue); + expect(openDemoGameLink('rees46://game'), isTrue); + await _settle(tester); + expect(sdk.enableAutoPopupPresentation, isFalse); + await _close(tester); + expect(sdk.enableAutoPopupPresentation, isTrue); + await _unmount(tester); + }); + }); +} + +const MethodChannel _links = MethodChannel('rees46_sdk_example/links'); + +/// An app on the demos' navigator with a home to come back to. +Widget _app({Brightness brightness = Brightness.light}) => MaterialApp( + navigatorKey: demoNavigatorKey, + theme: demoTheme(brightness), + home: const Scaffold(body: Text('home')), +); + +/// Taps the cross of the game's panel. +Future _close(WidgetTester tester) async { + await tester.tap( + find.byWidgetPredicate( + (widget) => widget is ShopRoundButton && widget.label == 'Закрыть', + ), + ); + await _settle(tester); + expect(find.byType(DemoGameScreen), findsNothing); +} + +/// Through a route's transition: the cover's loader keeps animating, so pumps of a +/// set length, not until it settles. +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); +} + +/// A link as MainActivity / AppDelegate hand it over while the app runs. +Future _linkFromOutside(WidgetTester tester, String url) => + tester.binding.defaultBinaryMessenger.handlePlatformMessage( + _links.name, + _links.codec.encodeMethodCall(MethodCall('onLink', url)), + (_) {}, + ); + +/// Drops the shop and runs out the timeouts of its requests, which have no host here. +Future _unmount(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(const Duration(minutes: 1)); +} + +/// WebViews without a platform: each remembers what it was told to do, and the test +/// finishes its page. +class _FakeWebViewPlatform extends WebViewPlatform { + final List<_FakeController> controllers = <_FakeController>[]; + + @override + PlatformWebViewController createPlatformWebViewController( + PlatformWebViewControllerCreationParams params, + ) { + final controller = _FakeController(params); + controllers.add(controller); + return controller; + } + + @override + PlatformNavigationDelegate createPlatformNavigationDelegate( + PlatformNavigationDelegateCreationParams params, + ) => _FakeDelegate(params); + + @override + PlatformWebViewWidget createPlatformWebViewWidget( + PlatformWebViewWidgetCreationParams params, + ) => _FakeWidget(params); +} + +class _FakeController extends PlatformWebViewController { + _FakeController(super.params) : super.implementation(); + + String? asset; + Uri? request; + JavaScriptMode? javaScriptMode; + Color? background; + _FakeDelegate? delegate; + final List scripts = []; + + void finish() => delegate!.onPageFinished!(asset ?? request.toString()); + + void fail() => delegate!.onWebResourceError!( + const WebResourceError( + errorCode: -2, + description: 'no network', + isForMainFrame: true, + ), + ); + + @override + Future loadFlutterAsset(String key) async => asset = key; + + @override + Future loadRequest(LoadRequestParams params) async => + request = params.uri; + + @override + Future setJavaScriptMode(JavaScriptMode javaScriptMode) async => + this.javaScriptMode = javaScriptMode; + + @override + Future setBackgroundColor(Color color) async => background = color; + + @override + Future setPlatformNavigationDelegate( + PlatformNavigationDelegate handler, + ) async => delegate = handler as _FakeDelegate; + + @override + Future runJavaScript(String javaScript) async => + scripts.add(javaScript); +} + +class _FakeDelegate extends PlatformNavigationDelegate { + _FakeDelegate(super.params) : super.implementation(); + + PageEventCallback? onPageFinished; + WebResourceErrorCallback? onWebResourceError; + + @override + Future setOnPageFinished(PageEventCallback onPageFinished) async => + this.onPageFinished = onPageFinished; + + @override + Future setOnWebResourceError( + WebResourceErrorCallback onWebResourceError, + ) async => this.onWebResourceError = onWebResourceError; +} + +class _FakeWidget extends PlatformWebViewWidget { + _FakeWidget(super.params) : super.implementation(); + + @override + Widget build(BuildContext context) => const SizedBox.expand(); +} diff --git a/example/test/demo_tabs_test.dart b/example/test/demo_tabs_test.dart new file mode 100644 index 0000000..f7db390 --- /dev/null +++ b/example/test/demo_tabs_test.dart @@ -0,0 +1,237 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk_example/demo_tabs.dart'; +import 'package:rees46_sdk_example/shop/shop_sort.dart'; + +/// A tab that shows whether it kept its state: every tap counts. +class _Counter extends StatefulWidget { + const _Counter(this.name); + + final String name; + + @override + State<_Counter> createState() => _CounterState(); +} + +class _CounterState extends State<_Counter> { + int _taps = 0; + + @override + Widget build(BuildContext context) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => setState(() => _taps++), + child: Text('${widget.name} taps: $_taps'), + ), + ), + ); +} + +/// Shop home: opens its screens on the navigator it finds, as the shop does, and +/// has a search panel that back closes first, as the shop's search field does. +class _ShopHome extends StatefulWidget { + const _ShopHome(); + + @override + State<_ShopHome> createState() => _ShopHomeState(); +} + +class _ShopHomeState extends State<_ShopHome> { + bool _searching = false; + + @override + Widget build(BuildContext context) => PopScope( + canPop: !_searching, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) setState(() => _searching = false); + }, + child: Scaffold( + appBar: AppBar(title: const Text('Shop home')), + body: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const _ShopCategory()), + ), + child: const Text('Open category'), + ), + TextButton( + onPressed: () => setState(() => _searching = true), + child: Text(_searching ? 'Search panel' : 'Search'), + ), + ], + ), + ), + ), + ); +} + +class _ShopCategory extends StatelessWidget { + const _ShopCategory(); + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('Category')), + body: Center( + child: TextButton( + onPressed: () => pickShopSort(context, ShopSort.relevance), + child: const Text('Sort'), + ), + ), + ); +} + +Widget _app() => const MaterialApp( + home: DemoTabs( + api: _Counter('api'), + uiKit: _Counter('kit'), + shop: _ShopHome(), + ), +); + +NavigationBar _bar(WidgetTester tester) => + tester.widget(find.byType(NavigationBar)); + +Future _openTab(WidgetTester tester, String label) async { + await tester.tap( + find.descendant(of: find.byType(NavigationBar), matching: find.text(label)), + ); + await tester.pumpAndSettle(); +} + +/// System back, as Android sends it. `false` — nothing in the app took it, so the +/// app would leave. +Future _systemBack(WidgetTester tester) async { + final handled = await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + return handled; +} + +/// Hidden tabs stay mounted, so a finder sees them too; only the open one takes taps. +Finder _shown(String text) => find.text(text).hitTestable(); + +void main() { + testWidgets('opens on API with API | UI Kit | Shop in the bar', ( + tester, + ) async { + await tester.pumpWidget(_app()); + + expect( + _bar(tester).destinations.map( + (destination) => (destination as NavigationDestination).label, + ), + ['API', 'UI Kit', 'Shop'], + ); + expect(_bar(tester).selectedIndex, 0); + expect(_shown('api taps: 0'), findsOneWidget); + // The other tabs are built when first opened. + expect(find.text('kit taps: 0'), findsNothing); + expect(find.text('Shop home'), findsNothing); + }); + + testWidgets('a tab keeps its state while another one is open', ( + tester, + ) async { + await tester.pumpWidget(_app()); + await tester.tap(find.text('api taps: 0')); + await tester.pump(); + + await _openTab(tester, 'UI Kit'); + expect(_bar(tester).selectedIndex, 1); + expect(_shown('api taps: 1'), findsNothing); + await tester.tap(_shown('kit taps: 0')); + await tester.pump(); + + await _openTab(tester, 'API'); + expect(_shown('api taps: 1'), findsOneWidget); + await _openTab(tester, 'UI Kit'); + expect(_shown('kit taps: 1'), findsOneWidget); + }); + + testWidgets('shop screens open inside the tab, under the tab bar', ( + tester, + ) async { + await tester.pumpWidget(_app()); + await _openTab(tester, 'Shop'); + expect(_shown('Shop home'), findsOneWidget); + // The shop's home is the tab's first screen: nothing to go back to. + expect(find.byType(BackButton), findsNothing); + + await tester.tap(find.text('Open category')); + await tester.pumpAndSettle(); + expect(_shown('Category'), findsOneWidget); + expect(find.byType(NavigationBar).hitTestable(), findsOneWidget); + + // The shop's stack waits while another tab is open. + await _openTab(tester, 'API'); + await _openTab(tester, 'Shop'); + expect(_shown('Category'), findsOneWidget); + + await tester.tap(find.byType(BackButton)); + await tester.pumpAndSettle(); + expect(_shown('Shop home'), findsOneWidget); + }); + + testWidgets('system back walks the shop stack only while Shop is open', ( + tester, + ) async { + await tester.pumpWidget(_app()); + await _openTab(tester, 'Shop'); + await tester.tap(find.text('Open category')); + await tester.pumpAndSettle(); + + // On another tab back leaves the app as usual and the shop keeps its screen. + await _openTab(tester, 'API'); + expect(await _systemBack(tester), isFalse); + await _openTab(tester, 'Shop'); + expect(_shown('Category'), findsOneWidget); + + // On Shop it steps back through the shop. + expect(await _systemBack(tester), isTrue); + expect(_shown('Shop home'), findsOneWidget); + expect(_bar(tester).selectedIndex, 2); + + // On the shop's home it is back as on any other tab. + expect(await _systemBack(tester), isFalse); + expect(_shown('Shop home'), findsOneWidget); + }); + + testWidgets('system back on the shop home closes its search panel first', ( + tester, + ) async { + await tester.pumpWidget(_app()); + await _openTab(tester, 'Shop'); + await tester.tap(find.text('Search')); + await tester.pumpAndSettle(); + expect(_shown('Search panel'), findsOneWidget); + + expect(await _systemBack(tester), isTrue); + expect(_shown('Search'), findsOneWidget); + expect(await _systemBack(tester), isFalse); + }); + + testWidgets('the sort picker of a shop screen closes, not the screen', ( + tester, + ) async { + await tester.pumpWidget(_app()); + await _openTab(tester, 'Shop'); + await tester.tap(find.text('Open category')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Sort')); + await tester.pumpAndSettle(); + expect(find.text('Sort by'), findsOneWidget); + await tester.tap(find.text('Discount')); + await tester.pumpAndSettle(); + expect(find.text('Sort by'), findsNothing); + expect(_shown('Category'), findsOneWidget); + + await tester.tap(find.text('Sort')); + await tester.pumpAndSettle(); + expect(await _systemBack(tester), isTrue); + expect(find.text('Sort by'), findsNothing); + expect(_shown('Category'), findsOneWidget); + }); +} diff --git a/example/test/main_shop_test.dart b/example/test/main_shop_test.dart new file mode 100644 index 0000000..a8ab640 --- /dev/null +++ b/example/test/main_shop_test.dart @@ -0,0 +1,108 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; +import 'package:rees46_sdk_example/demo_app.dart'; +import 'package:rees46_sdk_example/main_shop.dart'; +import 'package:rees46_sdk_example/shop/shop.dart'; + +void main() { + testWidgets('the shop-only demo opens the shop, without the tabs', ( + tester, + ) async { + await tester.pumpWidget(const ShopApp()); + + // No app bar: the home's own heading starts under the status bar. + expect(find.byType(AppBar), findsNothing); + expect(find.text('Shop'), findsOneWidget); + expect(find.byType(NavigationBar), findsNothing); + expect(find.text('REES46 SDK init demo'), findsNothing); + expect(REES46.isInitialized(demoShopId), isTrue); + await _unmount(tester); + }); + + testWidgets('home searches behind the button of its header', (tester) async { + await tester.pumpWidget(const ShopApp()); + expect(find.byType(PersonalizationInstantSearchField), findsNothing); + + await tester.tap(_round('Search')); + await tester.pump(); + await tester.pump(); + // The field takes the header's place, focused, and the rest of home steps aside. + expect(find.text('Shop'), findsNothing); + expect(find.byType(PersonalizationInstantSearchField), findsOneWidget); + expect( + tester.widget(find.byType(EditableText)).focusNode.hasFocus, + isTrue, + ); + expect(find.byType(PersonalizationStories).hitTestable(), findsNothing); + + await tester.tap(find.text('Cancel')); + await tester.pump(); + expect(find.text('Shop'), findsOneWidget); + expect(find.byType(PersonalizationInstantSearchField), findsNothing); + + // Back closes the search, not the screen. + await tester.tap(_round('Search')); + await tester.pump(); + expect(await tester.binding.handlePopRoute(), isTrue); + await tester.pump(); + expect(find.text('Shop'), findsOneWidget); + await _unmount(tester); + }); + + testWidgets('the popups menu of the header lists the demo popups', ( + tester, + ) async { + await tester.pumpWidget(const ShopApp()); + + // The home's loaders keep animating: pumps of a set length, not until it settles. + await tester.tap(_round('Show popup')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + for (final popup in demoManualPopups) { + expect(find.text(popup.label), findsOneWidget); + } + + // A pick closes the menu; the popup itself comes from the server. + await tester.tap(find.text(demoManualPopups.first.label)); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text(demoManualPopups.first.label), findsNothing); + await _unmount(tester); + }); + + testWidgets('the shop home stories share over API v3 in the demo scheme', ( + tester, + ) async { + await tester.pumpWidget(const ShopApp()); + + // The home's block runs under the v3 gate's widget. + final stories = tester.widget( + find.ancestor( + of: find.byType(PersonalizationStories), + matching: find.byType(PersonalizationStoriesV3), + ), + ); + expect(stories.ownApiV3Domain, demoStoriesApiV3Domain); + expect( + stories.shareUrlTransform!( + 'https://demo.rees46.ru/?r46_stories=c&r46_story=40&r46_slide=37', + ), + 'rees46flutter://demo.rees46.ru/?r46_stories=c&r46_story=40&r46_slide=37', + ); + await _unmount(tester); + }); +} + +/// The round button of the shop's header called [label]. +Finder _round(String label) => find.byWidgetPredicate( + (widget) => widget is ShopRoundButton && widget.label == label, +); + +/// Drops the shop and runs out the timeouts of its requests, which have no host here. +Future _unmount(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(const Duration(minutes: 1)); +} diff --git a/example/test/shop_facets_test.dart b/example/test/shop_facets_test.dart new file mode 100644 index 0000000..15aa097 --- /dev/null +++ b/example/test/shop_facets_test.dart @@ -0,0 +1,19 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk_example/shop/shop_facets.dart'; + +void main() { + test('the shop names its own facets, the rest keep the kit title', () { + expect(shopFacetTitle('stickers'), 'Стикеры'); + expect(shopFacetTitle('stickers_liquid'), 'Стикеры'); + expect(shopFacetTitle('product_type'), 'Тип товара'); + expect(shopFacetTitle('merchant'), isNull); + }); + + test('product types get names, other values keep the kit label', () { + expect(shopFacetValueTitle('product_type', 'regular'), 'Обычный'); + expect(shopFacetValueTitle('product_type', 'digital'), 'Цифровой'); + expect(shopFacetValueTitle('product_type', 'mto'), 'Под заказ'); + expect(shopFacetValueTitle('product_type', 'other'), isNull); + expect(shopFacetValueTitle('stickers', 'regular'), isNull); + }); +} diff --git a/example/test/shop_products_test.dart b/example/test/shop_products_test.dart new file mode 100644 index 0000000..13b6f48 --- /dev/null +++ b/example/test/shop_products_test.dart @@ -0,0 +1,141 @@ +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk_example/shop/shop_products.dart'; + +Product _product(Map fields) => Product.fromJson({ + 'id': '868', + 'name': 'Headphones', + 'brand': 'Logitech', + 'image_url': 'https://example.org/full.jpg', + 'price': 900, + 'price_formatted': '900 ₸', + 'currency': '₸', + ...fields, +}); + +void main() { + group('shopCard', () { + test('a discounted product: old price and the formatted discount', () { + final card = shopCard( + _product({ + 'oldprice': 1000, + 'oldprice_formatted': '1 000 ₸', + 'discount': 10, + 'discount_formatted': '10%', + 'picture': 'https://example.org/small.jpg', + }), + actionText: 'Add to cart', + ); + expect(card.price, '900 ₸'); + expect(card.oldPrice, '1 000 ₸'); + expect(card.discount, '-10%'); + expect(card.brand, 'Logitech'); + expect(card.actionText, 'Add to cart'); + expect( + (card.image! as NetworkImage).url, + 'https://example.org/small.jpg', + ); + }); + + test('no old price and no badge when the old price is not above', () { + final card = shopCard( + _product({ + 'oldprice': 900, + 'oldprice_formatted': '900 ₸', + 'discount': 10, + }), + ); + expect(card.oldPrice, isNull); + expect(card.discount, isNull); + }); + + test('a zero or boolean discount is no discount', () { + final old = {'oldprice': 1000, 'oldprice_formatted': '1 000 ₸'}; + expect( + shopCard( + _product({...old, 'discount': 0, 'discount_formatted': '0%'}), + ).discount, + isNull, + ); + expect(shopCard(_product({...old, 'discount': true})).discount, isNull); + }); + + test('discount_percent alone gives "N%", never discount_formatted', () { + final card = shopCard( + _product({ + 'oldprice': 1000, + 'oldprice_formatted': '1 000 ₸', + 'discount': 0, + 'discount_formatted': '0%', + 'discount_percent': 12, + }), + ); + expect(card.discount, '-12%'); + }); + + test('a formatted discount with a minus gets exactly one', () { + final card = shopCard( + _product({ + 'oldprice': 1000, + 'oldprice_formatted': '1 000 ₸', + 'discount': 10, + 'discount_formatted': '-10%', + }), + ); + expect(card.discount, '-10%'); + }); + + test('price and image fall back to price + currency and image_url', () { + final card = shopCard(_product({'price_formatted': null})); + expect(card.price, '900.0 ₸'); + expect((card.image! as NetworkImage).url, 'https://example.org/full.jpg'); + }); + }); + + test('shopTopCategories takes the listing categories first', () { + final response = ProductsListResponse.fromJson({ + 'products_total': 1, + 'categories': [ + {'id': 'laptops', 'name': 'Laptops'}, + {'id': 'gaming', 'name': 'Gaming laptops', 'parent_id': 'laptops'}, + {'id': 'kitchen', 'name': 'Kitchen'}, + ], + 'products': [ + { + 'id': '1', + 'categories': [ + {'id': 'phones', 'name': 'Phones'}, + ], + }, + ], + }); + expect(shopTopCategories(response).map((c) => c.id), [ + 'laptops', + 'kitchen', + ]); + }); + + test('without listing categories they come from the products', () { + final response = ProductsListResponse.fromJson({ + 'products_total': 2, + 'products': [ + { + 'id': '1', + 'categories': [ + {'id': 'phones', 'name': 'Phones'}, + {'id': 'headphones', 'name': 'Headphones', 'parent_id': 'phones'}, + ], + }, + { + 'id': '2', + 'categories': [ + {'id': 'kitchen', 'name': 'Kitchen'}, + {'id': 'phones', 'name': 'Phones'}, + ], + }, + ], + }); + expect(shopTopCategories(response).map((c) => c.id), ['phones', 'kitchen']); + }); +} diff --git a/example/test/shop_sort_test.dart b/example/test/shop_sort_test.dart new file mode 100644 index 0000000..3489d5d --- /dev/null +++ b/example/test/shop_sort_test.dart @@ -0,0 +1,48 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk_example/shop/shop_sort.dart'; + +void main() { + test('each sort is the sort_by / sort_dir pair the API takes', () { + expect( + ShopSort.values.map((sort) => (sort.label, sort.sortBy, sort.sortDir)), + [ + ('Relevance', null, null), + ('Price: low to high', 'price', 'asc'), + ('Price: high to low', 'price', 'desc'), + ('Discount', 'discount', 'desc'), + ], + ); + }); + + for (final platform in [TargetPlatform.android, TargetPlatform.iOS]) { + testWidgets('the sheet hands back the chosen sort on ${platform.name}', ( + tester, + ) async { + final picked = []; + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: platform), + home: Builder( + builder: (context) => TextButton( + onPressed: () async => + picked.add(await pickShopSort(context, ShopSort.relevance)), + child: const Text('Sort'), + ), + ), + ), + ); + + await tester.tap(find.text('Sort')); + await tester.pumpAndSettle(); + expect(find.text('Sort by'), findsOneWidget); + expect(find.text('Relevance'), findsOneWidget); + // The current sort is checked, the others are not. + expect(find.byIcon(Icons.check), findsOneWidget); + await tester.tap(find.text('Discount')); + await tester.pumpAndSettle(); + + expect(picked, [ShopSort.discount]); + }); + } +} diff --git a/example/test/stories_polls_demo_test.dart b/example/test/stories_polls_demo_test.dart new file mode 100644 index 0000000..f8de3b7 --- /dev/null +++ b/example/test/stories_polls_demo_test.dart @@ -0,0 +1,77 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +// ignore: implementation_imports +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; +import 'package:rees46_sdk_example/stories_polls_demo.dart'; + +List _stories() { + final json = + jsonDecode( + File('assets/uikit/stories_polls_feed.json').readAsStringSync(), + ) + as Map; + return StoriesBlock.fromJson(json['payload'] as Map).stories; +} + +void main() { + test( + 'the demo feed: one campaign, seven polls drawn, the unknown dropped', + () { + final slides = _stories().single.slides; + expect(slides, hasLength(8)); + expect( + slides.where( + (slide) => slide.elements.whereType().isNotEmpty, + ), + hasLength(7), + ); + }, + ); + + testWidgets( + 'the fake transport: results add up to 100, demo_text fails once', + (tester) async { + final transport = DemoPollsTransport(_stories()); + StoryPollReply? reply; + unawaited( + transport + .answerMiniPoll('demo_multi', { + 'option_ids': [1, 3], + }) + .then((value) => reply = value), + ); + await tester.pump(DemoPollsTransport.delay); + expect(reply!.answer!.optionIds, [1, 3]); + final options = reply!.results!.options!; + expect( + options.fold(0, (sum, option) => sum + option.percent), + 100, + ); + expect( + reply!.results!.percentOf(1), + greaterThan(reply!.results!.percentOf(2)!), + ); + + Object? error; + unawaited( + transport + .answerMiniPoll('demo_text', {'text': 'a'}) + .then((_) {}, onError: (Object e) => error = e), + ); + await tester.pump(DemoPollsTransport.delay); + expect(error, isNotNull); + unawaited( + transport + .answerMiniPoll('demo_text', {'text': 'a'}) + .then((value) => reply = value), + ); + await tester.pump(DemoPollsTransport.delay); + expect(reply!.answer!.text, 'a'); + expect(reply!.results, isNull, reason: 'no show_results'); + }, + ); +} diff --git a/example/test/widget_test.dart b/example/test/widget_test.dart index 6511e83..51e0244 100644 --- a/example/test/widget_test.dart +++ b/example/test/widget_test.dart @@ -5,6 +5,7 @@ // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. +import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rees46_sdk_example/main.dart'; @@ -14,4 +15,30 @@ void main() { await tester.pumpWidget(const App()); expect(find.text('REES46 SDK init demo'), findsOneWidget); }); + + testWidgets('Shop and UI Kit are tabs, not entries of the API page', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(const App()); + + for (final label in ['API', 'UI Kit', 'Shop']) { + expect( + find.descendant( + of: find.byType(NavigationBar), + matching: find.text(label), + ), + findsOneWidget, + ); + } + for (final key in [ + 'open-shop', + 'open-shop-button', + 'open-ui-kit', + 'open-ui-kit-button', + ]) { + expect(find.byKey(Key(key)), findsNothing); + } + expect(find.byKey(const Key('open-multi-instance')), findsOneWidget); + expect(find.byKey(const Key('open-multi-instance-button')), findsOneWidget); + }); } diff --git a/ios/rees46_sdk.podspec b/ios/rees46_sdk.podspec index 296010d..6219444 100644 --- a/ios/rees46_sdk.podspec +++ b/ios/rees46_sdk.podspec @@ -20,7 +20,7 @@ Flutter plugin wrapper around REES46 native SDK. # Keep in step with the dependency in rees46_sdk/Package.swift. CocoaPods trunk is # read-only, so a version newer than the last one there resolves only through the # app's Podfile (see "iOS" in README.md). - s.dependency 'REES46', '3.36.1' + s.dependency 'REES46', '3.37.0' s.platform = :ios, '13.0' # Flutter.framework does not contain a i386 slice. diff --git a/ios/rees46_sdk/Package.swift b/ios/rees46_sdk/Package.swift index ae48507..b3459a8 100644 --- a/ios/rees46_sdk/Package.swift +++ b/ios/rees46_sdk/Package.swift @@ -13,7 +13,7 @@ let package = Package( ], dependencies: [ // Keep in step with the dependency in ../rees46_sdk.podspec. - .package(url: "https://github.com/rees46/ios-sdk.git", exact: "3.36.1") + .package(url: "https://github.com/rees46/ios-sdk.git", exact: "3.37.0") ], targets: [ .target( diff --git a/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift b/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift index 7dab496..e016157 100644 --- a/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift +++ b/ios/rees46_sdk/Sources/rees46_sdk/Rees46FlutterSdkPlugin.swift @@ -263,9 +263,24 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { ] if let pf = p.priceFormatted { dict["price_formatted"] = pf } if let pff = p.priceFullFormatted { dict["price_full_formatted"] = pff } + _putDiscount(&dict, oldPrice: p.oldPrice, oldPriceFormatted: p.oldPriceFormatted, discount: p.discount) + if !p.deeplinkIos.isEmpty { dict["deeplink_ios"] = p.deeplinkIos } return dict } + /// Old price and discount as the API sends them: only for a discounted product. The + /// native models fill an absent value with 0 or "", which would read as a real one. + private static func _putDiscount( + _ dict: inout [String: Any], + oldPrice: Double, + oldPriceFormatted: String?, + discount: Int + ) { + if oldPrice > 0 { dict["oldprice"] = oldPrice } + if let v = oldPriceFormatted, !v.isEmpty { dict["oldprice_formatted"] = v } + if discount > 0 { dict["discount"] = discount } + } + private static func _categoryToDict(_ c: REES46.Category) -> [String: Any] { var dict: [String: Any] = ["id": c.id, "name": c.name] if let parentId = c.parentId { dict["parent_id"] = parentId } @@ -340,17 +355,35 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { // As of REES46 3.24+, ProductsListResponse.products is [Product] (not [ProductInfo]); // Product carries no categories, which the Dart parser already treats as optional. var dict: [String: Any] = [ - "products": r.products.map { _searchProductToDict($0) }, + "products": r.products.map { _productsListProductToDict($0) }, "products_total": r.productsTotal, ] if let pr = r.priceRange { dict["price_range"] = ["min": pr.min, "max": pr.max] } + if let brands = r.brands { + dict["brands"] = brands + } + if let filters = r.filters { + dict["filters"] = filters.mapValues { ["count": $0.count, "values": $0.values] as [String: Any] } + } + return dict + } + + /// A products list item for the Dart `Product`, whose old price and discount are + /// nullable: they go out only for a discounted product, as on Android. Search keeps + /// sending the native zeros, which its model reads as "none". + private static func _productsListProductToDict(_ p: Product) -> [String: Any] { + var dict = _searchProductToDict(p) + dict.removeValue(forKey: "oldprice") + dict.removeValue(forKey: "oldprice_formatted") + dict.removeValue(forKey: "discount") + _putDiscount(&dict, oldPrice: p.oldPrice, oldPriceFormatted: p.oldPriceFormatted, discount: p.discount) return dict } private static func _productInfoToDict(_ p: ProductInfo) -> [String: Any] { - return [ + var dict: [String: Any] = [ "id": p.id, // normalised from "uniqid" "name": p.name, "brand": p.brand, @@ -372,6 +405,11 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { return d }, ] + if !p.resizedImageUrl.isEmpty { dict["picture"] = p.resizedImageUrl } + _putDiscount(&dict, oldPrice: p.oldPrice, oldPriceFormatted: p.oldPriceFormatted, discount: p.discount) + if !p.deeplinkIos.isEmpty { dict["deeplink_ios"] = p.deeplinkIos } + if let isNew = p.isNew { dict["is_new"] = isNew } + return dict } func searchBlank(shopId: String?, completion: @escaping (Result) -> Void) { @@ -587,7 +625,8 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { "oldprice_formatted": p.oldPriceFormatted, "discount": p.discount, ] - _ = dict // suppress unused warning; all fields set above + if !p.deeplinkIos.isEmpty { dict["deeplink_ios"] = p.deeplinkIos } + if let isNew = p.isNew { dict["is_new"] = isNew } return dict } @@ -691,7 +730,7 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { } } - func getCategory(category: String, limit: Int64?, page: Int64?, shopId: String?, completion: @escaping (Result) -> Void) { + func getCategory(category: String, limit: Int64?, page: Int64?, paramsJson: String?, 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 @@ -700,13 +739,23 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { completion(.failure(PigeonError(code: "bad_args", message: "category is required", details: nil))) return } + let p = parseJsonObject(paramsJson) + let brands = (p?["brands"] as? String).flatMap { $0.isEmpty ? nil : $0 } + let locations = (p?["locations"] as? String).flatMap { $0.isEmpty ? nil : $0 } + let filters = (p?["filters"] as? [String: Any]).flatMap { $0.isEmpty ? nil : $0 } + let sortBy = (p?["sort_by"] as? String).flatMap { $0.isEmpty ? nil : $0 } + let sortDir = (p?["sort_dir"] as? String).flatMap { $0.isEmpty ? nil : $0 } sdk.getCategory( category: category, limit: limit.map { Int($0) }, page: page.map { Int($0) }, - brands: nil, - locations: nil, - filters: nil + brands: brands, + locations: locations, + filters: filters, + priceMin: p?["price_min"] as? Double, + priceMax: p?["price_max"] as? Double, + sortBy: sortBy, + sortDir: sortDir ) { result in switch result { case .success(let response): @@ -782,6 +831,69 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { } } + func shareUrl( + url: String, + anchorX: Double, + anchorY: Double, + anchorWidth: Double, + anchorHeight: Double, + completion: @escaping (Result) -> Void + ) { + guard let target = URL(string: url) else { + completion(.failure(PigeonError(code: "bad_args", message: "invalid url", details: nil))) + return + } + DispatchQueue.main.async { + guard let presenter = Self._topViewController() else { + completion(.failure(PigeonError(code: "share_failed", message: "no view controller to present from", details: nil))) + return + } + let sheet = UIActivityViewController(activityItems: [target], applicationActivities: nil) + // The handler may come more than once (an activity done, then the sheet gone): one reply. + var replied = false + sheet.completionWithItemsHandler = { _, _, _, _ in + if replied { return } + replied = true + completion(.success(())) + } + // iPad shows the sheet as a popover, and a popover without a source crashes. The anchor + // is the button in the Flutter view's points; without one the popover sits in the middle. + if let popover = sheet.popoverPresentationController { + let source = Self._flutterView() ?? presenter.view! + let anchor = CGRect(x: anchorX, y: anchorY, width: anchorWidth, height: anchorHeight) + popover.sourceView = source + if anchor.isEmpty { + popover.sourceRect = CGRect(x: source.bounds.midX, y: source.bounds.midY, width: 0, height: 0) + popover.permittedArrowDirections = [] + } else { + popover.sourceRect = anchor + } + } + presenter.present(sheet, animated: true) + } + } + + /// The key window of the app. + private static func _keyWindow() -> UIWindow? { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + return scenes.flatMap { $0.windows }.first { $0.isKeyWindow } + ?? (UIApplication.shared.delegate?.window ?? nil) + } + + /// The controller on top of the key window: the one a sheet is presented from. + private static func _topViewController() -> UIViewController? { + var top = _keyWindow()?.rootViewController + while let presented = top?.presentedViewController, !presented.isBeingDismissed { + top = presented + } + return top + } + + /// The view Flutter draws into: the coordinates Dart measures the anchor in. + private static func _flutterView() -> UIView? { + return (_keyWindow()?.rootViewController as? FlutterViewController)?.view + } + // MARK: - Stories viewer (UI kit) func getStoriesSeen(shop: String) throws -> [String: [Any?]] { @@ -845,6 +957,12 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { return [ "products_total": r.productsTotal, "products": r.products.map { _categoryProductToDict($0) }, + "brands": r.brands.compactMap { b -> [String: Any]? in + guard let name = b.name, !name.isEmpty else { return nil } + var d: [String: Any] = ["name": name] + if let count = b.count { d["count"] = count } + return d + }, ] } diff --git a/ios/rees46_sdk/Sources/rees46_sdk/pigeon/PersonalizationApi.g.swift b/ios/rees46_sdk/Sources/rees46_sdk/pigeon/PersonalizationApi.g.swift index 79ec05b..de5f1b9 100644 --- a/ios/rees46_sdk/Sources/rees46_sdk/pigeon/PersonalizationApi.g.swift +++ b/ios/rees46_sdk/Sources/rees46_sdk/pigeon/PersonalizationApi.g.swift @@ -663,8 +663,12 @@ protocol PersonalizationHostApi { func getProductCounters(item: String, shopId: String?, completion: @escaping (Result) -> Void) /// Returns a category product listing as a JSON string. /// [limit] and [page] paginate the result; both are optional. + /// [paramsJson] is a JSON object string with the optional filters: "brands" and + /// "locations" (comma-separated strings), "filters" (facet name → [values]), + /// "price_min" / "price_max" (numbers), "sort_by" / "sort_dir" (strings). A bridge + /// passes on only what its native SDK takes for a category. /// Dart layer parses the result into [CategoryResponse]. - func getCategory(category: String, limit: Int64?, page: Int64?, shopId: String?, completion: @escaping (Result) -> Void) + func getCategory(category: String, limit: Int64?, page: Int64?, paramsJson: String?, shopId: String?, completion: @escaping (Result) -> Void) /// Returns a merchandised collection's products as a JSON string. /// Dart layer parses the result into [CollectionResponse]. func getCollection(collectionId: String, shopId: String?, completion: @escaping (Result) -> Void) @@ -676,6 +680,12 @@ protocol PersonalizationHostApi { /// Opens [url] with the system handler (browser or the app that claims the link). /// Returns false when nothing could open it. func openUrl(url: String, completion: @escaping (Result) -> Void) + /// Shows the system share sheet with one link [url] — the "Share" button of the stories + /// viewer. Completes when the sheet is gone: iOS — `completionWithItemsHandler` of + /// `UIActivityViewController`; Android — the window got its focus back after the + /// chooser (`Intent.createChooser` of `ACTION_SEND`). The anchor is the button in + /// logical pixels of the Flutter view: the popover of the sheet points at it on iPad. + func shareUrl(url: String, anchorX: Double, anchorY: Double, anchorWidth: Double, anchorHeight: Double, completion: @escaping (Result) -> Void) /// The slide ids seen per story id for [shop] — the plugin's own store /// (SharedPreferences on Android, UserDefaults on iOS), not the native SDK's. It /// survives app restarts. The inner lists are untyped on purpose: the channel @@ -1088,6 +1098,10 @@ class PersonalizationHostApiSetup { } /// Returns a category product listing as a JSON string. /// [limit] and [page] paginate the result; both are optional. + /// [paramsJson] is a JSON object string with the optional filters: "brands" and + /// "locations" (comma-separated strings), "filters" (facet name → [values]), + /// "price_min" / "price_max" (numbers), "sort_by" / "sort_dir" (strings). A bridge + /// passes on only what its native SDK takes for a category. /// Dart layer parses the result into [CategoryResponse]. let getCategoryChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCategory\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) if let api = api { @@ -1096,8 +1110,9 @@ class PersonalizationHostApiSetup { let categoryArg = args[0] as! String let limitArg: Int64? = nilOrValue(args[1]) let pageArg: Int64? = nilOrValue(args[2]) - let shopIdArg: String? = nilOrValue(args[3]) - api.getCategory(category: categoryArg, limit: limitArg, page: pageArg, shopId: shopIdArg) { result in + let paramsJsonArg: String? = nilOrValue(args[3]) + let shopIdArg: String? = nilOrValue(args[4]) + api.getCategory(category: categoryArg, limit: limitArg, page: pageArg, paramsJson: paramsJsonArg, shopId: shopIdArg) { result in switch result { case .success(let res): reply(wrapResult(res)) @@ -1170,6 +1185,32 @@ class PersonalizationHostApiSetup { } else { openUrlChannel.setMessageHandler(nil) } + /// Shows the system share sheet with one link [url] — the "Share" button of the stories + /// viewer. Completes when the sheet is gone: iOS — `completionWithItemsHandler` of + /// `UIActivityViewController`; Android — the window got its focus back after the + /// chooser (`Intent.createChooser` of `ACTION_SEND`). The anchor is the button in + /// logical pixels of the Flutter view: the popover of the sheet points at it on iPad. + let shareUrlChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.shareUrl\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + shareUrlChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let urlArg = args[0] as! String + let anchorXArg = args[1] as! Double + let anchorYArg = args[2] as! Double + let anchorWidthArg = args[3] as! Double + let anchorHeightArg = args[4] as! Double + api.shareUrl(url: urlArg, anchorX: anchorXArg, anchorY: anchorYArg, anchorWidth: anchorWidthArg, anchorHeight: anchorHeightArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + shareUrlChannel.setMessageHandler(nil) + } /// The slide ids seen per story id for [shop] — the plugin's own store /// (SharedPreferences on Android, UserDefaults on iOS), not the native SDK's. It /// survives app restarts. The inner lists are untyped on purpose: the channel diff --git a/lib/rees46_sdk.dart b/lib/rees46_sdk.dart index 1e30d1f..e5ba59e 100644 --- a/lib/rees46_sdk.dart +++ b/lib/rees46_sdk.dart @@ -1,5 +1,5 @@ -// Stories stay with the UI kit until its release: the kit imports them from src. -export 'src/personalization_sdk.dart' hide PersonalizationStoriesBridge; +// The story viewer's plumbing stays internal: the kit imports it from src. +export 'src/personalization_sdk.dart' hide PersonalizationStoryViewerBridge; export 'src/multi_instance/rees46.dart'; export 'src/multi_instance/rees46_config.dart'; export 'src/multi_instance/push_event.dart'; @@ -22,14 +22,5 @@ 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; +// The UI kit: tokens, the theme, components and the widgets with SDK data. +export 'src/ui/personalization_ui.dart'; diff --git a/lib/src/category/category_params.dart b/lib/src/category/category_params.dart new file mode 100644 index 0000000..4598b8c --- /dev/null +++ b/lib/src/category/category_params.dart @@ -0,0 +1,40 @@ +/// Wire format of the [PersonalizationSdk.getCategory] filters. Not exported from the +/// package barrel. +library; + +import 'dart:convert'; + +/// Whether a category listing applies a price range and a sort (`price_min`, +/// `price_max`, `sort_by`, `sort_dir`) on this platform. +/// +/// The bridges pass them to the native SDKs (Android 2.47.0, iOS 3.37.0 and later +/// take them). The kit's category screen hides its price section and sort button +/// while this is `false`. +const bool categoryPriceAndSortApplied = true; + +/// The JSON object the bridges read, `null` when no filter is set. Keys are the API's; +/// empty values are left out. +String? categoryParamsJson({ + String? brands, + String? locations, + Map>? filters, + double? priceMin, + double? priceMax, + String? sortBy, + String? sortDir, +}) { + final facets = >{ + for (final entry in (filters ?? const >{}).entries) + if (entry.value.isNotEmpty) entry.key: entry.value, + }; + final params = { + if ((brands ?? '').isNotEmpty) 'brands': brands!, + if ((locations ?? '').isNotEmpty) 'locations': locations!, + if (facets.isNotEmpty) 'filters': facets, + 'price_min': ?priceMin, + 'price_max': ?priceMax, + if ((sortBy ?? '').isNotEmpty) 'sort_by': sortBy!, + if ((sortDir ?? '').isNotEmpty) 'sort_dir': sortDir!, + }; + return params.isEmpty ? null : jsonEncode(params); +} diff --git a/lib/src/category/category_response.dart b/lib/src/category/category_response.dart index 356e463..b2c5afe 100644 --- a/lib/src/category/category_response.dart +++ b/lib/src/category/category_response.dart @@ -1,19 +1,41 @@ -import '../products/products_list_response.dart' show Product; +import '../products/products_list_response.dart' show PriceRange, Product; import '../json_number.dart'; +import '../search/search_facets.dart'; +import '../search/search_response.dart' show SearchFilter; export '../products/products_list_response.dart' show Product; /// Response from [PersonalizationSdk.getCategory]. /// -/// Exposes the common subset available on both platforms: the total product -/// count and the product list. Products are parsed with the shared [Product] -/// model (Android returns a richer product than iOS; the parser tolerates the -/// missing fields). +/// The total product count and the product list, plus the facets the API sends +/// with a category as with full search. Products are parsed with the shared +/// [Product] model (Android returns a richer product than iOS; the parser tolerates +/// the missing fields). +/// +/// On iOS only [brands] arrive for now: the native category model has no filters +/// or price range. class CategoryResponse { final int productsTotal; final List products; - const CategoryResponse({required this.productsTotal, required this.products}); + /// Brand names found in the category. + final List brands; + + /// Product count per brand name. + final Map brandCounts; + + /// Shop facets keyed by name: value → product count. + final Map filters; + final PriceRange? priceRange; + + const CategoryResponse({ + required this.productsTotal, + required this.products, + this.brands = const [], + this.brandCounts = const {}, + this.filters = const {}, + this.priceRange, + }); factory CategoryResponse.fromJson(Map json) { return CategoryResponse( @@ -21,6 +43,14 @@ class CategoryResponse { products: (json['products'] as List? ?? []) .map((e) => Product.fromJson(e as Map)) .toList(), + brands: parseBrandNames(json['brands']), + brandCounts: parseFacetCounts(json['brands'], 'name'), + filters: parseFacetFilters(json['filters']), + priceRange: json['price_range'] is Map + ? PriceRange.fromJson( + Map.from(json['price_range'] as Map), + ) + : null, ); } } diff --git a/lib/src/json_number.dart b/lib/src/json_number.dart index 1030aa5..deec1a4 100644 --- a/lib/src/json_number.dart +++ b/lib/src/json_number.dart @@ -6,7 +6,7 @@ /// A plain `value as num?` cast throws `'String' is not a subtype of type /// 'num?'` on the string form, which previously made product/search/ /// recommendation/catalog responses fail to parse. These helpers accept `num`, -/// `String`, or `null`. +/// `String`, or `null`. Flags and optional strings get the same tolerance below. library; /// Coerces [value] to a `double`, or returns `null` if it can't be parsed. @@ -27,3 +27,24 @@ int? toIntOrNull(dynamic value) { } return null; } + +/// Coerces [value] to a `bool`: a JSON bool, `0` / `1`, or `"true"` / `"false"` +/// (`is_new` and similar flags). `null` for anything else. +bool? toBoolOrNull(dynamic value) { + if (value is bool) return value; + if (value is num) return value != 0; + if (value is String) { + switch (value.trim().toLowerCase()) { + case 'true' || '1': + return true; + case 'false' || '0': + return false; + } + } + return null; +} + +/// A non-empty string, or `null` for a missing, empty or non-string value: the iOS +/// models fill an absent optional string with `""`. +String? toNonEmptyStringOrNull(dynamic value) => + value is String && value.isNotEmpty ? value : null; diff --git a/lib/src/personalization_sdk.dart b/lib/src/personalization_sdk.dart index 43807e3..8a11eb8 100644 --- a/lib/src/personalization_sdk.dart +++ b/lib/src/personalization_sdk.dart @@ -1,6 +1,8 @@ import 'dart:convert'; +import 'dart:ui' show Rect; import 'pigeon/personalization_api.g.dart' as pigeon; +import 'category/category_params.dart'; import 'category/category_response.dart'; import 'collection/collection_response.dart'; import 'init/sdk_init_handler.dart'; @@ -10,6 +12,7 @@ import 'multi_instance/push_event.dart'; import 'popups/in_app_popup.dart'; import 'popups/popup_dispatcher.dart'; import 'popups/popup_presenter.dart'; +import 'popups_v3/popups_v3_hooks.dart'; import 'products/product_counters_response.dart'; import 'profile/profile_params.dart'; import 'profile/profile_response.dart'; @@ -107,9 +110,20 @@ class PersonalizationSdk { _popups.autoPresentation = config.enableAutoPopupPresentation ?? true; // The native side reports popups under the shop id it was initialized with. PopupDispatcher.instance.register(config.shopId, _popups); + PopupsV3Hooks.initialized(tracking, config); return _initHandler.initialize(config); } + /// Whether the SDK shows popups by itself: the server popups while no [onPopup] is + /// set, and the other popups the SDK shows by itself (one shown by hand is shown all + /// the same). + /// `enableAutoPopupPresentation` of the config sets it on [initialize]; it may be + /// changed at any time — off, say, while a screen of the app must not be covered. + bool get enableAutoPopupPresentation => _popups.autoPresentation; + + set enableAutoPopupPresentation(bool value) => + _popups.autoPresentation = value; + /// Takes the server popups (in-app messages) of this shop instead of the SDK showing /// them. /// @@ -133,13 +147,22 @@ class PersonalizationSdk { Future presentPopup(InAppPopup popup) => _popups.present(popup); Future setProfile(ProfileParams params) { - return _api.setProfile(params.toWire(), shopId); + final wire = params.toWire(); + PopupsV3Hooks.contextChanged(tracking, 'profile', 'set', wire.encode()); + return _api.setProfile(wire, shopId); } /// Subscribes or unsubscribes the client per channel and mailing type, see /// [ManageSubscriptionParams]. Future manageSubscription(ManageSubscriptionParams params) { - return _api.manageSubscription(params.toWire(), shopId); + final wire = params.toWire(); + PopupsV3Hooks.contextChanged( + tracking, + 'subscription', + 'manage', + wire.encode(), + ); + return _api.manageSubscription(wire, shopId); } Future getSid() { @@ -258,16 +281,45 @@ class PersonalizationSdk { /// Returns a category product listing (native `CategoryManager.getCategory`). /// - /// [limit] and [page] paginate the result; both are optional. + /// [limit] and [page] paginate the result; both are optional. The filters are + /// optional too: [brands] and [locations] are comma-separated, [filters] are the + /// shop's own facets by name — `{"Материал корпуса": ["Металл"]}` — as the + /// response lists them in [CategoryResponse.filters]. + /// + /// [priceMin], [priceMax], [sortBy] (`price`, `discount`, …) and [sortDir] + /// (`asc` / `desc`) are sent, but not applied yet: the native SDKs this plugin + /// is built against take no price range or sort for a category. They apply with + /// no change to the call once the plugin moves to native releases that do. Future getCategory( String category, { int? limit, int? page, + String? brands, + String? locations, + Map>? filters, + double? priceMin, + double? priceMax, + String? sortBy, + String? sortDir, }) async { if (category.isEmpty) { throw ArgumentError.value(category, 'category', 'must be non-empty'); } - final json = await _api.getCategory(category, limit, page, shopId); + final json = await _api.getCategory( + category, + limit, + page, + categoryParamsJson( + brands: brands, + locations: locations, + filters: filters, + priceMin: priceMin, + priceMax: priceMax, + sortBy: sortBy, + sortDir: sortDir, + ), + shopId, + ); return CategoryResponse.fromJson(jsonDecode(json) as Map); } @@ -316,6 +368,7 @@ class PersonalizationSdk { final customFieldsJson = customFields == null ? null : jsonEncode(customFields); + PopupsV3Hooks.trackEvent(tracking, event); return _api.trackEvent( event, time, @@ -355,6 +408,7 @@ class PersonalizationSdk { if (items.isEmpty) { throw ArgumentError.value(items, 'items', 'must be non-empty'); } + PopupsV3Hooks.purchase(tracking); final wireItems = items .map( (e) => pigeon.PurchaseLineItemWire( @@ -390,9 +444,8 @@ class PersonalizationSdk { } } -/// Stories for the UI kit — hidden from the package barrel (`export ... hide`) until the -/// kit's release, and reached by the kit through a direct `src` import. It lives in this -/// library because it calls the host API the handle owns. +/// Stories of the UI kit: the block data and the system handler for its links. It lives +/// in this library because it calls the host API the handle owns. extension PersonalizationStoriesBridge on PersonalizationSdk { /// The stories block [code] (`stories/{code}`). Future getStories(String code) async { @@ -405,6 +458,17 @@ extension PersonalizationStoriesBridge on PersonalizationSdk { /// Opens [url] with the system handler; `false` when nothing could open it. Future openUrl(String url) => _api.openUrl(url); +} + +/// The plumbing of the kit's story viewer: the share sheet and the slides seen on this +/// device. Hidden from the package barrel (`export ... hide`) — the viewer reaches it +/// through a direct `src` import. +extension PersonalizationStoryViewerBridge on PersonalizationSdk { + /// Shows the system share sheet with the link [url]; completes when the sheet is gone. + /// [anchor] is the "Share" button in global logical pixels: the sheet's popover points + /// at it on iPad. + Future shareUrl(String url, Rect anchor) => + _api.shareUrl(url, anchor.left, anchor.top, anchor.width, anchor.height); /// The stories slides seen on this device for [shop] (slide ids by story id), from the /// plugin's own persistent store. diff --git a/lib/src/pigeon/personalization_api.g.dart b/lib/src/pigeon/personalization_api.g.dart index 1be9487..bf70543 100644 --- a/lib/src/pigeon/personalization_api.g.dart +++ b/lib/src/pigeon/personalization_api.g.dart @@ -1272,11 +1272,16 @@ class PersonalizationHostApi { /// Returns a category product listing as a JSON string. /// [limit] and [page] paginate the result; both are optional. + /// [paramsJson] is a JSON object string with the optional filters: "brands" and + /// "locations" (comma-separated strings), "filters" (facet name → [values]), + /// "price_min" / "price_max" (numbers), "sort_by" / "sort_dir" (strings). A bridge + /// passes on only what its native SDK takes for a category. /// Dart layer parses the result into [CategoryResponse]. Future getCategory( String category, int? limit, int? page, + String? paramsJson, String? shopId, ) async { final String pigeonVar_channelName = @@ -1288,7 +1293,7 @@ class PersonalizationHostApi { binaryMessenger: pigeonVar_binaryMessenger, ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [category, limit, page, shopId], + [category, limit, page, paramsJson, shopId], ); final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; @@ -1414,6 +1419,44 @@ class PersonalizationHostApi { } } + /// Shows the system share sheet with one link [url] — the "Share" button of the stories + /// viewer. Completes when the sheet is gone: iOS — `completionWithItemsHandler` of + /// `UIActivityViewController`; Android — the window got its focus back after the + /// chooser (`Intent.createChooser` of `ACTION_SEND`). The anchor is the button in + /// logical pixels of the Flutter view: the popover of the sheet points at it on iPad. + Future shareUrl( + String url, + double anchorX, + double anchorY, + double anchorWidth, + double anchorHeight, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.shareUrl$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [url, anchorX, anchorY, anchorWidth, anchorHeight], + ); + 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; + } + } + /// The slide ids seen per story id for [shop] — the plugin's own store /// (SharedPreferences on Android, UserDefaults on iOS), not the native SDK's. It /// survives app restarts. The inner lists are untyped on purpose: the channel diff --git a/lib/src/popups/popup_presenter.dart b/lib/src/popups/popup_presenter.dart index 58a867c..832d066 100644 --- a/lib/src/popups/popup_presenter.dart +++ b/lib/src/popups/popup_presenter.dart @@ -67,6 +67,19 @@ class PopupPresenter { static final Queue<_Request> _queue = Queue<_Request>(); static _Request? _current; + /// Whether the screen is held by a popup of the new kind (popups v3): the queue + /// waits until [resume] is called. + static bool Function() heldElsewhere = () => false; + + /// Called whenever a popup of this kind leaves the screen. + static void Function()? onIdle; + + /// Whether a popup of this kind is on screen now. + static bool get isPresenting => _current != null; + + /// Shows the next queued popup once the screen is free again. + static void resume() => _next(); + /// 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 @@ -129,7 +142,7 @@ class PopupPresenter { } static void _next() { - if (_current != null || _queue.isEmpty) return; + if (_current != null || _queue.isEmpty || heldElsewhere()) return; final request = _current = _queue.removeFirst(); request.presenter ._show(request) @@ -141,6 +154,7 @@ class PopupPresenter { // Past a reset the queue has moved on without this request. if (_current == request) _current = null; _next(); + if (_current == null) onIdle?.call(); }); } diff --git a/lib/src/popups_v3/popup_v3.dart b/lib/src/popups_v3/popup_v3.dart new file mode 100644 index 0000000..d3a7d32 --- /dev/null +++ b/lib/src/popups_v3/popup_v3.dart @@ -0,0 +1,280 @@ +import 'popup_v3_values.dart'; + +/// Макет попапа v3 в приложении. +enum PopupV3Layout { + /// Полоса сверху или снизу; приложение под ней доступно. + banner('banner'), + + /// Окно по центру; одно на экране. + modal('modal'), + + /// Весь экран; занимает тот же слот, что и окно. + fullscreen('fullscreen'); + + const PopupV3Layout(this.wire); + + final String wire; + + static PopupV3Layout? parse(Object? value) { + for (final layout in values) { + if (layout.wire == value) return layout; + } + return null; + } +} + +/// Где стоит попап: баннер — сверху или снизу, окно и полный экран — по центру. +enum PopupV3Placement { top, bottom, center } + +/// Когда показывать попап. +enum PopupV3Trigger { + /// Запуск приложения: проверяется на каждой загрузке списка и на каждом открытом + /// экране из `target_screens`; сколько раз показать, решает частота. + appStart('app_start'), + + /// Открытие экрана из `target_screens`. + screenOpen('screen_open'), + + /// Столько-то секунд на экране из `target_screens`. + timeOnScreen('time_on_screen'), + + /// Своё событие SDK (`tracking.custom`) с именем `trigger_event`. + trackEvent('track_event'), + + /// Только вручную — `popups.show(id)`. + manual('manual'); + + const PopupV3Trigger(this.wire); + + final String wire; + + static PopupV3Trigger? parse(Object? value) { + for (final trigger in values) { + if (trigger.wire == value) return trigger; + } + return null; + } +} + +/// Как часто показывать попап; считается на устройстве. +enum PopupV3Frequency { + onceSession('once_session'), + onceLife('once_life'), + onceDay('once_day'), + onceWeek('once_week'), + onceMonth('once_month'), + everyPage('every_page'); + + const PopupV3Frequency(this.wire); + + final String wire; + + /// Неизвестная частота и `null` — раз за сессию, как у веба. + static PopupV3Frequency parse(Object? value) { + for (final frequency in values) { + if (frequency.wire == value) return frequency; + } + return onceSession; + } +} + +final RegExp _promoToken = RegExp(r'\{\{\s*promo_code\s*\}\}'); + +/// Попап v3 из `GET /api/v3/storefront/popups` (канал mobile). +class PopupV3 { + const PopupV3({ + required this.id, + required this.layout, + required this.placement, + required this.trigger, + this.triggerDelay = Duration.zero, + this.triggerEvent, + this.frequency = PopupV3Frequency.onceSession, + this.cooldownMinutes = 0, + this.promoCodeListId, + this.targetScreens = const [], + this.design = const {}, + }); + + final int id; + final PopupV3Layout layout; + final PopupV3Placement placement; + final PopupV3Trigger trigger; + + /// Сколько сидеть на экране для `time_on_screen` (`trigger_value`, секунды). + final Duration triggerDelay; + + /// Имя события для `track_event`. + final String? triggerEvent; + final PopupV3Frequency frequency; + final double cooldownMinutes; + + /// Список промокодов: код запрашивается до показа. + final String? promoCodeListId; + + /// Коды экранов; пусто — любой экран. + final List targetScreens; + + /// Опубликованный документ design как есть. + final Map design; + + /// Окно или полный экран — слот «одна модалка». + bool get isModal => layout != PopupV3Layout.banner; + + /// Подходит ли экран [screen]: пустой список — любой, `null` (экран ещё не открыт) + /// подходит только пустому списку. + bool matchesScreen(String? screen) => + targetScreens.isEmpty || + (screen != null && targetScreens.contains(screen)); + + /// Нужен ли персональный промокод до показа: задан список и в дизайне есть + /// `{{promo_code}}` или элемент промокода не со статическим кодом. + bool get needsPromoCode { + if (promoCodeListId == null) return false; + final elements = design['elements']; + if (elements is List) { + for (final element in elements) { + if (element is Map && + element['type'] == 'promoCode' && + (element['style'] is! Map || + (element['style'] as Map)['promoSource'] != 'static')) { + return true; + } + } + } + return _hasPromoToken(design); + } + + static bool _hasPromoToken(Object? value) { + if (value is String) return _promoToken.hasMatch(value); + if (value is Map) return value.values.any(_hasPromoToken); + if (value is List) return value.any(_hasPromoToken); + return false; + } + + /// Попап из JSON или `null` с причиной в [onSkip]: нет id, неизвестный для mobile + /// макет или триггер. + static PopupV3? tryParse( + Object? json, { + void Function(Object? id, String reason)? onSkip, + }) { + if (json is! Map) { + onSkip?.call(null, 'not an object'); + return null; + } + final rawId = json['id']; + final id = rawId is int + ? rawId + : rawId is num + ? rawId.toInt() + : int.tryParse('${rawId ?? ''}'.trim()); + if (id == null) { + onSkip?.call(rawId, 'no id'); + return null; + } + final layout = PopupV3Layout.parse(json['layout']); + if (layout == null) { + onSkip?.call(id, 'unknown layout ${json['layout']}'); + return null; + } + final trigger = PopupV3Trigger.parse(json['trigger_type']); + if (trigger == null) { + onSkip?.call(id, 'unknown trigger ${json['trigger_type']}'); + return null; + } + final screens = json['target_screens']; + final design = json['design']; + final seconds = cssNum(json['trigger_value'], 0); + return PopupV3( + id: id, + layout: layout, + placement: layout == PopupV3Layout.banner + ? (json['placement'] == 'bottom' + ? PopupV3Placement.bottom + : PopupV3Placement.top) + : PopupV3Placement.center, + trigger: trigger, + triggerDelay: Duration( + milliseconds: (seconds < 0 ? 0 : seconds * 1000).round(), + ), + triggerEvent: cssPresent(json['trigger_event'])?.trim(), + frequency: PopupV3Frequency.parse(json['frequency']), + cooldownMinutes: cssNum(json['cooldown_minutes'], 0), + promoCodeListId: cssPresent(json['promo_code_list_id'])?.trim(), + targetScreens: screens is List + ? [ + for (final screen in screens) + if (cssPresent(screen) case final name?) name.trim(), + ] + : const [], + design: design is Map + ? Map.from(design) + : const {}, + ); + } + + @override + String toString() => 'PopupV3($id, ${layout.wire}, ${trigger.wire})'; +} + +/// Попап, исключённый сервером (`excluded` с `debug=1`). +typedef PopupV3Excluded = ({Object? id, String reason}); + +/// Список попапов: срок кеша, попапы канала mobile, исключённые сервером и +/// пропущенные приложением. +class PopupsV3List { + const PopupsV3List({ + required this.ttl, + required this.popups, + this.excluded = const [], + this.skipped = const {}, + }); + + /// Срок кеша по умолчанию — и для пустого списка после ошибки 4xx. + static const Duration defaultTtl = Duration(seconds: 300); + + static const PopupsV3List empty = PopupsV3List( + ttl: defaultTtl, + popups: [], + ); + + final Duration ttl; + final List popups; + final List excluded; + + /// Пропущенные приложением: id → причина. + final Map skipped; + + /// `payload` ответа списка: `ttl` (числом или строкой; не больше нуля — 300), + /// `popups`, `excluded`. + static PopupsV3List parse(Map payload) { + final seconds = cssNum(payload['ttl'], 0); + final skipped = {}; + final popups = []; + final raw = payload['popups']; + if (raw is List) { + for (final item in raw) { + final popup = PopupV3.tryParse( + item, + onSkip: (id, reason) => skipped[id] = reason, + ); + if (popup != null) popups.add(popup); + } + } + final excluded = payload['excluded']; + return PopupsV3List( + ttl: seconds > 0 + ? Duration(milliseconds: (seconds * 1000).round()) + : defaultTtl, + popups: popups, + excluded: excluded is List + ? [ + for (final item in excluded) + if (item is Map) + (id: item['id'], reason: cssString(item['reason'])), + ] + : const [], + skipped: skipped, + ); + } +} diff --git a/lib/src/popups_v3/popup_v3_values.dart b/lib/src/popups_v3/popup_v3_values.dart new file mode 100644 index 0000000..12d0997 --- /dev/null +++ b/lib/src/popups_v3/popup_v3_values.dart @@ -0,0 +1,43 @@ +/// Разбор значений документа попапа v3: числа, флаги и строки приходят как попало — +/// числом, строкой, `null`. Правила — как у компилятора дизайна на сервере +/// (`Context#num`, `presence`), чтобы приложение и сайт рисовали одно и то же. +library; + +import '../json_number.dart'; + +final RegExp _leadingNumber = RegExp(r'^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?'); + +/// Число [value] или [fallback]: число, строка с числом в начале (`"12"`, `" 7 "`, +/// `"12px"` → 12, как `parseFloat`). Пусто, `null`, булево и прочее — [fallback]. +double cssNum(Object? value, double fallback) { + if (value is num) return value.isFinite ? value.toDouble() : fallback; + if (value is String) { + final match = _leadingNumber.firstMatch(value.trim()); + if (match == null) return fallback; + return double.tryParse(match.group(0)!) ?? fallback; + } + return fallback; +} + +/// Флаг: `true`/`"true"`/`1` и `false`/`"false"`/`0`; иначе `null`. +bool? cssBool(Object? value) => toBoolOrNull(value); + +/// Строка с содержимым (не пустая и не из одних пробелов) — как `presence` в Ruby; +/// число — строкой. Иначе `null`. +String? cssPresent(Object? value) { + final text = value is String + ? value + : value is num + ? (value == value.roundToDouble() ? '${value.toInt()}' : '$value') + : null; + if (text == null || text.trim().isEmpty) return null; + return text; +} + +/// Строка как есть (`to_s`): строка, число строкой, иначе пустая. +String cssString(Object? value) => + value is String ? value : (cssPresent(value) ?? ''); + +/// Одно из [allowed] или `null`. +String? cssEnum(Object? value, List allowed) => + value is String && allowed.contains(value) ? value : null; diff --git a/lib/src/popups_v3/popups_v3.dart b/lib/src/popups_v3/popups_v3.dart new file mode 100644 index 0000000..ef9cc77 --- /dev/null +++ b/lib/src/popups_v3/popups_v3.dart @@ -0,0 +1,302 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import '../multi_instance/rees46.dart'; +import '../personalization_sdk.dart'; +import '../popups/popup_presenter.dart'; +import '../profile/profile_params.dart'; +import '../sdk_init_config.dart'; +import '../stories/stories_response.dart'; +import '../subscriptions/manage_subscription_params.dart'; +import '../ui/components/personalization_product.dart'; +import '../ui/popups_v3/popup_v3_host.dart'; +import '../ui/widgets/stories_api_v3.dart'; +import '../ui/widgets/stories_polls_api.dart'; +import 'popups_v3_api.dart'; +import 'popups_v3_engine.dart'; +import 'popups_v3_frequency.dart'; +import 'popups_v3_hooks.dart'; + +/// Попапы v3 магазина: `sdk.popups`. +extension PersonalizationPopupsV3 on PersonalizationSdk { + /// Попапы нового конструктора (документ design) этого магазина. + PopupsV3 get popups => PopupsV3.of(this); +} + +/// Попапы нового конструктора: движок (список, триггеры, частота, события) и рендер +/// документа design. Один на магазин. +/// +/// Спит, пока хост его не включил: без [enabled] ни одного запроса. Включённый работает, +/// если `/init` вернул флаг `popups_v3` или хост задал [ignoreInitFlag]. Флаг из `/init` +/// во Flutter пока не приходит (плагин собран против опубликованных нативных SDK), поэтому +/// приложение, которое хочет попапы, ставит оба. +/// +/// Хост сообщает экраны — [screenOpened] с кодом, который маркетолог пишет в +/// `target_screens` (или [PersonalizationScreenObserver] на навигаторе), — и может +/// показать попап вручную ([show]). С `enableAutoPopupPresentation: false` в init +/// попапы по триггерам пропускаются (с записью в лог), ручной показ работает. +class PopupsV3 with WidgetsBindingObserver implements PopupsV3Listener { + PopupsV3._(this._shop, PersonalizationSdk sdk) : _sdk = sdk { + engine = PopupsV3Engine( + sdk: sdk, + platform: _SdkPlatform(this), + presenter: PopupV3Host(), + storage: PopupsV3PreferencesStorage(_shop.isEmpty ? 'default' : _shop), + logTag: _shop, + ); + // Автопоказ выключен (в init или на ходу) — триггеры молчат, ручной [show] + // показывает. + engine.autoPresentation = () => _sdk.enableAutoPopupPresentation; + PopupsV3Hooks.listen(sdk.tracking, this); + // Окно одно на экране со старыми попапами: старый ждёт закрытия окна v3, окно v3 + // — закрытия старого. + PopupPresenter.heldElsewhere = () => + PopupsV3Slots.isTaken(PopupsV3Slots.modal); + PopupPresenter.onIdle = PopupsV3Slots.notify; + } + + static final Map _byShop = {}; + + /// Попапы магазина [sdk]. Переинициализированный магазин (новый инстанс с тем же + /// `shopId`) получает те же попапы с теми же настройками. + static PopupsV3 of(PersonalizationSdk sdk) { + final shop = _shopOf(sdk); + final popups = _byShop[shop]; + if (popups == null) return _byShop[shop] = PopupsV3._(shop, sdk); + if (!identical(popups._sdk, sdk)) popups._rebind(sdk); + return popups; + } + + static String _shopOf(PersonalizationSdk sdk) { + final own = sdk.shopId; + if (own != null && own.isNotEmpty) return own; + final live = REES46.liveShopIds; + return live.length == 1 ? live.single : ''; + } + + final String _shop; + PersonalizationSdk _sdk; + + /// Движок попапов магазина. + late final PopupsV3Engine engine; + + bool _enabled = false; + bool _ignoreInitFlag = false; + bool? _initFlag; + bool _observing = false; + + /// Включить попапы v3. Выключенные не делают ни одного запроса. + bool get enabled => _enabled; + + set enabled(bool value) { + _enabled = value; + _update(); + } + + /// Работать без флага `popups_v3` из `/init` (во Flutter он пока не приходит). + bool get ignoreInitFlag => _ignoreInitFlag; + + set ignoreInitFlag(bool value) { + _ignoreInitFlag = value; + _update(); + } + + /// Флаг `popups_v3` из ответа `/init`; `null` — не приходил. + bool? get initFlag => _initFlag; + + set initFlag(bool? value) { + _initFlag = value; + _update(); + } + + /// Работает ли движок сейчас. + bool get active => _enabled && (_initFlag == true || _ignoreInitFlag); + + /// Хост ЛК (API попапов, событий и опросов) без схемы; по умолчанию `app.rees46.ru`. + String get appHost => engine.appHost; + + set appHost(String value) { + final host = StoriesApiV3.host(value) ?? 'app.rees46.ru'; + if (host == engine.appHost) return; + engine.appHost = host; + if (active) unawaited(engine.refresh(force: true)); + } + + /// Тестовый режим: попапы со статусом «Тест», показы не пишутся в частоту. + bool get testMode => engine.testMode; + + set testMode(bool value) { + if (value == engine.testMode) return; + engine.testMode = value; + if (active) unawaited(engine.refresh(force: true)); + } + + /// `debug=1` в запросе списка и каждое решение движка в лог. + bool get debug => engine.debug; + + set debug(bool value) => engine.debug = value; + + /// Обработчик ссылок попапов (кнопка-ссылка, ссылка текста и картинки, ссылка + /// применения промокода, ссылка товара) — после события `click`. `true` — ссылку + /// открыл обработчик: попап закрывается без события `close`, как после перехода. + /// `false`, исключение или нет обработчика — ссылку открывает система, попап + /// остаётся. + bool Function(String url)? get onLink => engine.onLink; + + set onLink(bool Function(String url)? handler) => engine.onLink = handler; + + /// Нажатие на товар блока рекомендаций в попапе (после события `click`). `true` — + /// товар открыл обработчик: попап закрывается без события `close`, как после + /// перехода. `false`, исключение или нет обработчика — открывается ссылка товара + /// (`deeplink`, иначе `url`), как любая ссылка попапа ([onLink]). + bool Function(PersonalizationProduct product)? get onProductClick => + engine.onProductClick; + + set onProductClick(bool Function(PersonalizationProduct product)? handler) => + engine.onProductClick = handler; + + /// Открыт экран [name] — код экрана, который маркетолог указывает в `target_screens`. + void screenOpened(String name) => engine.screenOpened(name); + + /// Показать попап [id] вручную: без триггера, экранов и частоты (и без флага из + /// `/init`, но только включённым). Показывает и при выключенном в init + /// `enableAutoPopupPresentation` — тот глушит только автоматические показы. + Future show(int id) { + if (!_enabled) { + debugPrint('PersonalizationPopupsV3: show($id) — popups are not enabled'); + return Future.value(); + } + return engine.show(id); + } + + void _update() { + if (active) { + if (!_observing) { + WidgetsBinding.instance.addObserver(this); + _observing = true; + } + engine.apiHost = _apiHost; + unawaited(engine.start()); + } else if (engine.active) { + engine.stop(); + if (_observing) { + WidgetsBinding.instance.removeObserver(this); + _observing = false; + } + } + } + + void _rebind(PersonalizationSdk sdk) { + PopupsV3Hooks.listen(_sdk.tracking, null); + _sdk = sdk; + engine.sdk = sdk; + PopupsV3Hooks.listen(sdk.tracking, this); + engine.apiHost = _apiHost; + } + + /// API-хост магазина из init (промокоды, сегменты). + String get _apiHost => + StoriesApiV3.host( + PopupsV3Hooks.configOf(_sdk.tracking)?.apiDomain ?? '', + ) ?? + 'api.rees46.ru'; + + @override + void onInitialized(SdkInitConfig config) { + engine.apiHost = _apiHost; + if (active) unawaited(engine.refresh()); + } + + @override + void onTrackEvent(String event) => engine.onTrackEvent(event); + + @override + void onContextChanged(String type, String action, Object? data) => + engine.onContextChanged(type, action, data); + + @override + void onPurchase() => engine.onPurchase(); + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + switch (state) { + case AppLifecycleState.resumed: + engine.onForeground(); + case AppLifecycleState.paused: + case AppLifecycleState.hidden: + engine.onBackground(); + case AppLifecycleState.inactive: + case AppLifecycleState.detached: + break; + } + } + + /// Тестам: забыть все магазины. + @visibleForTesting + static void reset() { + for (final popups in _byShop.values) { + popups.engine.stop(); + if (popups._observing) { + WidgetsBinding.instance.removeObserver(popups); + } + PopupsV3Hooks.listen(popups._sdk.tracking, null); + } + _byShop.clear(); + } +} + +/// Движку — SDK магазина: `did`/`sid` через мост, ссылки, профиль, подписка, опросы. +class _SdkPlatform implements PopupsV3Platform { + _SdkPlatform(this._popups); + + final PopupsV3 _popups; + + PersonalizationSdk get _sdk => _popups._sdk; + + static const Duration _poll = Duration(milliseconds: 200); + static const Duration _timeout = Duration(seconds: 15); + + @override + Future identity() async { + final shop = PopupsV3._shopOf(_sdk); + if (shop.isEmpty) throw StateError('popups v3: unknown shop_id'); + for (var waited = Duration.zero; ; waited += _poll) { + String? did; + var sid = ''; + try { + did = await _sdk.getDid(); + sid = await _sdk.getSid(); + } catch (_) { + // Инстанс ещё не готов — спросим снова. + } + if (did != null && did.isNotEmpty && sid.isNotEmpty) { + return (shopId: shop, did: did, sid: sid); + } + if (waited >= _timeout) { + throw TimeoutException('popups v3: no did or sid', _timeout); + } + await Future.delayed(_poll); + } + } + + @override + Future openUrl(String url) => _sdk.openUrl(url); + + @override + Future manageSubscription(ManageSubscriptionParams params) => + _sdk.manageSubscription(params); + + @override + Future setProfile(ProfileParams params) => _sdk.setProfile(params); + + @override + Future review(String kind, Map body) async { + final type = switch (kind) { + 'csat' => StoryPollType.csat, + 'ces' => StoryPollType.ces, + _ => StoryPollType.nps, + }; + await StoriesPollsApi(_sdk, _popups.appHost).review(type, body); + } +} diff --git a/lib/src/popups_v3/popups_v3_api.dart b/lib/src/popups_v3/popups_v3_api.dart new file mode 100644 index 0000000..15ff97d --- /dev/null +++ b/lib/src/popups_v3/popups_v3_api.dart @@ -0,0 +1,333 @@ +import 'dart:async'; +import 'dart:convert'; + +import '../ui/widgets/stories_api_v3.dart'; +import 'popup_v3.dart'; +import 'popup_v3_values.dart'; + +/// `shop_id`, `did` и `sid`, с которыми идут запросы попапов. +typedef PopupsV3Identity = ({String shopId, String did, String sid}); + +/// Событие попапа для `POST /api/v3/storefront/popups/:id/events`. +enum PopupV3Event { + show('show'), + close('close'), + click('click'), + submit('submit'), + subscribe('subscribe'), + + /// Зарезервировано под колесо фортуны, на mobile не отправляется. + prize('prize'); + + const PopupV3Event(this.wire); + + final String wire; +} + +/// Чем кончился запрос списка. +enum PopupsV3ListOutcome { + /// Список пришёл. + success, + + /// 4xx или не тот ответ: кешируем пустой список на 300 с. + clientError, + + /// Нет сети или 5xx: не кешируем, спросим при следующем поводе. + failure, +} + +/// Ответ на запрос списка. +typedef PopupsV3ListResult = ({ + PopupsV3ListOutcome outcome, + PopupsV3List list, + String? error, +}); + +/// HTTP попапов v3: список, один попап, события — на хосте ЛК (`app.rees46.ru`); +/// промокод и сегмент — на API-хосте магазина (`api.rees46.ru`). +/// +/// Транспорт общий со сторис API v3 ([StoriesApiV3.send]): тот же шов для тестов и +/// офлайн-демо. +class PopupsV3Api { + PopupsV3Api({StoriesV3Send? send, DateTime Function()? now}) + : _send = + send ?? ((method, uri, body) => StoriesApiV3.send(method, uri, body)), + _now = now ?? DateTime.now; + + final StoriesV3Send _send; + final DateTime Function() _now; + + /// Ожидание ответа на любой запрос. + static const Duration requestTimeout = Duration(seconds: 15); + + /// Ожидание промокода: дольше попап не ждёт. + static const Duration promoTimeout = Duration(seconds: 10); + + /// Сколько помнить выданный промокод списка. + static const Duration promoCacheTtl = Duration(hours: 2); + + /// Пауза отправки событий после 429. + static const Duration eventsPause = Duration(seconds: 60); + + final Map _promoCodes = + {}; + DateTime? _eventsPausedUntil; + + /// `GET https://{appHost}/api/v3/storefront/popups?shop_id&did&sid&channel=mobile` + /// `[&testmode=true][&debug=1]`. + static Uri listUri( + String appHost, + PopupsV3Identity id, { + bool testMode = false, + bool debug = false, + }) => StoriesApiV3.apiUri( + appHost, + const ['storefront', 'popups'], + { + 'shop_id': id.shopId, + 'did': id.did, + 'sid': id.sid, + 'channel': 'mobile', + if (testMode) 'testmode': 'true', + if (debug) 'debug': '1', + }, + ); + + /// `GET https://{appHost}/api/v3/storefront/popups/:id?shop_id&did&sid[&testmode=true]`. + static Uri oneUri( + String appHost, + int popupId, + PopupsV3Identity id, { + bool testMode = false, + }) => StoriesApiV3.apiUri( + appHost, + ['storefront', 'popups', '$popupId'], + { + 'shop_id': id.shopId, + 'did': id.did, + 'sid': id.sid, + if (testMode) 'testmode': 'true', + }, + ); + + /// `POST https://{appHost}/api/v3/storefront/popups/:id/events`. + static Uri eventsUri(String appHost, int popupId) => StoriesApiV3.apiUri( + appHost, + ['storefront', 'popups', '$popupId', 'events'], + ); + + /// Тело события: `channel` — только у `subscribe`. + static Map eventBody( + PopupsV3Identity id, + PopupV3Event event, { + String? channel, + }) => { + 'shop_id': id.shopId, + 'did': id.did, + 'sid': id.sid, + 'event': event.wire, + if (event == PopupV3Event.subscribe && channel != null) 'channel': channel, + }; + + /// `GET https://{apiHost}/promo_codes/fetch?shop_id&did&sid&id`. + static Uri promoUri(String apiHost, PopupsV3Identity id, String listId) => + Uri.parse('https://$apiHost').replace( + pathSegments: const ['promo_codes', 'fetch'], + queryParameters: { + 'shop_id': id.shopId, + 'did': id.did, + 'sid': id.sid, + 'id': listId, + }, + ); + + /// `POST https://{apiHost}/segments/add`. + static Uri segmentUri(String apiHost) => Uri.parse( + 'https://$apiHost', + ).replace(pathSegments: const ['segments', 'add']); + + /// Список попапов. Ответ не `success`, без `payload` или 4xx — пустой список с + /// [PopupsV3ListOutcome.clientError]; нет сети или 5xx — [PopupsV3ListOutcome.failure]. + Future list( + String appHost, + PopupsV3Identity id, { + bool testMode = false, + bool debug = false, + }) async { + final StoriesV3Response response; + try { + response = await _send( + 'GET', + listUri(appHost, id, testMode: testMode, debug: debug), + null, + ).timeout(requestTimeout); + } catch (error) { + return ( + outcome: PopupsV3ListOutcome.failure, + list: PopupsV3List.empty, + error: '$error', + ); + } + if (response.status >= 500) { + return ( + outcome: PopupsV3ListOutcome.failure, + list: PopupsV3List.empty, + error: 'HTTP ${response.status}: ${_short(response.body)}', + ); + } + final json = _json(response.body); + final payload = json?['payload']; + if (response.status >= 300 || + json?['status'] != 'success' || + payload is! Map) { + return ( + outcome: PopupsV3ListOutcome.clientError, + list: PopupsV3List.empty, + error: 'HTTP ${response.status}: ${_short(response.body)}', + ); + } + return ( + outcome: PopupsV3ListOutcome.success, + list: PopupsV3List.parse(Map.from(payload)), + error: null, + ); + } + + /// Один попап для ручного показа; нет его (404) или ошибка — `null` и причина в + /// [onError]. + Future one( + String appHost, + int popupId, + PopupsV3Identity id, { + bool testMode = false, + void Function(String error)? onError, + }) async { + try { + final response = await _send( + 'GET', + oneUri(appHost, popupId, id, testMode: testMode), + null, + ).timeout(requestTimeout); + final json = _json(response.body); + final payload = json?['payload']; + if (response.status < 200 || + response.status >= 300 || + json?['status'] != 'success' || + payload is! Map) { + onError?.call('HTTP ${response.status}: ${_short(response.body)}'); + return null; + } + String? skipped; + final popup = PopupV3.tryParse( + payload['popup'], + onSkip: (_, reason) => skipped = reason, + ); + if (popup == null) onError?.call(skipped ?? 'no popup'); + return popup; + } catch (error) { + onError?.call('$error'); + return null; + } + } + + /// Событие [event] попапа [popupId]. «Выстрелил и забыл»: один повтор при ошибке + /// сети или 5xx, 4xx не повторяем, после 429 события минуту не отправляются. + /// Возвращает код ответа (`null` — не отправлено) для лога. + Future event( + String appHost, + int popupId, + PopupsV3Identity id, + PopupV3Event event, { + String? channel, + }) async { + final pausedUntil = _eventsPausedUntil; + if (pausedUntil != null && _now().isBefore(pausedUntil)) return null; + final uri = eventsUri(appHost, popupId); + final body = jsonEncode(eventBody(id, event, channel: channel)); + for (var attempt = 0; attempt < 2; attempt++) { + int? status; + try { + status = (await _send( + 'POST', + uri, + body, + ).timeout(requestTimeout)).status; + } catch (_) { + status = null; + } + if (status == 429) { + _eventsPausedUntil = _now().add(eventsPause); + return status; + } + if (status != null && status < 500) return status; + } + return null; + } + + /// Персональный промокод из списка [listId]; нет кода, ошибка или нет ответа за + /// [promoTimeout] — `null`. Выданный код помнится [promoCacheTtl]. + Future promoCode( + String apiHost, + PopupsV3Identity id, + String listId, + ) async { + final cached = _promoCodes[listId]; + if (cached != null && _now().isBefore(cached.expires)) return cached.code; + try { + final response = await _send( + 'GET', + promoUri(apiHost, id, listId), + null, + ).timeout(promoTimeout); + if (response.status < 200 || response.status >= 300) return null; + final code = cssPresent(_json(response.body)?['code'])?.trim(); + if (code == null) return null; + _promoCodes[listId] = (code: code, expires: _now().add(promoCacheTtl)); + return code; + } catch (_) { + return null; + } + } + + /// Добавить устройство в сегмент [segmentId] (`segments/add` по `did`). Ошибка — + /// исключение. + Future segmentAdd( + String apiHost, + PopupsV3Identity id, + String segmentId, + ) async { + final number = int.tryParse(segmentId); + final response = await _send( + 'POST', + segmentUri(apiHost), + jsonEncode({ + 'shop_id': id.shopId, + 'did': id.did, + 'sid': id.sid, + 'segment_id': number ?? segmentId, + }), + ).timeout(requestTimeout); + final json = _json(response.body); + if (response.status < 200 || + response.status >= 300 || + json?['status'] == 'error' || + json?['status'] == 'fail') { + throw StoriesV3Exception( + 'segments/add HTTP ${response.status}: ${_short(response.body)}', + status: response.status, + ); + } + } + + static Map? _json(String body) { + try { + final json = jsonDecode(body); + return json is Map ? Map.from(json) : null; + } on FormatException { + return null; + } + } + + static String _short(String body) => + body.length > 200 ? '${body.substring(0, 200)}…' : body; +} diff --git a/lib/src/popups_v3/popups_v3_engine.dart b/lib/src/popups_v3/popups_v3_engine.dart new file mode 100644 index 0000000..f394ff5 --- /dev/null +++ b/lib/src/popups_v3/popups_v3_engine.dart @@ -0,0 +1,879 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; + +import '../personalization_sdk.dart'; +import '../popups/popup_presenter.dart'; +import '../profile/profile_params.dart'; +import '../subscriptions/manage_subscription_params.dart'; +import '../ui/components/personalization_product.dart'; +import 'popup_v3.dart'; +import 'popups_v3_api.dart'; +import 'popups_v3_frequency.dart'; + +/// Часы и таймеры движка — тесты подменяют. +abstract interface class PopupsV3Clock { + DateTime now(); + + Timer timer(Duration delay, void Function() callback); +} + +class _SystemClock implements PopupsV3Clock { + const _SystemClock(); + + @override + DateTime now() => DateTime.now(); + + @override + Timer timer(Duration delay, void Function() callback) => + Timer(delay, callback); +} + +/// Что движку нужно от SDK: идентичность запросов, ссылки, профиль, подписка, отзыв. +abstract interface class PopupsV3Platform { + /// `shop_id`, `did` и `sid`; SDK ещё не готов — ждёт, не дождался — ошибка. + Future identity(); + + Future openUrl(String url); + + Future manageSubscription(ManageSubscriptionParams params); + + Future setProfile(ProfileParams params); + + /// Оценка шкалы [kind] (`nps`, `csat`, `ces`) с телом [body] на API v3 опросов. + Future review(String kind, Map body); +} + +/// Показанный на экране попап. +abstract interface class PopupsV3Shown { + /// Завершается, когда попап ушёл с экрана — по любой причине. + Future get closed; + + /// Убрать попап без события `close`. + void dismiss(); +} + +/// Рендер попапов: рисует [popup] и отдаёт действия его элементов в [actions]. +abstract interface class PopupsV3Presenter { + /// Показать попап с витринными переменными [variables] (`promo_code`). `null` — + /// показать не удалось (нет навигатора). + Future present( + PopupV3 popup, + Map variables, + PopupV3Actions actions, + ); +} + +/// Данные формы профиля попапа. +class PopupV3ProfileSubmission { + const PopupV3ProfileSubmission({ + this.email, + this.phone, + this.firstName, + this.lastName, + this.birthday, + this.gender, + this.custom = const {}, + this.consentFields = const [], + this.segmentId, + }); + + final String? email; + final String? phone; + final String? firstName; + final String? lastName; + + /// `YYYY-MM-DD`. + final String? birthday; + + /// `m` или `f`. + final String? gender; + + /// Свои свойства клиента: ключ → значение. + final Map custom; + + /// Флаги подписки, если согласие отмечено (`email_bulk` …). + final List consentFields; + final String? segmentId; +} + +/// Действия элементов показанного попапа: события, ссылки, формы, опрос. +abstract interface class PopupV3Actions { + /// Инстанс SDK попапа — для блока рекомендаций. + PersonalizationSdk get sdk; + + /// Событие попапа ([PopupV3Event.close] шлёт рендер при любом закрытии). + void event(PopupV3Event event, {String? channel}); + + /// Открыть ссылку: сначала обработчик хоста, потом система. Пустая ссылка, + /// `javascript:` и `data:` не открываются. `true` — ссылку открыл хост, попап + /// закрывается без события `close`; ушла системе — остаётся. + bool openLink(String url); + + /// Нажатие на товар блока рекомендаций: сначала обработчику хоста, не открыл он — + /// ссылка товара ([openLink]). `true` — товар или его ссылку открыл хост, попап + /// закрывается без события `close`. + bool openProduct(PersonalizationProduct product); + + /// Подписка на email с флагами [consentFields] и сегментом; ошибка — исключение. + Future subscribeEmail({ + required String email, + required List consentFields, + String? segmentId, + }); + + /// Форма профиля; ошибка — исключение. + Future submitProfile(PopupV3ProfileSubmission submission); + + /// Оценка опроса [kind] (`nps`, `csat`, `ces`) в кампанию [code]; ошибка — исключение. + Future review({ + required String kind, + required String code, + required int rate, + String? comment, + }); +} + +/// Слоты экрана, общие на процесс: окно одно (вместе со старыми попапами), баннер — +/// по одному сверху и снизу. +abstract final class PopupsV3Slots { + static const String modal = 'modal'; + + static final Map _taken = {}; + static final Set _listeners = {}; + + /// Занят ли экран старым попапом. + static bool Function() legacyModal = () => PopupPresenter.isPresenting; + + static String of(PopupV3 popup) => + popup.isModal ? modal : 'banner_${popup.placement.name}'; + + static bool isFree(String slot) => + !_taken.containsKey(slot) && !(slot == modal && legacyModal()); + + static bool isTaken(String slot) => _taken.containsKey(slot); + + static void take(String slot, Object owner) => _taken[slot] = owner; + + static void release(String slot, Object owner) { + if (!identical(_taken[slot], owner)) return; + _taken.remove(slot); + if (slot == modal) PopupPresenter.resume(); + notify(); + } + + /// Слот освободился: движки показывают свои очереди. + static void notify() { + for (final listener in _listeners.toList()) { + listener(); + } + } + + static void listen(void Function() listener) => _listeners.add(listener); + + static void unlisten(void Function() listener) => _listeners.remove(listener); + + @visibleForTesting + static void reset() { + _taken.clear(); + _listeners.clear(); + legacyModal = () => PopupPresenter.isPresenting; + } +} + +typedef _ListCache = ({ + String sid, + bool testMode, + DateTime expires, + PopupsV3List list, +}); + +typedef _Open = ({PopupV3 popup, PopupsV3Shown shown, String slot}); + +/// Движок попапов v3 одного инстанса SDK: загрузка и кеш списка, экраны и триггеры, +/// частота, очередь на слот, промокод до показа, события. +class PopupsV3Engine { + PopupsV3Engine({ + required this.sdk, + required this.platform, + required this.presenter, + PopupsV3Api? api, + PopupsV3Storage? storage, + PopupsV3Clock? clock, + this.logTag = '', + }) : api = api ?? PopupsV3Api(), + clock = clock ?? const _SystemClock(), + frequency = PopupsV3FrequencyRules(storage ?? PopupsV3MemoryStorage()); + + /// Инстанс SDK магазина; переинициализация магазина подставляет новый. + PersonalizationSdk sdk; + final PopupsV3Platform platform; + final PopupsV3Presenter presenter; + final PopupsV3Api api; + final PopupsV3Clock clock; + final PopupsV3FrequencyRules frequency; + + /// Метка в логе (магазин). + final String logTag; + + /// Хост ЛК без схемы. + String appHost = 'app.rees46.ru'; + + /// API-хост магазина без схемы — промокоды и сегменты. + String apiHost = 'api.rees46.ru'; + + /// Тестовый режим: попапы со статусом «Тест», частота не пишется. + bool testMode = false; + + /// `debug=1` в списке и каждое решение движка в лог. + bool debug = false; + + /// Обработчик ссылок хоста: `true` — ссылку открыл он, попап закрывается без + /// события `close`. + bool Function(String url)? onLink; + + /// Нажатие на товар рекомендаций в попапе: `true` — товар открыл хост, иначе + /// открывается ссылка товара. + bool Function(PersonalizationProduct product)? onProductClick; + + /// Показывать ли попапы самим (`enableAutoPopupPresentation` из init); ручной показ + /// — всегда. + bool Function() autoPresentation = _autoPresentation; + + static bool _autoPresentation() => true; + + /// Сброс кеша после смены контекста — с такой задержкой. + static const Duration invalidateDelay = Duration(seconds: 2); + + /// Сколько событий `track_event` держать, пока список не пришёл, и как долго. + static const int bufferLimit = 20; + static const Duration bufferWindow = Duration(seconds: 10); + + bool _active = false; + String? _sid; + _ListCache? _cache; + Map _popups = {}; + bool _armed = false; + Future _loading = Future.value(); + + String? _screen; + int _screenSeq = 0; + DateTime? _screenAt; + final Set _screenEvaluated = {}; + final Map _screenTimers = {}; + bool _foreground = true; + + final List<({String event, DateTime at})> _buffer = + <({String event, DateTime at})>[]; + final Set _showing = {}; + final Map _open = {}; + final List<({PopupV3 popup, bool manual})> _queue = + <({PopupV3 popup, bool manual})>[]; + final Map _signatures = {}; + Timer? _invalidateTimer; + + /// Работает ли движок (хост включил, флаг или принудительное включение). + bool get active => _active; + + /// Текущий экран. + String? get screen => _screen; + + /// Попапы текущего списка. + List get popups => _popups.values.toList(); + + /// Показанные сейчас попапы. + List get openIds => _open.keys.toList(); + + /// Ждут слота. + List get queuedIds => [for (final item in _queue) item.popup.id]; + + /// Запустить: загрузить список и поставить триггеры. Повторный вызов — обновить. + Future start() { + if (!_active) { + _active = true; + PopupsV3Slots.listen(_processQueue); + } + return refresh(); + } + + /// Остановить: таймеры сняты, список забыт; показанные попапы остаются. + void stop() { + if (!_active) return; + _active = false; + PopupsV3Slots.unlisten(_processQueue); + _cancelScreenTimers(); + _invalidateTimer?.cancel(); + _invalidateTimer = null; + _popups = {}; + _armed = false; + _queue.clear(); + } + + /// Обновить список: кеш годен — из кеша, иначе запрос. Новая сессия — заново + /// триггеры запуска. Запросы идут по одному. + Future refresh({bool force = false}) { + final next = _loading.then((_) => _refresh(force)); + _loading = next.catchError((Object error) { + _log('list not loaded — $error', always: true); + }); + return _loading; + } + + Future _refresh(bool force) async { + if (!_active) return; + final id = await platform.identity(); + if (!_active) return; + if (_sid != id.sid) { + if (_sid != null) _log('new session ${id.sid}'); + _sid = id.sid; + _signatures.clear(); + // Новая сессия — и новая «страница» для частоты `every_page`. + frequency.newPage(); + } + final cache = _cache; + if (!force && + cache != null && + cache.sid == id.sid && + cache.testMode == testMode && + clock.now().isBefore(cache.expires)) { + _setList(cache.list); + return; + } + final result = await api.list( + appHost, + id, + testMode: testMode, + debug: debug, + ); + if (!_active) return; + switch (result.outcome) { + case PopupsV3ListOutcome.success: + _cache = ( + sid: id.sid, + testMode: testMode, + expires: clock.now().add(result.list.ttl), + list: result.list, + ); + case PopupsV3ListOutcome.clientError: + _log('list request failed: ${result.error}', always: true); + _cache = ( + sid: id.sid, + testMode: testMode, + expires: clock.now().add(PopupsV3List.defaultTtl), + list: PopupsV3List.empty, + ); + case PopupsV3ListOutcome.failure: + _log('list request failed: ${result.error}', always: true); + return; + } + _setList(result.list); + } + + void _setList(PopupsV3List list) { + for (final excluded in list.excluded) { + _log('popup ${excluded.id} excluded by the server: ${excluded.reason}'); + } + list.skipped.forEach((id, reason) => _log('popup $id skipped: $reason')); + + final next = { + for (final popup in list.popups) popup.id: popup, + }; + for (final id in _popups.keys) { + if (next.containsKey(id)) continue; + _screenTimers.remove(id)?.cancel(); + _queue.removeWhere((item) => item.popup.id == id && !item.manual); + } + _popups = next; + _armed = true; + _log('${next.length} popup(s) loaded'); + + // Запуск проверяется на каждой загрузке списка и на каждом открытом экране: + // повтор отсекает частота (`every_page` — раз на экран). + for (final popup in next.values) { + if (popup.trigger != PopupV3Trigger.appStart) continue; + _screenEvaluated.add(popup.id); + if (popup.matchesScreen(_screen)) { + _fire(popup); + } else { + _log('popup ${popup.id} waits for screen ${popup.targetScreens}'); + } + } + if (_screen != null) { + for (final popup in next.values) { + if (!_screenEvaluated.contains(popup.id)) _evaluateScreen(popup); + } + } + final since = clock.now().subtract(bufferWindow); + final buffered = _buffer.where((item) => !item.at.isBefore(since)).toList(); + _buffer.clear(); + for (final item in buffered) { + onTrackEvent(item.event); + } + } + + /// Открыт экран [name] — код, который маркетолог пишет в `target_screens`. + void screenOpened(String name) { + final screen = name.trim(); + if (screen.isEmpty) return; + _log('screen $screen'); + _screen = screen; + _screenSeq++; + _screenAt = clock.now(); + _screenEvaluated.clear(); + _cancelScreenTimers(); + frequency.newPage(); + if (!_active || !_armed) return; + for (final popup in _popups.values) { + _evaluateScreen(popup); + } + } + + void _evaluateScreen(PopupV3 popup) { + _screenEvaluated.add(popup.id); + if (!popup.matchesScreen(_screen)) return; + switch (popup.trigger) { + case PopupV3Trigger.appStart: + case PopupV3Trigger.screenOpen: + _fire(popup); + case PopupV3Trigger.timeOnScreen: + _startTimer(popup); + case PopupV3Trigger.trackEvent: + case PopupV3Trigger.manual: + break; + } + } + + void _startTimer(PopupV3 popup) { + if (!_foreground) return; + final since = clock.now().difference(_screenAt ?? clock.now()); + final left = popup.triggerDelay - since; + final seq = _screenSeq; + _screenTimers.remove(popup.id)?.cancel(); + _screenTimers[popup.id] = clock.timer( + left.isNegative ? Duration.zero : left, + () { + _screenTimers.remove(popup.id); + if (_active && _foreground && seq == _screenSeq) _fire(popup); + }, + ); + } + + void _cancelScreenTimers() { + for (final timer in _screenTimers.values) { + timer.cancel(); + } + _screenTimers.clear(); + } + + /// Приложение ушло в фон: таймеры «время на экране» сброшены. + void onBackground() { + _foreground = false; + _cancelScreenTimers(); + } + + /// Приложение вернулось: таймеры «время на экране» заново, список — если сменилась + /// сессия или истёк кеш. + void onForeground() { + if (_foreground) return; + _foreground = true; + _screenAt = clock.now(); + if (_active && _armed) { + for (final popup in _popups.values) { + if (popup.trigger == PopupV3Trigger.timeOnScreen && + popup.matchesScreen(_screen)) { + _startTimer(popup); + } + } + } + if (_active) unawaited(refresh()); + } + + /// Своё событие SDK [event] — триггер `track_event`. Экран должен подходить: событие + /// не ждёт экрана. Пока список не пришёл, последние события копятся. + void onTrackEvent(String event) { + if (!_active) return; + if (!_armed) { + _buffer.add((event: event, at: clock.now())); + if (_buffer.length > bufferLimit) { + _buffer.removeRange(0, _buffer.length - bufferLimit); + } + return; + } + for (final popup in _popups.values) { + if (popup.trigger != PopupV3Trigger.trackEvent || + popup.triggerEvent != event) { + continue; + } + if (popup.matchesScreen(_screen)) { + _fire(popup); + } else { + _log( + 'popup ${popup.id} skipped: screen $_screen is not in ${popup.targetScreens}', + ); + } + } + } + + /// Смена контекста клиента: кеш сбрасывается и список запрашивается заново через + /// [invalidateDelay]. Те же данные повторно в той же сессии кеш не сбрасывают. + void onContextChanged(String type, String action, Object? data) { + if (!_active) return; + String signature; + try { + signature = jsonEncode([action, data]); + } catch (_) { + signature = '${math.Random().nextDouble()}'; + } + if (_signatures[type] == signature) return; + _signatures[type] = signature; + _invalidate(); + } + + /// Покупка: список заново через [invalidateDelay]. + void onPurchase() { + if (_active) _invalidate(); + } + + void _invalidate() { + _invalidateTimer?.cancel(); + _invalidateTimer = clock.timer(invalidateDelay, () { + _invalidateTimer = null; + _log('list invalidated'); + _cache = null; + unawaited(refresh(force: true)); + }); + } + + /// Показать попап [id] вручную: без триггера, экранов и частоты; слот и промокод — + /// как обычно. + Future show(int id) async { + final PopupsV3Identity identity; + try { + identity = await platform.identity(); + } catch (error) { + _log('popup $id not loaded — $error', always: true); + return; + } + final popup = await api.one( + appHost, + id, + identity, + testMode: testMode, + onError: (error) => _log('popup $id not loaded — $error', always: true), + ); + if (popup != null) await _show(popup, manual: true); + } + + void _fire(PopupV3 popup) { + _log('popup ${popup.id} triggered (${popup.trigger.wire})'); + unawaited(_show(popup, manual: false)); + } + + Future _show(PopupV3 popup, {required bool manual}) async { + final id = popup.id; + if (_showing.contains(id) || _open.containsKey(id)) return; + _showing.add(id); + try { + if (!manual) { + final reason = await frequency.check( + popup, + now: clock.now(), + sid: _sid, + ); + if (reason != null) { + _log('popup $id skipped: $reason'); + return; + } + if (!autoPresentation()) { + _log( + 'popup $id skipped: automatic popup presentation is off', + always: true, + ); + return; + } + } + final slot = PopupsV3Slots.of(popup); + if (!PopupsV3Slots.isFree(slot)) { + _postpone(popup, manual, slot); + return; + } + final variables = {}; + if (popup.needsPromoCode) { + final code = await _promoCode(popup); + if (code == null) { + _log('popup $id skipped: no promo code', always: true); + return; + } + variables['promo_code'] = code; + } + // Пока ждали промокод, слот мог занять другой попап. + if (!PopupsV3Slots.isFree(slot)) { + _postpone(popup, manual, slot); + return; + } + PopupsV3Slots.take(slot, this); + final PopupsV3Shown? shown; + try { + shown = await presenter.present( + popup, + variables, + _EngineActions(this, popup), + ); + } catch (error) { + PopupsV3Slots.release(slot, this); + rethrow; + } + if (shown == null) { + PopupsV3Slots.release(slot, this); + _log('popup $id not shown: nothing to show it on', always: true); + return; + } + _open[id] = (popup: popup, shown: shown, slot: slot); + if (!manual) { + await frequency.record( + popup, + now: clock.now(), + sid: _sid, + testMode: testMode, + ); + } + _log('popup $id shown'); + sendEvent(popup, PopupV3Event.show); + unawaited( + shown.closed.whenComplete(() { + _open.remove(id); + PopupsV3Slots.release(slot, this); + }), + ); + } catch (error, stack) { + _log('popup $id failed — $error\n$stack', always: true); + } finally { + _showing.remove(id); + } + } + + void _postpone(PopupV3 popup, bool manual, String slot) { + _log('popup ${popup.id} postponed: $slot is busy'); + if (_queue.any((item) => item.popup.id == popup.id)) return; + _queue.add((popup: popup, manual: manual)); + } + + void _processQueue() { + if (_queue.isEmpty) return; + final queued = _queue.toList(); + _queue.clear(); + for (final item in queued) { + final current = item.manual ? item.popup : _popups[item.popup.id]; + if (current != null) unawaited(_show(current, manual: item.manual)); + } + } + + Future _promoCode(PopupV3 popup) async { + try { + final identity = await platform.identity(); + return await api.promoCode(apiHost, identity, popup.promoCodeListId!); + } catch (error) { + _log('promo code of popup ${popup.id} — $error', always: true); + return null; + } + } + + /// Событие [event] попапа [popup] — «выстрелил и забыл». + void sendEvent(PopupV3 popup, PopupV3Event event, {String? channel}) { + unawaited(() async { + try { + final identity = await platform.identity(); + final status = await api.event( + appHost, + popup.id, + identity, + event, + channel: channel, + ); + _log( + 'event ${event.wire}${channel == null ? '' : ' ($channel)'} of popup ' + '${popup.id}: ${status == null ? 'not sent' : 'HTTP $status'}', + ); + } catch (error) { + _log('event ${event.wire} of popup ${popup.id} — $error', always: true); + } + }()); + } + + /// Закрыть все показанные попапы этого движка без событий. + void dismissAll() { + for (final open in _open.values.toList()) { + open.shown.dismiss(); + } + } + + void _log(String message, {bool always = false}) { + if (!always && !debug) return; + debugPrint( + 'PersonalizationPopupsV3${logTag.isEmpty ? '' : ' [$logTag]'}: $message', + ); + } + + /// Запись в лог от действий попапа. + void log(String message, {bool always = false}) => + _log(message, always: always); +} + +final RegExp _unsafeScheme = RegExp( + r'^\s*(javascript|data|vbscript):', + caseSensitive: false, +); + +/// Ссылка, которую можно открыть: не пустая и не `javascript:`/`data:`. +String? popupV3SafeLink(String? url) { + final link = url?.trim() ?? ''; + if (link.isEmpty || _unsafeScheme.hasMatch(link)) return null; + return link; +} + +class _EngineActions implements PopupV3Actions { + _EngineActions(this.engine, this.popup); + + final PopupsV3Engine engine; + final PopupV3 popup; + + @override + PersonalizationSdk get sdk => engine.sdk; + + @override + void event(PopupV3Event event, {String? channel}) => + engine.sendEvent(popup, event, channel: channel); + + @override + bool openLink(String url) { + final link = popupV3SafeLink(url); + if (link == null) return false; + final handler = engine.onLink; + if (handler != null) { + try { + if (handler(link)) return true; + } catch (error) { + engine.log('link handler, $link — $error', always: true); + } + } + unawaited(_openUrl(link)); + return false; + } + + Future _openUrl(String link) async { + try { + final opened = await engine.platform.openUrl(link); + if (!opened) engine.log('nothing opens $link', always: true); + } catch (error) { + engine.log('link $link — $error', always: true); + } + } + + @override + bool openProduct(PersonalizationProduct product) { + final handler = engine.onProductClick; + if (handler != null) { + try { + if (handler(product)) return true; + } catch (error) { + engine.log('product ${product.id} — $error', always: true); + } + } + final deeplink = product.deeplink?.trim() ?? ''; + final link = deeplink.isNotEmpty ? deeplink : product.url; + return link != null && openLink(link); + } + + @override + Future subscribeEmail({ + required String email, + required List consentFields, + String? segmentId, + }) async { + await engine.platform.manageSubscription( + _consent(consentFields, email: email), + ); + await _segment(segmentId); + event(PopupV3Event.subscribe, channel: 'email'); + event(PopupV3Event.submit); + } + + @override + Future submitProfile(PopupV3ProfileSubmission submission) async { + await engine.platform.setProfile( + ProfileParams( + email: submission.email, + phone: submission.phone, + firstName: submission.firstName, + lastName: submission.lastName, + birthday: submission.birthday, + gender: switch (submission.gender) { + 'm' => ProfileGender.male, + 'f' => ProfileGender.female, + _ => null, + }, + customProperties: submission.custom.isEmpty ? null : submission.custom, + ), + ); + if (submission.consentFields.isNotEmpty) { + if (submission.email != null || submission.phone != null) { + await engine.platform.manageSubscription( + _consent( + submission.consentFields, + email: submission.email, + phone: submission.phone, + ), + ); + } else { + engine.log('form of popup ${popup.id}: consent without a contact'); + } + } + await _segment(submission.segmentId); + event(PopupV3Event.submit); + } + + @override + Future review({ + required String kind, + required String code, + required int rate, + String? comment, + }) async { + await engine.platform.review(kind, { + 'channel': 'popup', + kind == 'nps' ? 'category' : 'campaign': code, + 'rate': rate, + if (comment != null && comment.trim().isNotEmpty) + 'comment': comment.trim(), + }); + event(PopupV3Event.submit); + } + + Future _segment(String? segmentId) async { + final id = segmentId?.trim() ?? ''; + if (id.isEmpty) return; + try { + final identity = await engine.platform.identity(); + await engine.api.segmentAdd(engine.apiHost, identity, id); + engine.onContextChanged('segment', 'add', { + 'segment_id': id, + }); + } catch (error) { + engine.log('segment $id of popup ${popup.id} — $error', always: true); + } + } + + static ManageSubscriptionParams _consent( + List fields, { + String? email, + String? phone, + }) => ManageSubscriptionParams( + email: email, + phone: phone, + emailBulk: fields.contains('email_bulk') ? true : null, + emailChain: fields.contains('email_chain') ? true : null, + emailTransactional: fields.contains('email_transactional') ? true : null, + ); +} diff --git a/lib/src/popups_v3/popups_v3_frequency.dart b/lib/src/popups_v3/popups_v3_frequency.dart new file mode 100644 index 0000000..8c60065 --- /dev/null +++ b/lib/src/popups_v3/popups_v3_frequency.dart @@ -0,0 +1,132 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import 'popup_v3.dart'; + +/// Последний показ попапа на устройстве: время (мс эпохи) и сессия. +typedef PopupV3LastShow = ({int? at, String? sid}); + +/// Где движок хранит последние показы попапов магазина. +abstract interface class PopupsV3Storage { + Future read(int popupId); + + Future write(int popupId, int at, String? sid); +} + +/// Показы в SharedPreferences, по магазину: `…..last` и `…..sid`. +class PopupsV3PreferencesStorage implements PopupsV3Storage { + PopupsV3PreferencesStorage(String shopId) + : _prefix = 'personalization.popupsV3.$shopId'; + + final String _prefix; + + @override + Future read(int popupId) async { + final preferences = await SharedPreferences.getInstance(); + return ( + at: preferences.getInt('$_prefix.$popupId.last'), + sid: preferences.getString('$_prefix.$popupId.sid'), + ); + } + + @override + Future write(int popupId, int at, String? sid) async { + final preferences = await SharedPreferences.getInstance(); + await preferences.setInt('$_prefix.$popupId.last', at); + if (sid != null && sid.isNotEmpty) { + await preferences.setString('$_prefix.$popupId.sid', sid); + } + } +} + +/// Показы в памяти — тесты и офлайн-сценарии. +class PopupsV3MemoryStorage implements PopupsV3Storage { + final Map shows = {}; + + @override + Future read(int popupId) async => + shows[popupId] ?? (at: null, sid: null); + + @override + Future write(int popupId, int at, String? sid) async { + final previous = shows[popupId]; + shows[popupId] = ( + at: at, + sid: sid != null && sid.isNotEmpty ? sid : previous?.sid, + ); + } +} + +/// Частота и пауза показов — как у веба (`frequency.ts`): +/// - пауза `cooldown_minutes` проверяется до частоты; +/// - `once_session` сравнивает сессию последнего показа; +/// - `once_day`/`once_week`/`once_month` — 24 ч, 7 и 30 дней; +/// - `every_page` — один показ на «страницу», то есть на открытие экрана; +/// - в тестовом режиме показ ничего не записывает (кроме «уже на этой странице»). +class PopupsV3FrequencyRules { + PopupsV3FrequencyRules(this.storage); + + final PopupsV3Storage storage; + final Set _shownOnPage = {}; + + static const Map periods = + { + PopupV3Frequency.onceDay: Duration(days: 1), + PopupV3Frequency.onceWeek: Duration(days: 7), + PopupV3Frequency.onceMonth: Duration(days: 30), + }; + + /// Открыт новый экран. + void newPage() => _shownOnPage.clear(); + + /// Можно ли показать [popup] сейчас ([now]) в сессии [sid]; нельзя — причина. + Future check( + PopupV3 popup, { + required DateTime now, + String? sid, + }) async { + if (_shownOnPage.contains(popup.id)) return 'already shown on this screen'; + final last = await storage.read(popup.id); + final lastAt = last.at; + final elapsed = lastAt == null + ? null + : Duration(milliseconds: now.millisecondsSinceEpoch - lastAt); + final cooldown = popup.cooldownMinutes; + if (cooldown > 0 && + elapsed != null && + elapsed < Duration(milliseconds: (cooldown * 60000).round())) { + return 'cooldown ${_minutes(cooldown)} min'; + } + switch (popup.frequency) { + case PopupV3Frequency.everyPage: + return null; + case PopupV3Frequency.onceLife: + return lastAt == null ? null : 'once_life: already shown'; + case PopupV3Frequency.onceDay: + case PopupV3Frequency.onceWeek: + case PopupV3Frequency.onceMonth: + return elapsed == null || elapsed >= periods[popup.frequency]! + ? null + : '${popup.frequency.wire}: shown recently'; + case PopupV3Frequency.onceSession: + return last.sid != null && last.sid == sid + ? 'once_session: already shown in this session' + : null; + } + } + + /// Запомнить показ [popup]. + Future record( + PopupV3 popup, { + required DateTime now, + String? sid, + bool testMode = false, + }) async { + _shownOnPage.add(popup.id); + if (testMode) return; + await storage.write(popup.id, now.millisecondsSinceEpoch, sid); + } + + static String _minutes(double value) => value == value.roundToDouble() + ? '${value.toInt()}' + : value.toStringAsFixed(1); +} diff --git a/lib/src/popups_v3/popups_v3_hooks.dart b/lib/src/popups_v3/popups_v3_hooks.dart new file mode 100644 index 0000000..ab3d626 --- /dev/null +++ b/lib/src/popups_v3/popups_v3_hooks.dart @@ -0,0 +1,51 @@ +import '../sdk_init_config.dart'; + +/// Что движок попапов v3 узнаёт от вызовов SDK. +abstract interface class PopupsV3Listener { + /// SDK инициализирован (или переинициализирован) с [config]. + void onInitialized(SdkInitConfig config); + + /// Своё событие SDK (`tracking.custom`) — триггер `track_event`. + void onTrackEvent(String event); + + /// Смена контекста клиента: профиль, подписка, сегмент (`type`), действие и данные. + void onContextChanged(String type, String action, Object? data); + + /// Покупка. + void onPurchase(); +} + +/// Связь обёртки SDK с движком попапов v3 без публичного API: обёртка сообщает о своих +/// вызовах по ключу — объекту `tracking` инстанса, движок подписывается на тот же ключ. +/// Пока движка нет, вызовы ничего не делают; конфиг init запоминается. +abstract final class PopupsV3Hooks { + static final Expando _listeners = Expando( + 'popupsV3', + ); + static final Expando _configs = Expando( + 'popupsV3Config', + ); + + static void listen(Object key, PopupsV3Listener? listener) => + _listeners[key] = listener; + + /// Конфиг последнего init инстанса [key]. + static SdkInitConfig? configOf(Object key) => _configs[key]; + + static void initialized(Object key, SdkInitConfig config) { + _configs[key] = config; + _listeners[key]?.onInitialized(config); + } + + static void trackEvent(Object key, String event) => + _listeners[key]?.onTrackEvent(event); + + static void contextChanged( + Object key, + String type, + String action, + Object? data, + ) => _listeners[key]?.onContextChanged(type, action, data); + + static void purchase(Object key) => _listeners[key]?.onPurchase(); +} diff --git a/lib/src/products/products_list_response.dart b/lib/src/products/products_list_response.dart index 8b17500..0c5307a 100644 --- a/lib/src/products/products_list_response.dart +++ b/lib/src/products/products_list_response.dart @@ -1,22 +1,37 @@ import '../recommendation/recommendation_response.dart' show ProductCategory; import '../json_number.dart'; +import '../search/search_facets.dart'; +import '../search/search_response.dart' show SearchFilter; export '../recommendation/recommendation_response.dart' show ProductCategory; /// Response from [PersonalizationSdk.getProductsList]. /// -/// Excluded Android-only fields: brands (`List`), categories -/// (`List`), filters (`List`), priceRanges, priceMedian. -/// Excluded iOS-only fields: brands (`[String]`), filters (`[String: Filter]`). +/// Excluded Android-only fields: priceRanges, priceMedian. class ProductsListResponse { final List products; final int productsTotal; final PriceRange? priceRange; + /// Brand names found in the listing (Android carries counts too, iOS only names). + final List brands; + + /// Shop facets keyed by name: value → product count. + final Map filters; + + /// Categories of the listing (`categories`); the top-level ones have no + /// [ProductCategory.parentId]. Android only for now: the iOS bridge builds the + /// response from the native model, which gets them in the next iOS SDK release, + /// so on iOS the list stays empty until then. + final List categories; + const ProductsListResponse({ required this.products, required this.productsTotal, this.priceRange, + this.brands = const [], + this.filters = const {}, + this.categories = const [], }); factory ProductsListResponse.fromJson(Map json) { @@ -28,6 +43,12 @@ class ProductsListResponse { priceRange: json['price_range'] == null ? null : PriceRange.fromJson(json['price_range'] as Map), + brands: parseBrandNames(json['brands']), + filters: parseFacetFilters(json['filters']), + categories: (json['categories'] as List? ?? []) + .whereType>() + .map((e) => ProductCategory.fromJson(Map.from(e))) + .toList(), ); } } @@ -40,10 +61,15 @@ class ProductsListResponse { /// Note: iOS maps product ID from JSON key "uniqid"; the bridge normalises /// this to "id" so Dart always reads from "id". /// -/// Excluded Android-only fields: _id, imageUrlHandle, urlHandle, picture, -/// categoryIds, locationIds. -/// Excluded iOS-only fields: model, barcode, deeplinkIos, resizedImageUrl, -/// oldPrice / oldPriceFull (and formatted variants), discount, isNew, params. +/// Excluded Android-only fields: _id, imageUrlHandle, urlHandle, categoryIds, +/// locationIds. +/// Excluded iOS-only fields: model, barcode, oldPriceFull (and its formatted +/// variant), params. +/// +/// The fields after [categories] are nullable: the API sends them for every product +/// listing, but a bridge fills only those its native model carries. Android hands +/// [PersonalizationSdk.getProductInfo] and [PersonalizationSdk.getProductsList] over +/// as raw JSON, so they carry all of them; the rest is noted per field. class Product { final String id; final String name; @@ -61,6 +87,34 @@ class Product { final Map resizedImages; final List categories; + /// Resized copy of the main image (`picture`), the one to show in lists. + final String? picture; + + /// Price before the discount (`oldprice`). Not in iOS categories and collections. + final double? oldPrice; + final String? oldPriceFormatted; + + /// Discount (`discount`) and its display form (`discount_formatted`, e.g. `6%`). + /// The display form is not on iOS; neither is in iOS categories and collections. + final int? discount; + final String? discountFormatted; + + /// Discount in percent as the shop computes it (`discount_percent`). Android + /// product info and products list only for now. + final int? discountPercent; + + /// Android app link to the product (`deeplink_android`). Android product info and + /// products list only for now. + final String? deeplinkAndroid; + + /// iOS app link to the product (`deeplink_ios`). Not in categories and collections + /// for now. + final String? deeplinkIos; + + /// The shop marks the product as new (`is_new`). Not in iOS categories and + /// collections. + final bool? isNew; + const Product({ required this.id, required this.name, @@ -77,6 +131,15 @@ class Product { required this.relativeSalesRate, required this.resizedImages, required this.categories, + this.picture, + this.oldPrice, + this.oldPriceFormatted, + this.discount, + this.discountFormatted, + this.discountPercent, + this.deeplinkAndroid, + this.deeplinkIos, + this.isNew, }); factory Product.fromJson(Map json) { @@ -98,6 +161,16 @@ class Product { categories: (json['categories'] as List? ?? []) .map((e) => ProductCategory.fromJson(e as Map)) .toList(), + picture: toNonEmptyStringOrNull(json['picture']), + oldPrice: toDoubleOrNull(json['oldprice']), + oldPriceFormatted: toNonEmptyStringOrNull(json['oldprice_formatted']), + // `false` in product info for a product without a discount. + discount: toIntOrNull(json['discount']), + discountFormatted: toNonEmptyStringOrNull(json['discount_formatted']), + discountPercent: toIntOrNull(json['discount_percent']), + deeplinkAndroid: toNonEmptyStringOrNull(json['deeplink_android']), + deeplinkIos: toNonEmptyStringOrNull(json['deeplink_ios']), + isNew: toBoolOrNull(json['is_new']), ); } } diff --git a/lib/src/recommendation/recommendation_response.dart b/lib/src/recommendation/recommendation_response.dart index 79681c8..d5004a9 100644 --- a/lib/src/recommendation/recommendation_response.dart +++ b/lib/src/recommendation/recommendation_response.dart @@ -2,7 +2,8 @@ import '../json_number.dart'; /// Typed response for [PersonalizationSdk.getRecommendation]. /// -/// Contains only fields present in **both** Android and iOS native SDK models. +/// Contains the fields present in **both** Android and iOS native SDK models, plus +/// the nullable discount, app link and novelty fields of [RecommendedProduct]. /// /// Fields available in the native Android SDK but excluded from this contract: /// - `html` — rendered block HTML (`GetExtendedRecommendationResponse.html`). @@ -12,10 +13,9 @@ import '../json_number.dart'; /// - `Product.locationIds` — flat list of location IDs (use `locations` on iOS). /// /// Fields available in the native iOS SDK but excluded from this contract: -/// - `Product.barcode`, `Product.model`, `Product.deeplinkIos`. -/// - `Product.oldPrice`, `Product.oldPriceFull`, `Product.oldPriceFormatted`, -/// `Product.oldPriceFullFormatted` — original price before discount. -/// - `Product.discount`, `Product.rating`. +/// - `Product.barcode`, `Product.model`. +/// - `Product.oldPriceFull`, `Product.oldPriceFullFormatted`. +/// - `Product.rating`. /// - `Product.fashionSizes`, `Product.fashionColors`, `Product.fashionOriginalSizes`. /// - `Product.locations` — full location objects (Android only exposes IDs). /// - `Product.paramsRaw` — raw extra params from the API response. @@ -43,6 +43,10 @@ class RecommendationResponse { /// A single recommended product. /// /// See [RecommendationResponse] for the full list of excluded platform-specific fields. +/// +/// The fields after [relativeSalesRate] are nullable: the API sends them with every +/// recommended product, but the bridges re-serialize the native models, so a field +/// arrives only where the native model carries it — see each field. class RecommendedProduct { final String id; final String name; @@ -70,6 +74,29 @@ class RecommendedProduct { final int salesRate; final double relativeSalesRate; + /// Price before the discount (`oldprice`). + final double? oldPrice; + final String? oldPriceFormatted; + + /// Discount (`discount`) and its display form (`discount_formatted`, e.g. `6%`). + /// The display form comes from Android only for now. + final int? discount; + final String? discountFormatted; + + /// Discount in percent as the shop computes it (`discount_percent`). Neither + /// native model carries it yet. + final int? discountPercent; + + /// Android app link to the product (`deeplink_android`). The Android model does + /// not carry it yet. + final String? deeplinkAndroid; + + /// iOS app link to the product (`deeplink_ios`). From iOS only for now. + final String? deeplinkIos; + + /// The shop marks the product as new (`is_new`). From Android only for now. + final bool? isNew; + const RecommendedProduct({ required this.id, required this.name, @@ -87,6 +114,14 @@ class RecommendedProduct { required this.currency, required this.salesRate, required this.relativeSalesRate, + this.oldPrice, + this.oldPriceFormatted, + this.discount, + this.discountFormatted, + this.discountPercent, + this.deeplinkAndroid, + this.deeplinkIos, + this.isNew, }); factory RecommendedProduct.fromJson(Map json) { @@ -113,6 +148,14 @@ class RecommendedProduct { currency: json['currency'] as String? ?? '', salesRate: toIntOrNull(json['sales_rate']) ?? 0, relativeSalesRate: toDoubleOrNull(json['relative_sales_rate']) ?? 0.0, + oldPrice: toDoubleOrNull(json['oldprice']), + oldPriceFormatted: toNonEmptyStringOrNull(json['oldprice_formatted']), + discount: toIntOrNull(json['discount']), + discountFormatted: toNonEmptyStringOrNull(json['discount_formatted']), + discountPercent: toIntOrNull(json['discount_percent']), + deeplinkAndroid: toNonEmptyStringOrNull(json['deeplink_android']), + deeplinkIos: toNonEmptyStringOrNull(json['deeplink_ios']), + isNew: toBoolOrNull(json['is_new']), ); } } diff --git a/lib/src/search/search_facets.dart b/lib/src/search/search_facets.dart new file mode 100644 index 0000000..23b5dc1 --- /dev/null +++ b/lib/src/search/search_facets.dart @@ -0,0 +1,48 @@ +/// Facet parsers shared by the search, category and products list responses. +/// +/// Every catalog-like endpoint answers with the same facets as full search, so the +/// responses parse them the same way. Not exported from the package barrel. +library; + +import '../json_number.dart'; +import 'search_response.dart' show SearchFilter; + +/// Brands arrive as `[{name, count}]` (Android, raw API) or `[name]` (iOS); both +/// become names. +List parseBrandNames(dynamic raw) { + if (raw is! List) return const []; + return raw + .map((e) => e is Map ? e['name']?.toString() : e?.toString()) + .whereType() + .where((name) => name.isNotEmpty) + .toList(); +} + +/// Product counts of `[{: value, count}]` entries by value: brands (`name`) and +/// the colours (`color`) and sizes (`size`) of `industrial_filters`. Entries without a +/// count are left out — iOS sends the brands of a full search as bare names. +Map parseFacetCounts(dynamic raw, String key) { + if (raw is! List) return const {}; + final counts = {}; + for (final entry in raw) { + if (entry is! Map) continue; + final value = entry[key]?.toString(); + final count = toIntOrNull(entry['count']); + if (value != null && value.isNotEmpty && count != null) { + counts[value] = count; + } + } + return counts; +} + +/// Shop facets (`filters`) keyed by name: value → product count. +Map parseFacetFilters(dynamic raw) { + if (raw is! Map) return const {}; + return { + for (final entry in raw.entries) + if (entry.value is Map) + entry.key.toString(): SearchFilter.fromJson( + Map.from(entry.value as Map), + ), + }; +} diff --git a/lib/src/search/search_response.dart b/lib/src/search/search_response.dart index 57f3cb8..d8ef7d9 100644 --- a/lib/src/search/search_response.dart +++ b/lib/src/search/search_response.dart @@ -1,4 +1,5 @@ import '../json_number.dart'; +import 'search_facets.dart'; /// Response from [PersonalizationSdk.searchFull]. /// @@ -18,6 +19,9 @@ class SearchFullResponse { /// Brand names found in the results (Android carries counts too, iOS only names). final List brands; + /// Product count per brand name, where the native side carries it (not iOS). + final Map brandCounts; + /// Shop facets keyed by name: value → product count. final Map filters; final SearchIndustrialFilters? industrialFilters; @@ -29,6 +33,7 @@ class SearchFullResponse { this.priceRange, this.locations, this.brands = const [], + this.brandCounts = const {}, this.filters = const {}, this.industrialFilters, }); @@ -50,8 +55,9 @@ class SearchFullResponse { locations: (json['locations'] as List?) ?.map((e) => SearchLocation.fromJson(e as Map)) .toList(), - brands: _parseBrands(json['brands']), - filters: _parseFilters(json['filters']), + brands: parseBrandNames(json['brands']), + brandCounts: parseFacetCounts(json['brands'], 'name'), + filters: parseFacetFilters(json['filters']), industrialFilters: json['industrial_filters'] is Map ? SearchIndustrialFilters.fromJson( Map.from(json['industrial_filters'] as Map), @@ -61,27 +67,6 @@ class SearchFullResponse { } } -/// Brands arrive as `[{name, count}]` (Android) or `[name]` (iOS); both become names. -List _parseBrands(dynamic raw) { - if (raw is! List) return const []; - return raw - .map((e) => e is Map ? e['name']?.toString() : e?.toString()) - .whereType() - .where((name) => name.isNotEmpty) - .toList(); -} - -Map _parseFilters(dynamic raw) { - if (raw is! Map) return const {}; - return { - for (final entry in raw.entries) - if (entry.value is Map) - entry.key.toString(): SearchFilter.fromJson( - Map.from(entry.value as Map), - ), - }; -} - /// One facet of a full search: how many products carry it and the count per value. class SearchFilter { final int count; @@ -108,9 +93,15 @@ class SearchIndustrialFilters { final List colors; final List fashionSizes; + /// Product count per colour and per size, where the answer carries one. + final Map colorCounts; + final Map fashionSizeCounts; + const SearchIndustrialFilters({ this.colors = const [], this.fashionSizes = const [], + this.colorCounts = const {}, + this.fashionSizeCounts = const {}, }); factory SearchIndustrialFilters.fromJson(Map json) { @@ -123,6 +114,8 @@ class SearchIndustrialFilters { return SearchIndustrialFilters( colors: names(json['colors'], 'color'), fashionSizes: names(json['fashion_sizes'], 'size'), + colorCounts: parseFacetCounts(json['colors'], 'color'), + fashionSizeCounts: parseFacetCounts(json['fashion_sizes'], 'size'), ); } } @@ -132,8 +125,11 @@ class SearchIndustrialFilters { /// /// Excluded Android-only fields: _id, imageUrlHandle, urlHandle, categoryIds, /// locationIds, categories (product-level category model differs from search-level). -/// Excluded iOS-only fields: barcode, model, deeplinkIos, oldPriceFull (and its -/// formatted variant), isNew, params. +/// Excluded iOS-only fields: barcode, model, oldPriceFull (and its formatted +/// variant), params. +/// +/// The fields after [discountFormatted] are nullable: a bridge fills them only where +/// its native model carries them, see each field. class SearchProduct { final String id; final String name; @@ -164,6 +160,21 @@ class SearchProduct { final int discount; final String? discountFormatted; + /// Discount in percent as the shop computes it (`discount_percent`). Full search + /// on Android only for now: the native product models drop it. + final int? discountPercent; + + /// Android app link to the product (`deeplink_android`). Full search only for now, + /// on Android: iOS and the instant and blank search models drop it. + final String? deeplinkAndroid; + + /// iOS app link to the product (`deeplink_ios`). Full search on Android, every + /// search on iOS; the Android instant and blank search models drop it. + final String? deeplinkIos; + + /// The shop marks the product as new (`is_new`). + final bool? isNew; + const SearchProduct({ required this.id, required this.name, @@ -184,6 +195,10 @@ class SearchProduct { this.oldPriceFormatted, this.discount = 0, this.discountFormatted, + this.discountPercent, + this.deeplinkAndroid, + this.deeplinkIos, + this.isNew, }); factory SearchProduct.fromJson(Map json) { @@ -207,6 +222,10 @@ class SearchProduct { oldPriceFormatted: json['oldprice_formatted'] as String?, discount: toIntOrNull(json['discount']) ?? 0, discountFormatted: json['discount_formatted'] as String?, + discountPercent: toIntOrNull(json['discount_percent']), + deeplinkAndroid: toNonEmptyStringOrNull(json['deeplink_android']), + deeplinkIos: toNonEmptyStringOrNull(json['deeplink_ios']), + isNew: toBoolOrNull(json['is_new']), ); } } diff --git a/lib/src/stories/stories_poll.dart b/lib/src/stories/stories_poll.dart new file mode 100644 index 0000000..19ace4f --- /dev/null +++ b/lib/src/stories/stories_poll.dart @@ -0,0 +1,311 @@ +part of 'stories_response.dart'; + +/// Вид опроса элемента `poll` (`poll_type`). +enum StoryPollType { + miniPoll('mini_poll'), + nps('nps'), + csat('csat'), + ces('ces'); + + const StoryPollType(this.wire); + + /// Значение `poll_type` и сегмент пути `/api/v3/polls/{kind}/reviews` у шкал. + final String wire; + + /// NPS, CSAT или CES — шкала оценок. + bool get isScale => this != StoryPollType.miniPoll; + + static StoryPollType? _parse(Object? value) { + for (final type in values) { + if (type.wire == value) return type; + } + return null; + } +} + +/// Вид мини-опроса (`poll.kind`). +enum StoryMiniPollKind { + singleChoice('single_choice'), + multipleChoice('multiple_choice'), + text('text'); + + const StoryMiniPollKind(this.wire); + + final String wire; + + static StoryMiniPollKind? _parse(Object? value) { + for (final kind in values) { + if (kind.wire == value) return kind; + } + return null; + } +} + +/// Вариант ответа мини-опроса. +class StoryPollOption { + const StoryPollOption({required this.id, required this.label}); + + final int id; + final String label; +} + +/// Полоса шкалы `from..to` и текст благодарности за оценку из неё. +class StoryPollBand { + const StoryPollBand({required this.from, required this.to, this.success}); + + final double from; + final double to; + + /// Текст под отвеченной шкалой; `null` — не задан. + final String? success; +} + +/// Ответ посетителя: варианты, текст или оценка. +class StoryPollAnswer { + const StoryPollAnswer({this.id, this.optionIds, this.text, this.rate}); + + final int? id; + final List? optionIds; + final String? text; + + /// Оценка шкалы. Дробная тоже ответ, но ни одну ячейку не подсвечивает. + final num? rate; + + /// Ответ есть: непустые варианты, непустой текст или оценка. + bool get isAnswered => + (optionIds?.isNotEmpty ?? false) || + (text?.isNotEmpty ?? false) || + rate != null; + + /// Ответ из JSON (`answer` ленты или `payload.answer` отправки); не объект — `null`. + static StoryPollAnswer? tryParse(Object? json) { + if (json is! Map) return null; + final ids = json['option_ids']; + final text = json['text']; + return StoryPollAnswer( + id: toIntOrNull(json['id']), + optionIds: ids is List ? [for (final id in ids) ?_whole(id)] : null, + text: text is String ? text : null, + rate: _number(json['rate']), + ); + } +} + +/// Итоги мини-опроса (`results`, только при `show_results`). +class StoryPollResults { + const StoryPollResults({this.total = 0, this.options}); + + final int total; + + /// Проценты вариантов; `null` — `options` не массив, процентов у вариантов нет. + final List<({int id, double percent})>? options; + + /// Процент варианта [id] целым: округлён и зажат в 0…100, нет в итогах — 0. Без + /// процентов вариантов ([options] `null`) — `null`. + int? percentOf(int id) { + final options = this.options; + if (options == null) return null; + for (final option in options) { + if (option.id != id) continue; + final percent = option.percent; + return percent.isNaN ? 0 : percent.clamp(0, 100).round(); + } + return 0; + } + + /// Итоги из JSON; не объект — `null`. + static StoryPollResults? tryParse(Object? json) { + if (json is! Map) return null; + final options = json['options']; + return StoryPollResults( + total: toIntOrNull(json['total']) ?? 0, + options: options is List + ? <({int id, double percent})>[ + for (final option in _maps(options)) + if (_whole(option['id']) case final id?) + (id: id, percent: toDoubleOrNull(option['percent']) ?? 0), + ] + : null, + ); + } +} + +/// Тексты карточки от сервера (`labels`): `null` — не прислан, берётся текст хоста. +class StoryPollLabels { + const StoryPollLabels({this.reanswer, this.error, this.submit}); + + /// Ссылка «Ответить заново». + final String? reanswer; + + /// Отправка не удалась. + final String? error; + + /// Кнопка отправки, когда у опроса нет `submit_label`. + final String? submit; +} + +/// `poll`: опрос на слайде — мини-опрос (выбор одного, нескольких, текст) или шкала +/// NPS / CSAT / CES. Приходит только в ленте API v3. +/// +/// Разбор терпимый: числа строками, `null` в необязательных полях. Неизвестный +/// `poll_type` или `kind` и битый элемент — `null` при разборе (элемент пропускается). +class StoryPollElement extends StoryElement { + const StoryPollElement({ + required this.pollType, + this.kind, + required this.code, + this.yOffset, + this.allowReanswer = false, + this.question = '', + this.placeholder = '', + this.maxLength, + this.submitLabel = '', + this.thanksText = '', + this.showResults = false, + this.options = const [], + this.channel = '', + this.name = '', + this.rateMin, + this.rateMax, + this.bands = const [], + this.answer, + this.results, + this.labels = const StoryPollLabels(), + }); + + final StoryPollType pollType; + + /// Вид мини-опроса; у шкал `null`. + final StoryMiniPollKind? kind; + + /// Код опроса: мини-опроса — в пути запроса, шкалы — `category` (NPS) или `campaign`. + final String code; + + /// Верх карточки в процентах высоты, 0…100; `null` (не задан или не число) — 0. + final double? yOffset; + + /// Можно ответить заново: у отвеченного — ссылка «Ответить заново». + final bool allowReanswer; + final String question; + + // Мини-опрос. + final String placeholder; + + /// Предел длины текстового ответа; `null` — без предела. + final int? maxLength; + final String submitLabel; + final String thanksText; + final bool showResults; + final List options; + + // Шкала. + /// Канал отзыва; пусто — `stories`. + final String channel; + final String name; + + /// Границы шкалы; не целые — `null`, берутся умолчания вида. + final int? rateMin; + final int? rateMax; + final List bands; + + /// Ответ посетителя из ленты; `null` — не отвечал. + final StoryPollAnswer? answer; + final StoryPollResults? results; + final StoryPollLabels labels; + + /// Элемент из JSON; вид, который кит не рисует, и битый элемент — `null` и запись в + /// отладочный лог. + static StoryPollElement? tryParse(Map json) { + try { + return _parse(json); + } catch (error) { + debugPrint('PersonalizationStories: poll element skipped — $error'); + return null; + } + } + + static StoryPollElement? _parse(Map json) { + final type = StoryPollType._parse(json['poll_type']); + final poll = json['poll']; + if (type == null || poll is! Map) { + debugPrint( + type == null + ? 'PersonalizationStories: poll "${json['poll_type']}" is not supported' + : 'PersonalizationStories: poll "${type.wire}" without "poll"', + ); + return null; + } + final kind = StoryMiniPollKind._parse(poll['kind']); + if (type == StoryPollType.miniPoll && kind == null) { + debugPrint( + 'PersonalizationStories: mini poll "${poll['kind']}" is not supported', + ); + return null; + } + final labels = json['labels']; + String? label(String key) => + labels is Map ? toNonEmptyStringOrNull(labels[key]) : null; + final maxLength = toIntOrNull(poll['max_length']); + final yOffset = toDoubleOrNull(json['y_offset']); + return StoryPollElement( + pollType: type, + kind: type == StoryPollType.miniPoll ? kind : null, + code: poll['code']?.toString() ?? '', + yOffset: yOffset != null && yOffset.isFinite ? yOffset : null, + allowReanswer: _flag(json['allow_reanswer']), + question: _text(poll['question']), + placeholder: _text(poll['placeholder']), + maxLength: maxLength != null && maxLength > 0 ? maxLength : null, + submitLabel: _text(poll['submit_label']), + thanksText: _text(poll['thanks_text']), + showResults: _flag(poll['show_results']), + options: [ + for (final option in _maps(poll['options'])) + if (_whole(option['id']) case final id?) + StoryPollOption(id: id, label: _text(option['label'])), + ], + channel: _text(poll['channel']), + name: _text(poll['name']), + rateMin: _whole(poll['rate_min']), + rateMax: _whole(poll['rate_max']), + bands: [ + for (final band in _maps(poll['bands'])) + if ((toDoubleOrNull(band['from']), toDoubleOrNull(band['to'])) case ( + final from?, + final to?, + )) + StoryPollBand( + from: from, + to: to, + success: toNonEmptyStringOrNull(band['success']), + ), + ], + answer: StoryPollAnswer.tryParse(json['answer']), + results: StoryPollResults.tryParse(json['results']), + labels: StoryPollLabels( + reanswer: label('reanswer'), + error: label('error'), + submit: label('submit'), + ), + ); + } +} + +/// Флаг опроса: истина — только `true`, `1` или `"true"`, остальное — ложь. +bool _flag(Object? value) => value == true || value == 1 || value == 'true'; + +/// Число, в том числе строкой; не число и не конечное — `null`. +num? _number(Object? value) { + final number = value is String ? num.tryParse(value.trim()) : value; + return number is num && number.isFinite ? number : null; +} + +/// Целое число, в том числе строкой (`"7"`, `7.0`); дробное и не число — `null`. +int? _whole(Object? value) { + if (value is int) return value; + final number = toDoubleOrNull(value); + if (number == null || !number.isFinite || number != number.roundToDouble()) { + return null; + } + return number.toInt(); +} diff --git a/lib/src/stories/stories_response.dart b/lib/src/stories/stories_response.dart index 1ab2348..53ae60b 100644 --- a/lib/src/stories/stories_response.dart +++ b/lib/src/stories/stories_response.dart @@ -1,11 +1,16 @@ +import 'package:flutter/foundation.dart' show debugPrint; + import '../json_number.dart'; +part 'stories_poll.dart'; +part 'stories_share_v3.dart'; + +// The `payload` of API v3 (`/api/v3/storefront/stories/{code}`) has the same keys and +// is parsed here too. + /// A stories block (`GET stories/{code}`), parsed from the server JSON both bridges hand /// over untouched. /// -/// Internal to the UI kit until its release: the package barrel does not export it, the -/// kit barrel (`src/ui/personalization_ui.dart`) does. -/// /// Parsing is tolerant, the way the native SDKs read the same payload: numbers may arrive /// as strings (`font_size`, `y_offset`, `duration`), ids as numbers or strings, and a /// missing field takes the native default. The block-level `settings` (legacy colours of @@ -43,6 +48,10 @@ class Story { final int startPosition; final List slides; + // Sharing of API v3: behind the v3 gate, read through [StoryShareV3]. + final bool _shareable; + final String _shareUrl; + const Story({ required this.id, required this.name, @@ -51,10 +60,25 @@ class Story { this.pinned = false, this.startPosition = 0, required this.slides, + }) : _shareable = true, + _shareUrl = ''; + + const Story._json( + this._shareable, + this._shareUrl, { + required this.id, + required this.name, + required this.avatar, + required this.viewed, + required this.pinned, + required this.startPosition, + required this.slides, }); factory Story.fromJson(Map json) { - return Story( + return Story._json( + json['shareable'] != false, + _text(json['share_url']), id: json['id']?.toString() ?? '', name: json['name'] as String? ?? '', avatar: json['avatar'] as String? ?? '', @@ -97,6 +121,9 @@ class StorySlide { final Duration duration; final List elements; + // Sharing of API v3: behind the v3 gate, read through [StorySlideShareV3]. + final String _shareUrl; + /// Seconds a slide lasts when the server does not say (or says 0) — the same on every /// platform. static const int defaultDurationSeconds = 10; @@ -109,11 +136,23 @@ class StorySlide { this.preview = '', this.duration = const Duration(seconds: defaultDurationSeconds), this.elements = const [], + }) : _shareUrl = ''; + + const StorySlide._json( + this._shareUrl, { + required this.id, + required this.type, + required this.background, + required this.backgroundColor, + required this.preview, + required this.duration, + required this.elements, }); factory StorySlide.fromJson(Map json) { final seconds = toIntOrNull(json['duration']); - return StorySlide( + return StorySlide._json( + _text(json['share_url']), id: json['id']?.toString() ?? '', type: switch (json['type']) { 'image' => StorySlideType.image, @@ -144,7 +183,7 @@ class StorySlide { } /// An element placed on a slide. Unknown types and `header` (not drawn by the kit) are -/// dropped while parsing. +/// dropped while parsing, and so is a `poll` of a kind the kit does not draw. sealed class StoryElement { const StoryElement(); @@ -155,6 +194,7 @@ sealed class StoryElement { 'product' => StoryProductElement.fromJson(json), 'products' => StoryProductsElement.fromJson(json), 'text_block' => StoryTextBlockElement.fromJson(json), + 'poll' => StoryPollElement.tryParse(json), _ => null, }; } @@ -407,6 +447,9 @@ double parseStoryOpacity(dynamic value) { return fraction.clamp(0, 1).toDouble(); } +// A string field; JSON `null` (API v3 sends it for empty fields) and other types are empty. +String _text(dynamic value) => value is String ? value : ''; + Iterable> _maps(dynamic raw) { if (raw is! List) return const []; return raw.whereType().map(Map.from); diff --git a/lib/src/stories/stories_share_v3.dart b/lib/src/stories/stories_share_v3.dart new file mode 100644 index 0000000..8fe9c89 --- /dev/null +++ b/lib/src/stories/stories_share_v3.dart @@ -0,0 +1,21 @@ +part of 'stories_response.dart'; + +/// Sharing of a campaign over API v3. Behind the v3 gate (`src/v3/personalization_v3.dart`), +/// not the kit's. +extension StoryShareV3 on Story { + /// The shop allows sharing the campaign (`shareable`, API v3). A missing field allows it, + /// only `false` forbids. + bool get shareable => _shareable; + + /// "Share" link of the campaign (`share_url`, API v3); empty when not sent. Product + /// campaigns have only this one, their slides have none: a slide shares it with its + /// id in `r46_slide`. + String get shareUrl => _shareUrl; +} + +/// Sharing of a slide over API v3. Behind the v3 gate (`src/v3/personalization_v3.dart`), +/// not the kit's. +extension StorySlideShareV3 on StorySlide { + /// "Share" link of the slide (`share_url`, API v3); empty when not sent. + String get shareUrl => _shareUrl; +} diff --git a/lib/src/tracking/tracking_api.dart b/lib/src/tracking/tracking_api.dart index 28bcdf8..79eea4c 100644 --- a/lib/src/tracking/tracking_api.dart +++ b/lib/src/tracking/tracking_api.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import '../pigeon/personalization_api.g.dart' as pigeon; +import '../popups_v3/popups_v3_hooks.dart'; import 'purchase_line_item.dart'; import 'tracking_models.dart'; @@ -151,6 +152,7 @@ class TrackingApi { if (items.isEmpty) { throw ArgumentError.value(items, 'items', 'must be non-empty'); } + PopupsV3Hooks.purchase(this); return _api.trackPurchase( orderId, orderPrice, @@ -197,6 +199,7 @@ class TrackingApi { Map? customFields, }) { _requireNonEmpty(event, 'event'); + PopupsV3Hooks.trackEvent(this, event); return _api.trackEvent( event, time, diff --git a/lib/src/ui/components/personalization_badge.dart b/lib/src/ui/components/personalization_badge.dart index 44cd255..d87a8b1 100644 --- a/lib/src/ui/components/personalization_badge.dart +++ b/lib/src/ui/components/personalization_badge.dart @@ -63,8 +63,12 @@ class PersonalizationBadge extends StatelessWidget { : colors.semanticWarning, borderRadius: BorderRadius.circular(theme.radius.resolve(radius)), ), + // Плашка в одну строку: в тесноте подпись укорачивается, а не ломается по буквам. child: Text( label, + maxLines: 1, + softWrap: false, + overflow: TextOverflow.ellipsis, style: TextStyle( fontSize: fontSize, height: lineHeight / fontSize, diff --git a/lib/src/ui/components/personalization_button.dart b/lib/src/ui/components/personalization_button.dart index b6bacf5..b92f36c 100644 --- a/lib/src/ui/components/personalization_button.dart +++ b/lib/src/ui/components/personalization_button.dart @@ -91,6 +91,8 @@ class _PersonalizationButtonState extends State { Text( widget.label!, textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.ellipsis, style: TextStyle( fontSize: metrics.fontSize, height: metrics.lineHeight / metrics.fontSize, @@ -122,17 +124,23 @@ class _PersonalizationButtonState extends State { ), ), ), - child: Row( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - for (int i = 0; i < children.length; i++) ...[ - if (i > 0) const SizedBox(width: 8), - children[i], - ], - ], - ), + // Кнопка с одной подписью кладёт её прямо в контейнер: в тесноте (узкая колонка, + // крупный шрифт) подпись укорачивается многоточием, а не вылезает за кнопку. + // Flexible в Row для этого не годится — в Row без Expanded или в горизонтальном + // скролле кнопка получает бесконечную ширину, и flex-ребёнок падает. + child: children.length == 1 && _hasText + ? Align(widthFactor: 1, heightFactor: 1, child: children.single) + : Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + for (int i = 0; i < children.length; i++) ...[ + if (i > 0) const SizedBox(width: 8), + children[i], + ], + ], + ), ), ); } diff --git a/lib/src/ui/components/personalization_catalog.dart b/lib/src/ui/components/personalization_catalog.dart index 833a1e5..0e2b1f3 100644 --- a/lib/src/ui/components/personalization_catalog.dart +++ b/lib/src/ui/components/personalization_catalog.dart @@ -56,6 +56,8 @@ class PersonalizationCatalog extends StatelessWidget { this.onProductAction, this.onProductTap, this.emptyText, + this.emptyActionText, + this.onEmptyAction, this.loading = false, this.count, this.loadMoreText, @@ -64,6 +66,7 @@ class PersonalizationCatalog extends StatelessWidget { this.scrollable = true, this.controller, this.padding, + this.showRating = true, }); final Widget? header; @@ -79,6 +82,11 @@ class PersonalizationCatalog extends StatelessWidget { /// Текст пустой выдачи. `null` — без пустого состояния, плитка остаётся на месте. final String? emptyText; + + /// Кнопка под пустым состоянием — например, «повторить» после ошибки загрузки. + /// `null` — без кнопки. На время загрузки прячется, как «загрузить ещё». + final String? emptyActionText; + final VoidCallback? onEmptyAction; final bool loading; final PersonalizationCatalogCount? count; @@ -106,6 +114,10 @@ class PersonalizationCatalog extends StatelessWidget { /// Поля ленты. Содержимое прокручивается под ними, а не обрезается по их краю. final EdgeInsetsGeometry? padding; + /// Рисовать ли рейтинг товаров. `false` — карточки без рейтинга, даже если он у + /// товара есть. + final bool showRating; + /// Шаг между блоками каталога. static const double _gapBlock = PersonalizationSpacing.lg; @@ -130,6 +142,8 @@ class PersonalizationCatalog extends StatelessWidget { final int rows = grid ? (products.length + 1) ~/ 2 : products.length; final footer = [ if (empty) PersonalizationEmptyState(message: emptyText!), + if (empty && (emptyActionText ?? '').isNotEmpty && !loading) + _button(emptyActionText!, onEmptyAction), // Во фреймах с лоадером (296:3544, 299:6606) счётчика и кнопки нет — на время // загрузки лоадер встаёт на их место. if (loading) const PersonalizationLoader(), @@ -141,14 +155,7 @@ class PersonalizationCatalog extends StatelessWidget { total: count!.total, ), if (loadMoreText != null && loadMoreText!.isNotEmpty && !loading) - PersonalizationButton( - label: loadMoreText, - size: PersonalizationButtonSize.md, - view: PersonalizationButtonView.secondary, - iconStart: PersonalizationIcons.arrowRotateCw, - iconBuilder: iconBuilder, - onPressed: onLoadMore, - ), + _button(loadMoreText!, onLoadMore), ]; return CustomScrollView( @@ -203,6 +210,17 @@ class PersonalizationCatalog extends StatelessWidget { ); } + /// Кнопка под лентой: «загрузить ещё» или действие пустого состояния. + Widget _button(String label, VoidCallback? onPressed) => + PersonalizationButton( + label: label, + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.secondary, + iconStart: PersonalizationIcons.arrowRotateCw, + iconBuilder: iconBuilder, + onPressed: onPressed, + ); + /// Строка плитки. IntrinsicHeight + stretch: соседние карточки одной высоты, и /// цена с кнопкой у них на одной линии (см. [PersonalizationProductsList]). Widget _gridRow(int row) { @@ -239,7 +257,7 @@ class PersonalizationCatalog extends StatelessWidget { imageAspect: imageAspect, brand: product.brand, name: product.name, - rating: product.rating, + rating: showRating ? product.rating : null, price: product.price, oldPrice: product.oldPrice, discount: product.discount, diff --git a/lib/src/ui/components/personalization_checkbox.dart b/lib/src/ui/components/personalization_checkbox.dart index d8f9232..1bb6e5e 100644 --- a/lib/src/ui/components/personalization_checkbox.dart +++ b/lib/src/ui/components/personalization_checkbox.dart @@ -12,12 +12,21 @@ enum PersonalizationCheckboxState { unchecked, checked, indeterminate } /// /// Галка и черта рисуются штрихом по геометрии из макета: /// `M5 10 L8.75 13.75 L15 7.5` и `M5 10 H15`, толщина 2, круглые концы. +/// +/// Цвета по умолчанию — токены кита. Хост, который рисует чекбокс в своих +/// цветах, задаёт [checkedColor], [checkmarkColor], [uncheckedColor] и +/// [borderColor]; каждый заменяет один токен, остальные остаются из темы. +/// Заливки отключённого чекбокса — всегда токены `*Disabled`. class PersonalizationCheckbox extends StatelessWidget { const PersonalizationCheckbox({ super.key, this.state = PersonalizationCheckboxState.unchecked, this.disabled = false, this.onChanged, + this.checkedColor, + this.checkmarkColor, + this.uncheckedColor, + this.borderColor, }); final PersonalizationCheckboxState state; @@ -26,6 +35,18 @@ class PersonalizationCheckbox extends StatelessWidget { /// Зовётся с состоянием, в которое чекбокс переходит по нажатию. final ValueChanged? onChanged; + /// Заливка отмеченного и частичного. `null` — Button/Primary. + final Color? checkedColor; + + /// Галка и черта. `null` — Text/Light Primary. + final Color? checkmarkColor; + + /// Заливка пустого. `null` — Background/Input. + final Color? uncheckedColor; + + /// Рамка пустого. `null` — Line/Input. + final Color? borderColor; + static const double size = 20; @override @@ -39,12 +60,14 @@ class PersonalizationCheckbox extends StatelessWidget { painter: _CheckboxPainter( state: state, fill: isFilled - ? (disabled ? colors.buttonPrimaryDisabled : colors.buttonPrimary) + ? (disabled + ? colors.buttonPrimaryDisabled + : checkedColor ?? colors.buttonPrimary) : (disabled ? colors.backgroundInputDisabled - : colors.backgroundInput), - border: isFilled ? null : colors.lineInput, - glyph: colors.textLightPrimary, + : uncheckedColor ?? colors.backgroundInput), + border: isFilled ? null : borderColor ?? colors.lineInput, + glyph: checkmarkColor ?? colors.textLightPrimary, radius: theme.radius.resolve(PersonalizationRadiusToken.sm), ), ); diff --git a/lib/src/ui/components/personalization_filters.dart b/lib/src/ui/components/personalization_filters.dart index 92707af..b046471 100644 --- a/lib/src/ui/components/personalization_filters.dart +++ b/lib/src/ui/components/personalization_filters.dart @@ -349,61 +349,92 @@ class _PersonalizationFiltersState extends State { Widget build(BuildContext context) { final colors = PersonalizationTheme.of(context).colors; const double sectionGap = 16; + final Widget title = PersonalizationTitle( + title: widget.title, + trailing: PersonalizationButton( + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.ghost, + iconStart: PersonalizationIcons.crossLarge, + iconBuilder: widget.iconBuilder, + onPressed: widget.onClose, + ), + ); + final List sections = [ + for (final section in _sections) ...[ + const SizedBox(height: sectionGap), + _label( + context, + section.title, + PersonalizationTypography.lgEmphasized, + FontWeight.w600, + ), + const SizedBox(height: 12), + switch (section) { + PersonalizationFilterRange() => _range(context, section), + PersonalizationFilterOptions() => _options(context, section), + }, + ], + ]; + final Widget buttons = Row( + children: [ + Expanded( + child: PersonalizationButton( + label: widget.resetText, + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.secondary, + onPressed: widget.onReset, + ), + ), + const SizedBox(width: sectionGap), + Expanded( + child: PersonalizationButton( + label: widget.applyText, + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.primary, + onPressed: widget.onApply == null + ? null + : () => widget.onApply!(_sections), + ), + ), + ], + ); + // Заголовок и кнопки закреплены, прокручиваются только секции: фасетов бывает десятки, + // и до «Apply» не надо листать весь список. Без заданной высоты (экран в общей + // прокрутке хоста) — всё по содержимому, как одна колонка. return ColoredBox( color: colors.backgroundGeneric, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisSize: MainAxisSize.min, - children: [ - PersonalizationTitle( - title: widget.title, - trailing: PersonalizationButton( - size: PersonalizationButtonSize.md, - view: PersonalizationButtonView.ghost, - iconStart: PersonalizationIcons.crossLarge, - iconBuilder: widget.iconBuilder, - onPressed: widget.onClose, - ), - ), - for (final section in _sections) ...[ - const SizedBox(height: sectionGap), - _label( - context, - section.title, - PersonalizationTypography.lgEmphasized, - FontWeight.w600, - ), - const SizedBox(height: 12), - switch (section) { - PersonalizationFilterRange() => _range(context, section), - PersonalizationFilterOptions() => _options(context, section), - }, - ], - const SizedBox(height: sectionGap * 2), - Row( + child: LayoutBuilder( + builder: (context, constraints) { + if (!constraints.hasBoundedHeight) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + title, + ...sections, + const SizedBox(height: sectionGap * 2), + buttons, + ], + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + title, Expanded( - child: PersonalizationButton( - label: widget.resetText, - size: PersonalizationButtonSize.md, - view: PersonalizationButtonView.secondary, - onPressed: widget.onReset, - ), - ), - const SizedBox(width: sectionGap), - Expanded( - child: PersonalizationButton( - label: widget.applyText, - size: PersonalizationButtonSize.md, - view: PersonalizationButtonView.primary, - onPressed: widget.onApply == null - ? null - : () => widget.onApply!(_sections), + child: SingleChildScrollView( + padding: const EdgeInsets.only(bottom: sectionGap), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: sections, + ), ), ), + const SizedBox(height: sectionGap), + buttons, ], - ), - ], + ); + }, ), ); } diff --git a/lib/src/ui/components/personalization_product.dart b/lib/src/ui/components/personalization_product.dart index 18b7aa2..c10fa44 100644 --- a/lib/src/ui/components/personalization_product.dart +++ b/lib/src/ui/components/personalization_product.dart @@ -19,6 +19,8 @@ class PersonalizationProduct { this.oldPrice, this.discount, this.actionText, + this.url, + this.deeplink, }); final String id; @@ -30,4 +32,11 @@ class PersonalizationProduct { final String? oldPrice; final String? discount; final String? actionText; + + /// Страница товара на сайте магазина. + final String? url; + + /// Ссылка на товар в приложении для платформы, на которой оно запущено: + /// `deeplink_android` на Android, `deeplink_ios` на iOS. + final String? deeplink; } diff --git a/lib/src/ui/components/personalization_product_card.dart b/lib/src/ui/components/personalization_product_card.dart index 35ac0cd..e080e2d 100644 --- a/lib/src/ui/components/personalization_product_card.dart +++ b/lib/src/ui/components/personalization_product_card.dart @@ -5,6 +5,7 @@ import 'personalization_badge.dart'; import 'personalization_button.dart'; import 'personalization_product_image.dart'; import 'personalization_rating.dart'; +import 'personalization_wrap_row.dart'; /// Тип карточки товара. enum PersonalizationProductCardType { carousel, grid, list } @@ -138,8 +139,12 @@ class PersonalizationProductCard extends StatelessWidget { reviews: rating!.reviews, iconBuilder: iconBuilder, ); + // Цены не ломаются посреди числа: не влезают рядом — старая цена уходит на свою строку. final Widget priceText = Text( price, + maxLines: 1, + softWrap: false, + overflow: TextOverflow.ellipsis, style: style( metrics.priceSize, metrics.priceLineHeight, @@ -152,6 +157,9 @@ class PersonalizationProductCard extends StatelessWidget { ? null : Text( oldPrice!, + maxLines: 1, + softWrap: false, + overflow: TextOverflow.ellipsis, style: style( metrics.oldPriceSize, metrics.oldPriceLineHeight, @@ -209,23 +217,21 @@ class PersonalizationProductCard extends StatelessWidget { ], ], ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.center, + // В узкой колонке (360 dp, крупный шрифт) цена, бейдж и кнопка в строку + // не влезают: бейдж переносится под цену, кнопка — под блок цены вправо. + PersonalizationWrapRow( + horizontalGap: 8, + verticalGap: 8, + pinEnd: true, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - Row( - mainAxisSize: MainAxisSize.min, - children: [ - priceText, - if (discountBadge != null) ...[ - const SizedBox(width: 8), - discountBadge, - ], - ], + PersonalizationWrapRow( + horizontalGap: 8, + verticalGap: 4, + children: [priceText, ?discountBadge], ), ?oldPriceText, ], @@ -282,16 +288,15 @@ class PersonalizationProductCard extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 8), - Row( - crossAxisAlignment: CrossAxisAlignment.baseline, - textBaseline: TextBaseline.alphabetic, - children: [ - priceText, - if (oldPriceText != null) ...[ - const SizedBox(width: 8), - oldPriceText, - ], - ], + // Длинные цены («799 990 ₽» и «1 574 990 ₽») в колонку плитки рядом не + // влезают: старая цена встаёт строкой над ценой, и цена с кнопкой остаются + // на линии соседей. + PersonalizationWrapRow( + horizontalGap: 8, + verticalGap: 0, + wrapAbove: true, + alignBottom: true, + children: [priceText, ?oldPriceText], ), if (action != null) ...[const SizedBox(height: 8), action], ], diff --git a/lib/src/ui/components/personalization_recommender_block.dart b/lib/src/ui/components/personalization_products_block.dart similarity index 59% rename from lib/src/ui/components/personalization_recommender_block.dart rename to lib/src/ui/components/personalization_products_block.dart index fa86501..2060c9c 100644 --- a/lib/src/ui/components/personalization_recommender_block.dart +++ b/lib/src/ui/components/personalization_products_block.dart @@ -9,7 +9,8 @@ import 'personalization_product_image.dart'; import 'personalization_products_list.dart'; import 'personalization_title.dart'; -/// Блок рекомендаций: заголовок, товары, у карусели — точки. +/// Блок товаров: заголовок, товары, у карусели — точки. Товары даёт хост; блок +/// рекомендаций, который сам грузит товары по коду, — `PersonalizationRecommenderBlock`. /// /// Источник: Figma Mobile SDK UI Kit, секция Card — Recommender/Carousel (90:655), /// Recommender/Grid (126:1944), Recommender/List (126:2551). @@ -18,29 +19,34 @@ import 'personalization_title.dart'; /// /// Собран из [PersonalizationTitle], [PersonalizationButton], /// [PersonalizationProductsList], [PersonalizationDots]. -class PersonalizationRecommenderBlock extends StatefulWidget { - const PersonalizationRecommenderBlock({ +class PersonalizationProductsBlock extends StatefulWidget { + const PersonalizationProductsBlock({ super.key, this.layout = PersonalizationProductsLayout.carousel, - required this.title, + this.title, this.showAllText, this.onShowAll, - this.showDots = true, + this.showDots = false, required this.products, this.imageAspect = PersonalizationProductImageAspect.square, this.onProductAction, this.onProductTap, + this.showRating = true, this.iconBuilder, }); final PersonalizationProductsLayout layout; - final String title; + + /// Заголовок блока. `null` или пустая строка — без заголовка; строка заголовка + /// остаётся, только если в ней есть кнопка «показать все». + final String? title; /// Подпись кнопки «показать все» у карусели. `null` — без кнопки. final String? showAllText; final VoidCallback? onShowAll; - /// У карусели точки под лентой; выключаются, как в макете (showDots). + /// Точки под каруселью (showDots в макете). По умолчанию выключены: лента прокручивается + /// свободно, а не постранично, и точка на каждый товар индикатором не служит. final bool showDots; final List products; @@ -51,6 +57,10 @@ class PersonalizationRecommenderBlock extends StatefulWidget { /// Нажатие на карточку — открыть товар. final ValueChanged? onProductTap; + /// Рисовать ли рейтинг товаров. `false` — карточки без рейтинга, даже если он у + /// товара есть. + final bool showRating; + final Widget Function( BuildContext context, String asset, @@ -60,12 +70,12 @@ class PersonalizationRecommenderBlock extends StatefulWidget { iconBuilder; @override - State createState() => - _PersonalizationRecommenderBlockState(); + State createState() => + _PersonalizationProductsBlockState(); } -class _PersonalizationRecommenderBlockState - extends State { +class _PersonalizationProductsBlockState + extends State { int _page = 0; @override @@ -76,31 +86,36 @@ class _PersonalizationRecommenderBlockState carousel && widget.showAllText != null && widget.showAllText!.isNotEmpty; + final title = widget.title ?? ''; + final bool header = title.isNotEmpty || showAll; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ - PersonalizationTitle( - title: widget.title, - trailing: showAll - ? PersonalizationButton( - label: widget.showAllText, - size: PersonalizationButtonSize.sm, - view: PersonalizationButtonView.ghost, - iconEnd: PersonalizationIcons.angleLargeRight, - iconBuilder: widget.iconBuilder, - onPressed: widget.onShowAll, - ) - : null, - ), - SizedBox(height: gap), + if (header) ...[ + PersonalizationTitle( + title: title, + trailing: showAll + ? PersonalizationButton( + label: widget.showAllText, + size: PersonalizationButtonSize.sm, + view: PersonalizationButtonView.ghost, + iconEnd: PersonalizationIcons.angleLargeRight, + iconBuilder: widget.iconBuilder, + onPressed: widget.onShowAll, + ) + : null, + ), + SizedBox(height: gap), + ], PersonalizationProductsList( layout: widget.layout, products: widget.products, imageAspect: widget.imageAspect, onProductAction: widget.onProductAction, onProductTap: widget.onProductTap, + showRating: widget.showRating, onFirstVisibleChanged: carousel ? (int index) => setState(() => _page = index) : null, diff --git a/lib/src/ui/components/personalization_products_list.dart b/lib/src/ui/components/personalization_products_list.dart index ab269d7..fa4bdeb 100644 --- a/lib/src/ui/components/personalization_products_list.dart +++ b/lib/src/ui/components/personalization_products_list.dart @@ -27,6 +27,7 @@ class PersonalizationProductsList extends StatefulWidget { this.onProductTap, this.onFirstVisibleChanged, this.carouselPadding, + this.showRating = true, this.iconBuilder, }); @@ -45,6 +46,10 @@ class PersonalizationProductsList extends StatefulWidget { /// обрезаются полем. У плитки и списка поля задаёт разметка хоста. final EdgeInsetsGeometry? carouselPadding; + /// Рисовать ли рейтинг товаров. `false` — карточки без рейтинга, даже если он у + /// товара есть. + final bool showRating; + final Widget Function( BuildContext context, String asset, @@ -103,7 +108,7 @@ class _PersonalizationProductsListState imageAspect: widget.imageAspect, brand: product.brand, name: product.name, - rating: product.rating, + rating: widget.showRating ? product.rating : null, price: product.price, oldPrice: product.oldPrice, discount: product.discount, diff --git a/lib/src/ui/components/personalization_search_results_title.dart b/lib/src/ui/components/personalization_search_results_title.dart index 8233567..7f270e5 100644 --- a/lib/src/ui/components/personalization_search_results_title.dart +++ b/lib/src/ui/components/personalization_search_results_title.dart @@ -18,7 +18,9 @@ class PersonalizationSearchFilter { final VoidCallback onRemove; } -/// Строка «найдено N товаров». Слова — параметры, локализация за интегратором. +/// Строка «найдено N товаров». Слова — параметры, локализация за интегратором; пустой +/// [prefix] не рисуется. [count] `null` — число ещё неизвестно (выдача грузится): кнопки +/// на месте, а «Найдено 0» не рисуется. class PersonalizationSearchResults { const PersonalizationSearchResults({ required this.prefix, @@ -27,7 +29,7 @@ class PersonalizationSearchResults { }); final String prefix; - final int count; + final int? count; final String suffix; } @@ -148,11 +150,16 @@ class PersonalizationSearchResultsTitle extends StatelessWidget { ), if (showFiltersButton || showSortButton) const SizedBox(width: 12), - Text(results!.prefix, style: regular), - const SizedBox(width: 4), - Text('${results!.count}', style: strong), - const SizedBox(width: 4), - Text(results!.suffix, style: strong), + if (results!.count != null) ...[ + // Без префикса — просто «N товаров», как в заголовке категории. + if (results!.prefix.isNotEmpty) ...[ + Text(results!.prefix, style: regular), + const SizedBox(width: 4), + ], + Text('${results!.count}', style: strong), + const SizedBox(width: 4), + Text(results!.suffix, style: strong), + ], ], ), ], diff --git a/lib/src/ui/components/personalization_story_navigation.dart b/lib/src/ui/components/personalization_story_navigation.dart index 6d57dee..b78ca5b 100644 --- a/lib/src/ui/components/personalization_story_navigation.dart +++ b/lib/src/ui/components/personalization_story_navigation.dart @@ -1,6 +1,8 @@ +import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import '../personalization_icons.dart'; +import '../personalization_spacing.dart'; import '../personalization_theme.dart'; import 'personalization_story_progress.dart'; @@ -11,7 +13,8 @@ import 'personalization_story_progress.dart'; /// /// Колонка с шагом 12: [PersonalizationStoryProgress] и строка высотой 32, в конце /// которой крестик — иконка cross 32 (глиф 18) цвета Text/Secondary с прозрачностью 65%. -/// Касания ловит только крестик. +/// С [onShare] слева от крестика, через 8, — «Поделиться» в том же виде: коробка 32, +/// глиф 18, Text/Secondary, 65%, без фона. Касания ловят только кнопки. class PersonalizationStoryNavigation extends StatelessWidget { const PersonalizationStoryNavigation({ super.key, @@ -20,6 +23,8 @@ class PersonalizationStoryNavigation extends StatelessWidget { this.progress = 0, this.onClose, this.closeLabel = 'Close', + this.onShare, + this.shareLabel = 'Share', this.iconBuilder, }); @@ -33,6 +38,13 @@ class PersonalizationStoryNavigation extends StatelessWidget { /// Подпись крестика для скринридера. final String closeLabel; + /// Нажата «Поделиться»; `null` — кнопки нет. Приходит кнопка в глобальных логических + /// координатах: к ней на iPad крепится системное окно. + final ValueChanged? onShare; + + /// Подпись «Поделиться» для скринридера. + final String shareLabel; + /// Как нарисовать крестик: пакет не рисует SVG сам. final Widget Function( BuildContext context, @@ -66,31 +78,103 @@ class PersonalizationStoryNavigation extends StatelessWidget { const SizedBox(height: 12), SizedBox( height: _close, - child: Align( - alignment: AlignmentDirectional.centerEnd, - child: Semantics( - button: true, - label: closeLabel, - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: onClose, - child: SizedBox.square( - dimension: _close, - child: Opacity( - opacity: 0.65, - child: iconBuilder?.call( + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + if (onShare != null) ...[ + Semantics( + button: true, + label: shareLabel, + child: _ShareButton( + onPressed: onShare!, + child: _icon( context, - PersonalizationIcons.cross, - _close, + PersonalizationIcons.share, colors.textSecondary, ), ), ), + const SizedBox(width: PersonalizationSpacing.md), + ], + Semantics( + button: true, + label: closeLabel, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onClose, + child: _icon( + context, + PersonalizationIcons.cross, + colors.textSecondary, + ), + ), ), - ), + ], ), ), ], ); } + + /// Иконка кнопки шапки: коробка 32, прозрачность 65%. + Widget _icon(BuildContext context, String asset, Color color) => + SizedBox.square( + dimension: _close, + child: Opacity( + opacity: 0.65, + child: iconBuilder?.call(context, asset, _close, color), + ), + ); +} + +/// «Поделиться»: нажатие любой длины — нажатие. Удержание и свайпы, начатые на кнопке, +/// забирает она сама — слайд под ней не встаёт на паузу удержания и не листается. +class _ShareButton extends StatelessWidget { + const _ShareButton({required this.onPressed, required this.child}); + + final ValueChanged onPressed; + final Widget child; + + /// Короче удержания слайда (200 мс): долгое нажатие достаётся кнопке, а не слайду. + static const Duration _hold = Duration(milliseconds: 150); + + void _press(BuildContext context) { + final box = context.findRenderObject() as RenderBox?; + if (box == null || !box.hasSize) return; + onPressed(box.localToGlobal(Offset.zero) & box.size); + } + + @override + Widget build(BuildContext context) => RawGestureDetector( + behavior: HitTestBehavior.opaque, + gestures: { + TapGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + TapGestureRecognizer.new, + (recognizer) => recognizer.onTap = () => _press(context), + ), + LongPressGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + () => LongPressGestureRecognizer(duration: _hold), + (recognizer) => recognizer.onLongPressEnd = (details) { + // Отпустили на кнопке — нажатие; увели палец — ничего. + final box = context.findRenderObject() as RenderBox?; + if (box != null && box.size.contains(details.localPosition)) { + _press(context); + } + }, + ), + VerticalDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + VerticalDragGestureRecognizer.new, + (recognizer) => recognizer.onStart = (_) {}, + ), + HorizontalDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + HorizontalDragGestureRecognizer.new, + (recognizer) => recognizer.onStart = (_) {}, + ), + }, + child: child, + ); } diff --git a/lib/src/ui/components/personalization_story_poll.dart b/lib/src/ui/components/personalization_story_poll.dart new file mode 100644 index 0000000..84ff8ec --- /dev/null +++ b/lib/src/ui/components/personalization_story_poll.dart @@ -0,0 +1,1100 @@ +import 'dart:ui' show ImageFilter; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart' + show + InputDecoration, + Material, + MaterialType, + TextField, + TextSelectionTheme, + TextSelectionThemeData; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../../stories/stories_response.dart'; +import '../personalization_radius.dart'; +import '../personalization_spacing.dart'; +import '../personalization_theme.dart'; +import '../personalization_typography.dart'; +import '../widgets/stories_poll.dart'; +import '../widgets/stories_polls_api.dart'; + +/// Значения карточки опроса: матовая светлая карточка, текст по левому краю, варианты +/// с буквами, шкала — дорожкой. Карточка светлая и в тёмной теме: текст — тёмные токены +/// кита (`textDark*`), акцент — цвет выбора опроса. Дизайнер меняет их здесь разом; где +/// в ките есть токен с тем же значением, взят токен. +abstract final class _Poll { + // Цвета. + /// Акцент: выбор, основная кнопка, точка шапки итогов. + static const Color accent = Color(0xFF22C55E); + + /// Заливка выбранного варианта до отправки — акцент 20 %. + static const Color accentFill = Color(0x3322C55E); + + /// Полоска итога моего ответа — акцент 25 %. + static const Color accentBar = Color(0x4022C55E); + + /// Подложка карточки поверх размытия — белый 80 %. + static const Color card = Color(0xCCFFFFFF); + + /// Граница карточки — белый 50 %. + static const Color cardBorder = Color(0x80FFFFFF); + + /// Подложка вариантов, дорожки шкалы и неактивной кнопки — чёрный 6 %. + static const Color well = Color(0x0F000000); + + /// Полоска итога варианта — чёрный 8 %. + static const Color bar = Color(0x14000000); + + /// Квадрат буквы и поле ввода — белый 85 %. + static const Color light = Color(0xD9FFFFFF); + static const Color white = Color(0xFFFFFFFF); + static const Color error = Color(0xFFDC2626); + + // Размеры. + static const double maxWidth = 420; + static const double edge = PersonalizationSpacing.lg; + static const double radius = PersonalizationRadius.xl6; + static const double padding = PersonalizationSpacing.xl2; + static const double blur = 20; + static const double cardBorderWidth = 1; + static const double dot = 6; + static const double dotGap = PersonalizationSpacing.md; + + /// От шапки итогов до вопроса. + static const double headerGap = PersonalizationSpacing.lg; + + /// От вопроса до содержимого, от содержимого до подвала, кнопки и текста полосы. + static const double gap = PersonalizationSpacing.xl; + + /// Ссылка «Ответить заново» и ошибка под содержимым. + static const double noteGap = PersonalizationSpacing.lg; + static const double rowHeight = 56; + static const double rowRadius = PersonalizationRadius.xl5; + static const double rowPadding = PersonalizationSpacing.lg; + static const double rowsGap = PersonalizationSpacing.md; + static const double letter = 32; + static const double letterRadius = PersonalizationRadius.lg; + static const double letterGap = PersonalizationSpacing.lg; + static const double selectedBorder = 1.5; + static const double track = 52; + static const double trackPadding = PersonalizationSpacing.sm; + static const double field = 52; + static const double fieldRadius = PersonalizationRadius.xl4; + static const EdgeInsets fieldPadding = EdgeInsets.symmetric( + horizontal: PersonalizationSpacing.xl, + vertical: 14, + ); + + /// Поле растёт до стольких строк, дальше прокрутка внутри. + static const int fieldLines = 4; + + /// От поля (или счётчика) до кнопки. + static const double fieldGap = PersonalizationSpacing.lg; + static const double counterGap = PersonalizationSpacing.sm; + static const double button = 52; + static const double buttonRadius = PersonalizationRadius.xl4; + static const EdgeInsets buttonPadding = EdgeInsets.symmetric( + horizontal: PersonalizationSpacing.xl, + vertical: 14, + ); + static const double checkStroke = 2.5; + static const double dimmed = 0.55; + static const double sendingOpacity = 0.85; + static const double linkPadding = PersonalizationSpacing.sm; + static const Duration fillDuration = Duration(milliseconds: 600); + static const Curve fillCurve = Cubic(0.2, 0.8, 0.2, 1); + + // Шрифт — кегли кита. + static const TextStyle header = PersonalizationTypography.xsEmphasized; + + /// Разрядка шапки итогов — 0,08 em. + static const double headerTracking = 0.08; + static const TextStyle question = PersonalizationTypography.lgEmphasized; + + /// Межстрочный вопроса. + static const double questionLine = 24; + static const TextStyle body = PersonalizationTypography.baseDefault; + static const TextStyle bodyStrong = PersonalizationTypography.baseEmphasized; + static const TextStyle small = PersonalizationTypography.smDefault; + static const TextStyle smallStrong = PersonalizationTypography.smEmphasized; + static const TextStyle note = PersonalizationTypography.xsDefault; +} + +/// Карточка опроса на слайде сторис V2: мини-опрос (выбор одного, выбор нескольких, +/// текст) или шкала NPS / CSAT / CES. Логика — [StoryPollController]. +/// +/// - Касание, начатое на карточке, слайду не достаётся: она забирает свайпы, а касание +/// по третям и удержание слайда пропускают её касания ([StoryPollPointers]). +/// - Пока карточку держат пальцем, в фокусе поле или идёт отправка — [onHold]`(true)`; +/// только у живого слайда ([live]). Не живая — не нажимается. +/// - Поле ввода — [TextField] в прозрачном `Material`; нужны `MaterialLocalizations` +/// хоста (как у `PersonalizationInputField`). Свернули приложение — клавиатура уходит; +/// система убрала клавиатуру («назад» на Android) — поле отпускает фокус. +/// - Карточка матовая: размывает слайд под собой. +/// - Тексты итогов выбора — по языку устройства ([StoryPollResultTexts]). +/// - RTL: поля, полоски итогов и шкала зеркалятся. +class PersonalizationStoryPoll extends StatefulWidget { + const PersonalizationStoryPoll({ + super.key, + required this.poll, + required this.storyId, + required this.slideId, + required this.transport, + this.shopId = '', + this.texts = const StoryPollTexts(), + this.live = true, + this.onHold, + }); + + final StoryPollElement poll; + final String storyId; + final String slideId; + final StoryPollsTransport transport; + + /// Магазин — ключ хранилища ответов сессии. + final String shopId; + + /// Тексты хоста; `labels` опроса важнее. + final StoryPollTexts texts; + final bool live; + final ValueChanged? onHold; + + /// Ширина карточки на слайде шириной [width]: по 12 от краёв, не шире 420. + static double widthFor(double width) => + (width - 2 * _Poll.edge).clamp(0, _Poll.maxWidth).toDouble(); + + @override + State createState() => + _PersonalizationStoryPollState(); +} + +class _PersonalizationStoryPollState extends State + with WidgetsBindingObserver { + late final StoryPollController _poll = StoryPollController( + poll: widget.poll, + storyId: widget.storyId, + slideId: widget.slideId, + transport: widget.transport, + shopId: widget.shopId, + texts: widget.texts, + active: widget.live, + onHold: (held) => widget.onHold?.call(held), + ); + final TextEditingController _input = TextEditingController(); + final FocusNode _focus = FocusNode(debugLabel: 'story poll'); + + /// Пальцы на карточке. + final Set _pointers = {}; + bool _wasAnswered = false; + + /// Высота клавиатуры в прошлый раз. + double _keyboard = 0; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _wasAnswered = _poll.answered; + _poll.addListener(_onPoll); + _focus.addListener(_onFocus); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // Система убрала клавиатуру («назад» на Android) — поле отпускает фокус, слайд идёт + // дальше, а не стоит с курсором без клавиатуры. С аппаратной клавиатурой отступ всё + // время 0 — фокус остаётся. + final keyboard = MediaQuery.maybeViewInsetsOf(context)?.bottom ?? 0; + if (_keyboard > 0 && keyboard == 0 && _focus.hasFocus) _focus.unfocus(); + _keyboard = keyboard; + } + + @override + void didUpdateWidget(PersonalizationStoryPoll oldWidget) { + super.didUpdateWidget(oldWidget); + _poll.active = widget.live; + if (!widget.live) _focus.unfocus(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + // Свернули приложение — клавиатуру убрать. + if (state == AppLifecycleState.paused || + state == AppLifecycleState.hidden) { + _focus.unfocus(); + } + } + + @override + void didChangeLocales(List? locales) { + // Тексты итогов — по языку устройства. + if (mounted) setState(() {}); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _pointers.forEach(StoryPollPointers.release); + _poll + ..removeListener(_onPoll) + ..dispose(); + _focus.dispose(); + _input.dispose(); + super.dispose(); + } + + void _onPoll() { + if (!_poll.showsField && _focus.hasFocus) _focus.unfocus(); + // «Ответить заново» у текста: пустое поле в фокусе, как в вебе. + if (_wasAnswered && !_poll.answered && _poll.showsField) { + _input.clear(); + _focus.requestFocus(); + } + _wasAnswered = _poll.answered; + setState(() {}); + } + + void _onFocus() => _poll.focused = _focus.hasFocus; + + void _down(PointerDownEvent event) { + StoryPollPointers.claim(event.pointer); + _pointers.add(event.pointer); + _poll.pressed = true; + } + + void _up(PointerEvent event) { + StoryPollPointers.release(event.pointer); + _pointers.remove(event.pointer); + _poll.pressed = _pointers.isNotEmpty; + } + + /// Тексты итогов у отвеченного выбора; у остального — `null`. + StoryPollResultTexts? get _summary { + final choice = switch (widget.poll.kind) { + StoryMiniPollKind.singleChoice || + StoryMiniPollKind.multipleChoice => true, + _ => false, + }; + if (!choice || !_poll.answered) return null; + return StoryPollResultTexts.of( + WidgetsBinding.instance.platformDispatcher.locale.languageCode, + ); + } + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final poll = _poll; + final texts = poll.texts; + final element = widget.poll; + final summary = _summary; + final rows = <(Widget, double)>[ + if (summary != null) (_header(theme, summary.results), 0), + if (element.question.isNotEmpty) + ( + Text( + element.question, + style: _style( + theme, + _Poll.question, + height: _Poll.questionLine / _Poll.question.fontSize!, + ), + ), + _Poll.headerGap, + ), + ..._body(theme, summary), + if (poll.answered && element.allowReanswer) + ( + Align( + alignment: AlignmentDirectional.centerStart, + child: _Tap( + onTap: poll.reanswer, + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: _Poll.linkPadding, + ), + child: Text( + texts.reanswer, + style: _style(theme, _Poll.smallStrong).copyWith( + decoration: TextDecoration.underline, + decorationColor: theme.colors.textDarkPrimary, + ), + ), + ), + ), + ), + _Poll.noteGap, + ), + if (poll.failed) + ( + Semantics( + liveRegion: true, + child: Text( + texts.error, + style: _style(theme, _Poll.note, color: _Poll.error), + ), + ), + _Poll.noteGap, + ), + ]; + final radius = BorderRadius.circular(_Poll.radius); + // Матовая: размытие слайда под карточкой и светлая подложка. Прозрачность отправки — + // у подложки с содержимым: размытию нужен слайд, а не пустой слой. + final card = ClipRRect( + borderRadius: radius, + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: _Poll.blur, sigmaY: _Poll.blur), + child: Opacity( + opacity: poll.sending ? _Poll.sendingOpacity : 1, + child: DecoratedBox( + position: DecorationPosition.foreground, + decoration: BoxDecoration( + border: Border.all( + color: _Poll.cardBorder, + width: _Poll.cardBorderWidth, + ), + borderRadius: radius, + ), + child: ColoredBox( + color: _Poll.card, + // Не влезает между шапкой и кнопками — прокрутка внутри, без + // перелистывания. + child: SingleChildScrollView( + physics: const ClampingScrollPhysics(), + padding: const EdgeInsets.all(_Poll.padding), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final (index, (row, gap)) in rows.indexed) ...[ + if (index > 0) SizedBox(height: gap), + row, + ], + ], + ), + ), + ), + ), + ), + ), + ); + return Listener( + behavior: HitTestBehavior.opaque, + onPointerDown: _down, + onPointerUp: _up, + onPointerCancel: _up, + // Свайпы, начатые на карточке, — её: просмотр не листается и не закрывается. + child: RawGestureDetector( + behavior: HitTestBehavior.opaque, + gestures: { + VerticalDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers< + VerticalDragGestureRecognizer + >( + VerticalDragGestureRecognizer.new, + (recognizer) => recognizer.onStart = (_) {}, + ), + HorizontalDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers< + HorizontalDragGestureRecognizer + >( + HorizontalDragGestureRecognizer.new, + (recognizer) => recognizer.onStart = (_) {}, + ), + }, + child: Semantics( + container: true, + // TextField требует предка Material; прозрачный ничего не рисует. + child: Material(type: MaterialType.transparency, child: card), + ), + ), + ); + } +} + +/// Содержимое карточки по виду и состоянию: строки и зазор перед каждой. +extension on _PersonalizationStoryPollState { + List<(Widget, double)> _body( + PersonalizationTheme theme, + StoryPollResultTexts? summary, + ) { + final poll = _poll; + final element = widget.poll; + if (element.pollType.isScale) { + final band = poll.answered + ? storyPollBandText(element, poll.answer?.rate) + : null; + return <(Widget, double)>[ + (_scale(theme), _Poll.gap), + if (band != null && band.isNotEmpty) + (Text(band, style: _style(theme, _Poll.small)), _Poll.gap), + ]; + } + switch (element.kind) { + case StoryMiniPollKind.singleChoice || StoryMiniPollKind.multipleChoice + when summary != null: + return <(Widget, double)>[ + (_answeredOptions(theme), _Poll.gap), + (_footer(theme, summary), _Poll.gap), + ]; + case StoryMiniPollKind.singleChoice: + return <(Widget, double)>[(_choiceOptions(theme), _Poll.gap)]; + case StoryMiniPollKind.multipleChoice: + return <(Widget, double)>[ + (_choiceOptions(theme, multiple: true), _Poll.gap), + (_submit(theme, poll.submitChoices), _Poll.gap), + ]; + case StoryMiniPollKind.text when poll.answered: + return <(Widget, double)>[(_done(theme), _Poll.gap)]; + case StoryMiniPollKind.text: + final limit = element.maxLength; + return <(Widget, double)>[ + (_field(theme), _Poll.gap), + if (limit != null) + ( + Text( + '${poll.text.length}/$limit', + textAlign: TextAlign.end, + style: _style( + theme, + _Poll.note, + color: theme.colors.textDarkSecondary, + tabular: true, + ), + ), + _Poll.counterGap, + ), + (_submit(theme, poll.submitText), _Poll.fieldGap), + ]; + case null: + return const <(Widget, double)>[]; + } + } + + Widget _list(List children) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final (index, child) in children.indexed) ...[ + if (index > 0) const SizedBox(height: _Poll.rowsGap), + child, + ], + ], + ); + + /// Форма выбора: у одного нажатие отправляет, нажатый вариант сразу подсвечен; у + /// нескольких — переключает вариант. + Widget _choiceOptions(PersonalizationTheme theme, {bool multiple = false}) => + _list([ + for (final (index, option) in widget.poll.options.indexed) + _OptionRow( + theme: theme, + letter: _letter(index), + label: option.label, + selected: _poll.selected.contains(option.id), + onTap: _poll.sending + ? null + : multiple + ? () => _poll.toggle(option.id) + : () => _poll.choose(option.id), + ), + ]); + + /// Отвеченный выбор: ответ подсвечен, с итогами — полоски и проценты. + Widget _answeredOptions(PersonalizationTheme theme) { + final selected = {...?_poll.answer?.optionIds}; + final results = _poll.results; + return _list([ + for (final (index, option) in widget.poll.options.indexed) + _OptionRow( + theme: theme, + letter: _letter(index), + label: option.label, + selected: selected.contains(option.id), + answered: true, + percent: results?.percentOf(option.id), + ), + ]); + } + + /// Шапка итогов: точка акцента и «РЕЗУЛЬТАТЫ». + Widget _header(PersonalizationTheme theme, String text) => Row( + children: [ + const SizedBox.square( + dimension: _Poll.dot, + child: DecoratedBox( + decoration: BoxDecoration( + color: _Poll.accent, + shape: BoxShape.circle, + ), + ), + ), + const SizedBox(width: _Poll.dotGap), + Flexible( + child: Text( + text.toUpperCase(), + semanticsLabel: text, + style: _style( + theme, + _Poll.header, + color: theme.colors.textDarkSecondary, + tracking: _Poll.headerTracking * _Poll.header.fontSize!, + ), + ), + ), + ], + ); + + /// Подвал итогов: благодарность опроса или «Спасибо! Голос учтён»; справа — число + /// голосов, если оно есть. + Widget _footer(PersonalizationTheme theme, StoryPollResultTexts texts) { + final thanks = widget.poll.thanksText; + final total = _poll.results?.total ?? 0; + final strong = _style(theme, _Poll.smallStrong); + final muted = _style( + theme, + _Poll.small, + color: theme.colors.textDarkSecondary, + ); + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: thanks.isNotEmpty + ? Text(thanks, style: strong) + : Text.rich( + TextSpan( + children: [ + TextSpan(text: texts.thanks, style: strong), + TextSpan(text: ' ${texts.counted}', style: muted), + ], + ), + ), + ), + if (total > 0) ...[ + const SizedBox(width: _Poll.letterGap), + Text(texts.votes(total), style: muted), + ], + ], + ); + } + + Widget _submit(PersonalizationTheme theme, VoidCallback send) { + final label = widget.poll.submitLabel.isNotEmpty + ? widget.poll.submitLabel + : _poll.texts.submit; + final enabled = _poll.canSubmit; + return Semantics( + button: true, + enabled: enabled, + child: _Tap( + onTap: enabled ? send : null, + child: Container( + constraints: const BoxConstraints(minHeight: _Poll.button), + alignment: Alignment.center, + padding: _Poll.buttonPadding, + decoration: BoxDecoration( + color: enabled ? _Poll.accent : _Poll.well, + borderRadius: BorderRadius.circular(_Poll.buttonRadius), + ), + child: Text( + label, + textAlign: TextAlign.center, + style: _style( + theme, + _Poll.bodyStrong, + color: enabled + ? _onFill(_Poll.accent, theme.colors.textDarkPrimary) + : theme.colors.textDarkSecondary, + ), + ), + ), + ), + ); + } +} + +/// Поле, отвеченный текст и шкала. +extension on _PersonalizationStoryPollState { + /// Поле ввода: растёт до [_Poll.fieldLines] строк; предел `max_length` обрезает + /// ввод; пока идёт отправка, текст не меняется, а клавиатура остаётся. + Widget _field(PersonalizationTheme theme) { + final style = _style(theme, _Poll.body); + final placeholder = widget.poll.placeholder; + return Container( + constraints: const BoxConstraints(minHeight: _Poll.field), + padding: _Poll.fieldPadding, + alignment: AlignmentDirectional.centerStart, + decoration: BoxDecoration( + color: _Poll.light, + borderRadius: BorderRadius.circular(_Poll.fieldRadius), + ), + child: TextSelectionTheme( + data: TextSelectionThemeData( + cursorColor: theme.colors.textDarkPrimary, + selectionColor: _Poll.accentBar, + selectionHandleColor: _Poll.accent, + ), + child: TextField( + controller: _input, + focusNode: _focus, + minLines: 1, + maxLines: _Poll.fieldLines, + keyboardType: TextInputType.multiline, + textCapitalization: TextCapitalization.sentences, + keyboardAppearance: Brightness.light, + cursorColor: theme.colors.textDarkPrimary, + style: style, + inputFormatters: [ + _PollInputFormatter( + limit: widget.poll.maxLength, + frozen: () => _poll.sending, + ), + ], + onChanged: (value) => _poll.text = value, + decoration: InputDecoration.collapsed( + hintText: placeholder.isEmpty ? null : placeholder, + hintStyle: style.copyWith(color: theme.colors.textDarkHint), + ), + ), + ), + ); + } + + /// Отвеченный текст: кружок с галочкой и благодарность, под ними сам ответ. + Widget _done(PersonalizationTheme theme) { + final thanks = widget.poll.thanksText; + final text = _poll.answer?.text ?? ''; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + _Mark(theme: theme, circle: true), + if (thanks.isNotEmpty) ...[ + const SizedBox(width: _Poll.letterGap), + Expanded( + child: Text(thanks, style: _style(theme, _Poll.bodyStrong)), + ), + ], + ], + ), + if (text.isNotEmpty) ...[ + const SizedBox(height: _Poll.letterGap), + Text( + text, + style: _style( + theme, + _Poll.body, + color: theme.colors.textDarkSecondary, + ), + ), + ], + ], + ); + } + + /// Шкала — дорожка, цифры поровну. В форме нажатие отправляет; выбранная — капсула + /// цвета её полосы, у отвеченной остальные приглушены. + Widget _scale(PersonalizationTheme theme) { + final element = widget.poll; + final values = storyPollScaleRange(element); + if (values.isEmpty) return const SizedBox.shrink(); + final answered = _poll.answered; + final highlighted = _poll.rateValue; + return Container( + constraints: const BoxConstraints(minHeight: _Poll.track), + padding: const EdgeInsets.symmetric(horizontal: _Poll.trackPadding), + decoration: const BoxDecoration( + color: _Poll.well, + borderRadius: BorderRadius.all( + Radius.circular(PersonalizationRadius.rounded), + ), + ), + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final value in values) + Expanded( + child: _ScaleCell( + theme: theme, + value: value, + // Без полос — акцент. + color: element.bands.isEmpty + ? _Poll.accent + : storyPollScaleColor( + element.pollType, + value, + values.first, + values.last, + ), + selected: value == highlighted, + dimmed: answered && value != highlighted, + onTap: answered || _poll.sending + ? null + : () => _poll.rate(value), + ), + ), + ], + ), + ), + ); + } +} + +/// Буква варианта по номеру: A…Z, дальше AA, AB… +String _letter(int index) { + var letters = ''; + for (var rest = index + 1; rest > 0; rest = (rest - 1) ~/ 26) { + letters = String.fromCharCode(65 + (rest - 1) % 26) + letters; + } + return letters; +} + +/// Стиль текста карточки: кегль [token] кита, шрифт темы, свой цвет — по умолчанию +/// тёмный основной: карточка светлая в любой теме. +TextStyle _style( + PersonalizationTheme theme, + TextStyle token, { + Color? color, + double? height, + double? tracking, + bool tabular = false, +}) { + final weight = token.fontWeight ?? FontWeight.w400; + return TextStyle( + fontSize: token.fontSize, + height: height ?? token.height, + fontWeight: weight, + letterSpacing: tracking ?? token.letterSpacing ?? 0, + color: color ?? theme.colors.textDarkPrimary, + decoration: TextDecoration.none, + fontFamily: theme.fontFamily.familyFor(weight), + package: theme.fontFamily.package, + fontFeatures: tabular + ? const [FontFeature.tabularFigures()] + : null, + ); +} + +/// Цвет текста и значков на заливке [fill] — текста основной кнопки, галочки, цифры +/// шкалы: белый или [dark] — что контрастнее. +Color _onFill(Color fill, Color dark) { + final luminance = fill.computeLuminance() + 0.05; + final white = 1.05 / luminance; + final black = luminance / (dark.computeLuminance() + 0.05); + return white > black ? _Poll.white : dark; +} + +/// Нажимаемая область; `onTap == null` — не нажимается. +class _Tap extends StatelessWidget { + const _Tap({required this.onTap, required this.child}); + + final VoidCallback? onTap; + final Widget child; + + @override + Widget build(BuildContext context) => GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onTap, + child: child, + ); +} + +/// Вариант выбора: квадрат с буквой, подпись до двух строк; выбранный — в рамке +/// акцента, с галочкой вместо буквы, до отправки ещё и залит акцентом. У отвеченного +/// ([answered]) с итогами — процент справа и полоска доли от начала строки (растёт от +/// нуля), у моего ответа — акцента. +class _OptionRow extends StatelessWidget { + const _OptionRow({ + required this.theme, + required this.letter, + required this.label, + required this.selected, + this.answered = false, + this.percent, + this.onTap, + }); + + final PersonalizationTheme theme; + final String letter; + final String label; + final bool selected; + + /// Строка итогов: мой ответ без заливки, только рамка и полоска. + final bool answered; + final int? percent; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + final percent = this.percent; + final radius = BorderRadius.circular(_Poll.rowRadius); + final content = Padding( + padding: const EdgeInsets.all(_Poll.rowPadding), + child: Row( + children: [ + selected + ? _Mark(theme: theme) + : _LetterBox(theme: theme, letter: letter), + const SizedBox(width: _Poll.letterGap), + Expanded( + child: Text( + label, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: _style(theme, _Poll.body), + ), + ), + if (percent != null) ...[ + const SizedBox(width: _Poll.letterGap), + Text( + '$percent%', + style: _style(theme, _Poll.bodyStrong, tabular: true), + ), + ], + ], + ), + ); + final row = Container( + constraints: const BoxConstraints(minHeight: _Poll.rowHeight), + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + color: selected && !answered ? _Poll.accentFill : _Poll.well, + borderRadius: radius, + ), + foregroundDecoration: selected + ? BoxDecoration( + border: Border.all( + color: _Poll.accent, + width: _Poll.selectedBorder, + ), + borderRadius: radius, + ) + : null, + child: percent == null + ? content + : Stack( + children: [ + Positioned.fill( + child: _Fill( + value: percent / 100, + color: selected ? _Poll.accentBar : _Poll.bar, + ), + ), + content, + ], + ), + ); + return Semantics( + button: onTap != null, + selected: selected, + child: onTap == null ? row : _Tap(onTap: onTap, child: row), + ); + } +} + +/// Квадрат буквы варианта. +class _LetterBox extends StatelessWidget { + const _LetterBox({required this.theme, required this.letter}); + + final PersonalizationTheme theme; + final String letter; + + @override + Widget build(BuildContext context) => Container( + width: _Poll.letter, + height: _Poll.letter, + alignment: Alignment.center, + decoration: BoxDecoration( + color: _Poll.light, + borderRadius: BorderRadius.circular(_Poll.letterRadius), + ), + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + letter, + maxLines: 1, + style: _style( + theme, + _Poll.smallStrong, + color: theme.colors.textDarkSecondary, + ), + ), + ), + ); +} + +/// Галочка на акценте — белая или тёмная по контрасту: квадрат выбранного варианта +/// или кружок отвеченного текста ([circle]). +class _Mark extends StatelessWidget { + const _Mark({required this.theme, this.circle = false}); + + final PersonalizationTheme theme; + final bool circle; + + @override + Widget build(BuildContext context) => SizedBox.square( + dimension: _Poll.letter, + child: DecoratedBox( + decoration: BoxDecoration( + color: _Poll.accent, + shape: circle ? BoxShape.circle : BoxShape.rectangle, + borderRadius: circle ? null : BorderRadius.circular(_Poll.letterRadius), + ), + child: CustomPaint( + painter: _Check(_onFill(_Poll.accent, theme.colors.textDarkPrimary)), + ), + ), + ); +} + +/// Галочка цвета [color] по центру квадрата. +class _Check extends CustomPainter { + const _Check(this.color); + + final Color color; + + @override + void paint(Canvas canvas, Size size) { + canvas.drawPath( + Path() + ..moveTo(size.width * 0.31, size.height * 0.5) + ..lineTo(size.width * 0.44, size.height * 0.63) + ..lineTo(size.width * 0.69, size.height * 0.38), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = _Poll.checkStroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..color = color, + ); + } + + @override + bool shouldRepaint(_Check oldDelegate) => oldDelegate.color != color; +} + +/// Полоска итога варианта: от нуля до [value] (0…1) за 0,6 с; без анимаций в системе — +/// сразу. +class _Fill extends StatelessWidget { + const _Fill({required this.value, required this.color}); + + final double value; + final Color color; + + @override + Widget build(BuildContext context) { + final still = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + return TweenAnimationBuilder( + tween: Tween(begin: 0, end: value.clamp(0, 1).toDouble()), + duration: still ? Duration.zero : _Poll.fillDuration, + curve: _Poll.fillCurve, + builder: (context, width, _) => Align( + alignment: AlignmentDirectional.centerStart, + child: FractionallySizedBox( + widthFactor: width, + heightFactor: 1, + child: ColoredBox(color: color), + ), + ), + ); + } +} + +/// Цифра шкалы: выбранная — капсула цвета [color] на всю высоту дорожки, приглушённая +/// — у отвеченной шкалы. +class _ScaleCell extends StatelessWidget { + const _ScaleCell({ + required this.theme, + required this.value, + required this.color, + required this.selected, + required this.dimmed, + required this.onTap, + }); + + final PersonalizationTheme theme; + final int value; + final Color color; + final bool selected; + final bool dimmed; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) => Semantics( + button: onTap != null, + selected: selected, + child: _Tap( + onTap: onTap, + child: DecoratedBox( + decoration: selected + ? BoxDecoration( + color: color, + borderRadius: BorderRadius.circular( + PersonalizationRadius.rounded, + ), + ) + : const BoxDecoration(), + child: Center( + child: Opacity( + opacity: dimmed ? _Poll.dimmed : 1, + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + '$value', + maxLines: 1, + style: _style( + theme, + _Poll.bodyStrong, + color: selected + ? _onFill(color, theme.colors.textDarkPrimary) + : theme.colors.textDarkPrimary, + tabular: true, + ), + ), + ), + ), + ), + ), + ), + ); +} + +/// Предел длины поля в кодовых единицах UTF-16, как `maxLength` веба; суррогатную пару +/// не режет, набор через IME обрезает, когда он закончен. [frozen] — текст не меняется. +class _PollInputFormatter extends TextInputFormatter { + _PollInputFormatter({required this.limit, required this.frozen}); + + final int? limit; + final bool Function() frozen; + + @override + TextEditingValue formatEditUpdate( + TextEditingValue oldValue, + TextEditingValue newValue, + ) { + if (frozen() && newValue.text != oldValue.text) return oldValue; + final limit = this.limit; + final text = newValue.text; + if (limit == null || text.length <= limit || newValue.composing.isValid) { + return newValue; + } + var end = limit; + if (end > 0) { + final last = text.codeUnitAt(end - 1); + if (last >= 0xD800 && last <= 0xDBFF) end--; + } + int clamp(int offset) => offset.clamp(0, end); + return TextEditingValue( + text: text.substring(0, end), + selection: newValue.selection.copyWith( + baseOffset: clamp(newValue.selection.baseOffset), + extentOffset: clamp(newValue.selection.extentOffset), + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_wrap_row.dart b/lib/src/ui/components/personalization_wrap_row.dart new file mode 100644 index 0000000..62a4036 --- /dev/null +++ b/lib/src/ui/components/personalization_wrap_row.dart @@ -0,0 +1,279 @@ +import 'dart:math' as math; + +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// Два ребёнка в строку, а когда вместе не влезают — второй переносится под первый. +/// Нужен list-карточке товара: в узкой колонке (экран 360 dp, крупный системный шрифт) +/// цена с бейджем скидки и кнопка в строку не помещаются. Он же держит цену со старой +/// ценой у карточек колонкой: длинные цены («799 990 ₽» и «1 574 990 ₽») в колонку +/// плитки рядом не помещаются. +/// +/// В строке дети выровнены по центру по вертикали (с [alignBottom] — по низу), второй +/// стоит через [horizontalGap] после первого, а с [pinEnd] — у правого края (ряд тогда +/// занимает всю ширину). После переноса второй лежит под первым через [verticalGap] +/// (с [wrapAbove] — над ним): у левого края, а с [pinEnd] — у правого. Ребёнок шире +/// ряда ужимается до него. `Wrap` не подходит: одиночного ребёнка +/// в строке он ставит к началу, а кнопка должна остаться справа. +/// +/// Внутренний: из барреля не экспортируется. +class PersonalizationWrapRow extends MultiChildRenderObjectWidget { + const PersonalizationWrapRow({ + super.key, + required this.horizontalGap, + required this.verticalGap, + this.pinEnd = false, + this.wrapAbove = false, + this.alignBottom = false, + super.children, + }); + + final double horizontalGap; + final double verticalGap; + final bool pinEnd; + final bool wrapAbove; + final bool alignBottom; + + @override + RenderPersonalizationWrapRow createRenderObject(BuildContext context) => + RenderPersonalizationWrapRow( + horizontalGap: horizontalGap, + verticalGap: verticalGap, + pinEnd: pinEnd, + wrapAbove: wrapAbove, + alignBottom: alignBottom, + ); + + @override + void updateRenderObject( + BuildContext context, + RenderPersonalizationWrapRow renderObject, + ) { + renderObject + ..horizontalGap = horizontalGap + ..verticalGap = verticalGap + ..pinEnd = pinEnd + ..wrapAbove = wrapAbove + ..alignBottom = alignBottom; + } +} + +class _WrapRowParentData extends ContainerBoxParentData {} + +class RenderPersonalizationWrapRow extends RenderBox + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { + RenderPersonalizationWrapRow({ + required double horizontalGap, + required double verticalGap, + required bool pinEnd, + bool wrapAbove = false, + bool alignBottom = false, + }) : _horizontalGap = horizontalGap, + _verticalGap = verticalGap, + _pinEnd = pinEnd, + _wrapAbove = wrapAbove, + _alignBottom = alignBottom; + + double _horizontalGap; + set horizontalGap(double value) { + if (value == _horizontalGap) return; + _horizontalGap = value; + markNeedsLayout(); + } + + double _verticalGap; + set verticalGap(double value) { + if (value == _verticalGap) return; + _verticalGap = value; + markNeedsLayout(); + } + + bool _pinEnd; + set pinEnd(bool value) { + if (value == _pinEnd) return; + _pinEnd = value; + markNeedsLayout(); + } + + bool _wrapAbove; + set wrapAbove(bool value) { + if (value == _wrapAbove) return; + _wrapAbove = value; + markNeedsLayout(); + } + + bool _alignBottom; + set alignBottom(bool value) { + if (value == _alignBottom) return; + _alignBottom = value; + markNeedsLayout(); + } + + /// Перенесён ли второй ребёнок по последней раскладке. + bool get isWrapped => _wrapped; + bool _wrapped = false; + + @override + void setupParentData(RenderBox child) { + if (child.parentData is! _WrapRowParentData) { + child.parentData = _WrapRowParentData(); + } + } + + List get _children => getChildrenAsList(); + + bool _wraps(double first, double second, double width) => + first + _horizontalGap + second > width; + + @override + double computeMinIntrinsicWidth(double height) => _children.fold( + 0, + (double widest, RenderBox child) => + math.max(widest, child.getMinIntrinsicWidth(height)), + ); + + @override + double computeMaxIntrinsicWidth(double height) { + final List children = _children; + final double sum = children.fold( + 0, + (double total, RenderBox child) => + total + child.getMaxIntrinsicWidth(height), + ); + return children.length < 2 ? sum : sum + _horizontalGap; + } + + @override + double computeMinIntrinsicHeight(double width) => _heightFor( + width, + (RenderBox child, double w) => child.getMinIntrinsicHeight(w), + ); + + @override + double computeMaxIntrinsicHeight(double width) => _heightFor( + width, + (RenderBox child, double w) => child.getMaxIntrinsicHeight(w), + ); + + double _heightFor(double width, double Function(RenderBox, double) heightOf) { + final List children = _children; + if (children.isEmpty) return 0; + final RenderBox first = children.first; + if (children.length == 1) return heightOf(first, width); + final RenderBox second = children[1]; + final double firstWidth = math.min( + first.getMaxIntrinsicWidth(double.infinity), + width, + ); + final double secondWidth = math.min( + second.getMaxIntrinsicWidth(double.infinity), + width, + ); + if (_wraps(firstWidth, secondWidth, width)) { + return heightOf(first, width) + _verticalGap + heightOf(second, width); + } + return math.max(heightOf(first, firstWidth), heightOf(second, secondWidth)); + } + + @override + Size computeDryLayout(covariant BoxConstraints constraints) { + final BoxConstraints childConstraints = BoxConstraints( + maxWidth: constraints.maxWidth, + ); + final List sizes = _children + .map((RenderBox child) => child.getDryLayout(childConstraints)) + .toList(); + return _place(constraints, sizes).size; + } + + @override + void performLayout() { + final BoxConstraints childConstraints = BoxConstraints( + maxWidth: constraints.maxWidth, + ); + final List children = _children; + for (final RenderBox child in children) { + child.layout(childConstraints, parentUsesSize: true); + } + final _Placement placement = _place( + constraints, + children.map((RenderBox child) => child.size).toList(), + ); + _wrapped = placement.wrapped; + for (int i = 0; i < children.length; i++) { + (children[i].parentData! as _WrapRowParentData).offset = + placement.offsets[i]; + } + size = placement.size; + } + + _Placement _place(BoxConstraints constraints, List sizes) { + if (sizes.isEmpty) { + return _Placement(constraints.smallest, const [], false); + } + final Size first = sizes.first; + final bool pin = _pinEnd && constraints.hasBoundedWidth; + if (sizes.length == 1) { + final double width = pin ? constraints.maxWidth : first.width; + return _Placement( + constraints.constrain(Size(width, first.height)), + const [Offset.zero], + false, + ); + } + final Size second = sizes[1]; + final bool wrapped = _wraps( + first.width, + second.width, + constraints.maxWidth, + ); + final double contentWidth = wrapped + ? math.max(first.width, second.width) + : first.width + _horizontalGap + second.width; + final double height = wrapped + ? first.height + _verticalGap + second.height + : math.max(first.height, second.height); + final Size size = constraints.constrain( + Size(pin ? constraints.maxWidth : contentWidth, height), + ); + if (wrapped) { + final double x = _pinEnd ? size.width - second.width : 0; + return _Placement(size, [ + Offset(0, _wrapAbove ? second.height + _verticalGap : 0), + Offset(x, _wrapAbove ? 0 : first.height + _verticalGap), + ], true); + } + final double secondX = _pinEnd + ? size.width - second.width + : first.width + _horizontalGap; + return _Placement(size, [ + Offset(0, _inLine(height, first.height)), + Offset(secondX, _inLine(height, second.height)), + ], false); + } + + double _inLine(double lineHeight, double height) => + _alignBottom ? lineHeight - height : (lineHeight - height) / 2; + + @override + double? computeDistanceToActualBaseline(TextBaseline baseline) => + defaultComputeDistanceToFirstActualBaseline(baseline); + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) => + defaultHitTestChildren(result, position: position); + + @override + void paint(PaintingContext context, Offset offset) => + defaultPaint(context, offset); +} + +class _Placement { + const _Placement(this.size, this.offsets, this.wrapped); + + final Size size; + final List offsets; + final bool wrapped; +} diff --git a/lib/src/ui/personalization_icons.dart b/lib/src/ui/personalization_icons.dart index a197cdf..7859ac3 100644 --- a/lib/src/ui/personalization_icons.dart +++ b/lib/src/ui/personalization_icons.dart @@ -35,6 +35,10 @@ abstract final class PersonalizationIcons { static const String magnifier = 'packages/rees46_sdk/assets/icons/magnifier.svg'; static const String rosette = 'packages/rees46_sdk/assets/icons/rosette.svg'; + + /// «Поделиться» в шапке просмотра сторис — значок из веба (viewBox 24), вписан в 32 + /// так же, как глиф крестика: 18 по ширине. + static const String share = 'packages/rees46_sdk/assets/icons/share.svg'; static const String spacingMd = 'packages/rees46_sdk/assets/icons/spacing-md.svg'; @@ -63,6 +67,7 @@ abstract final class PersonalizationIcons { list, magnifier, rosette, + share, spacingMd, speaker, speakerOff, diff --git a/lib/src/ui/personalization_theme.dart b/lib/src/ui/personalization_theme.dart index bc58f6d..99ffbf5 100644 --- a/lib/src/ui/personalization_theme.dart +++ b/lib/src/ui/personalization_theme.dart @@ -291,6 +291,24 @@ class PersonalizationBrightness extends InheritedWidget { final Brightness brightness; + /// Яркость кита на непрозрачном фоне [background], который задаёт содержимое: та, + /// у темы которой основной текст (Text/Primary) контрастнее с фоном по WCAG. + /// Поровну — светлая. + static Brightness on(Color background) { + final luminance = background.computeLuminance(); + double contrast(PersonalizationTheme theme) { + final text = theme.colors.textPrimary.computeLuminance(); + return text > luminance + ? (text + 0.05) / (luminance + 0.05) + : (luminance + 0.05) / (text + 0.05); + } + + return contrast(PersonalizationTheme._dark) > + contrast(PersonalizationTheme._light) + ? Brightness.dark + : Brightness.light; + } + static Brightness? _of(BuildContext context) => context .dependOnInheritedWidgetOfExactType() ?.brightness; diff --git a/lib/src/ui/personalization_ui.dart b/lib/src/ui/personalization_ui.dart index ba1442c..d533594 100644 --- a/lib/src/ui/personalization_ui.dart +++ b/lib/src/ui/personalization_ui.dart @@ -1,18 +1,6 @@ /// UI-кит дизайн-системы: токены, тема и все собранные на них компоненты. /// -/// Намеренно не экспортируется из `package:rees46_sdk/rees46_sdk.dart`. Кит ещё -/// собирается и ничем в SDK не используется, поэтому до релиза, который его -/// выпустит, он остаётся вне публичной поверхности. Пока единственный вход — -/// прямой импорт этого файла; анализатор помечает его как implementation -/// import, и это ожидаемо: -/// -/// ```dart -/// // ignore: implementation_imports -/// import 'package:rees46_sdk/src/ui/personalization_ui.dart'; -/// ``` -/// -/// Перед релизом эти экспорты переезжают в барель пакета, и кит становится -/// обычным публичным API. +/// Входит в `package:rees46_sdk/rees46_sdk.dart`. library; export 'personalization_typography.dart'; @@ -46,7 +34,7 @@ export 'components/personalization_favorites_badge.dart'; export 'components/personalization_product_card.dart'; export 'components/personalization_product.dart'; export 'components/personalization_products_list.dart'; -export 'components/personalization_recommender_block.dart'; +export 'components/personalization_products_block.dart'; export 'components/personalization_suggestion_row.dart'; export 'components/personalization_instant_search.dart'; export 'components/personalization_filters.dart'; @@ -69,13 +57,32 @@ export 'components/personalization_story_timer.dart'; export 'components/personalization_story_text_block.dart'; export 'components/personalization_story_used_products.dart'; -// Виджеты с данными SDK: сами резолвят инстанс по shopId, ходят в поиск и держат состояние. +// Виджеты с данными SDK: сами резолвят инстанс по shopId, ходят в API и держат состояние. export 'widgets/search_support.dart' show PersonalizationSearchCategory; export 'widgets/personalization_instant_search_field.dart'; export 'widgets/personalization_search_results_screen.dart'; -// Модели блока сторис живут рядом с остальными ответами SDK, но до релиза кита -// видны только отсюда: пакетный барель их не экспортирует. -export '../stories/stories_response.dart' hide parseStoryOpacity; +export 'widgets/personalization_category_screen.dart'; +export 'widgets/personalization_recommender_block.dart'; +// Модели блока сторис живут рядом с остальными ответами SDK. Списком, а не целиком: модели +// опросов и «Поделиться» в той же библиотеке — за шлюзом v3. +export '../stories/stories_response.dart' + show + StoriesBlock, + Story, + StorySlideType, + StorySlide, + StoryElement, + StoryButtonElement, + StoryProductElement, + StoryProductsElement, + StoryTextBlockElement, + StoryProduct; export 'widgets/stories_support.dart' show PersonalizationStoryImageProvider; -export 'widgets/personalization_story_viewer.dart'; -export 'widgets/personalization_stories.dart'; +// Списком: режим v3 сторис живёт в тех же библиотеках, но за шлюзом v3. +export 'widgets/personalization_story_viewer.dart' + show PersonalizationStoryViewer; +export 'widgets/personalization_stories.dart' + show PersonalizationStories, PersonalizationStoriesController; + +// Попапы нового конструктора, сторис на API v3 («Поделиться», ссылки, опросы) — за +// отдельным шлюзом v3 (`src/v3/personalization_v3.dart`), не здесь. diff --git a/lib/src/ui/popups_v3/css_color.dart b/lib/src/ui/popups_v3/css_color.dart new file mode 100644 index 0000000..01a9c0d --- /dev/null +++ b/lib/src/ui/popups_v3/css_color.dart @@ -0,0 +1,247 @@ +import 'dart:ui' show Color; + +/// Цвет CSS из документа попапа v3: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa` (порядок +/// CSS — альфа в конце), `rgb()`/`rgba()` через запятые или пробелы (альфа после `/`, +/// числом или процентом), 148 именованных цветов и `transparent`. Остальное — `null`: +/// элемент возьмёт свой цвет по умолчанию. +Color? parseCssColor(Object? value) { + if (value is! String) return null; + final text = value.trim().toLowerCase(); + if (text.isEmpty) return null; + if (text.startsWith('#')) return _hex(text.substring(1)); + if (text == 'transparent') return const Color(0x00000000); + if (text.startsWith('rgb')) return _rgb(text); + final named = _named[text]; + return named == null ? null : Color(0xff000000 | named); +} + +/// Цвет строкой `#rrggbbaa` в нижнем регистре — для тестов и логов. +String cssColorHex(Color color) { + String two(int value) => value.toRadixString(16).padLeft(2, '0'); + final argb = color.toARGB32(); + return '#${two((argb >> 16) & 0xff)}${two((argb >> 8) & 0xff)}' + '${two(argb & 0xff)}${two((argb >> 24) & 0xff)}'; +} + +final RegExp _hexDigits = RegExp(r'^[0-9a-f]+$'); + +Color? _hex(String digits) { + if (!_hexDigits.hasMatch(digits)) return null; + int channel(String part) => + int.parse(part.length == 1 ? '$part$part' : part, radix: 16); + switch (digits.length) { + case 3: + case 4: + final alpha = digits.length == 4 ? channel(digits[3]) : 255; + return Color.fromARGB( + alpha, + channel(digits[0]), + channel(digits[1]), + channel(digits[2]), + ); + case 6: + case 8: + final alpha = digits.length == 8 ? channel(digits.substring(6, 8)) : 255; + return Color.fromARGB( + alpha, + channel(digits.substring(0, 2)), + channel(digits.substring(2, 4)), + channel(digits.substring(4, 6)), + ); + } + return null; +} + +final RegExp _rgbFunction = RegExp(r'^rgba?\((.*)\)$'); + +Color? _rgb(String text) { + final match = _rgbFunction.firstMatch(text); + if (match == null) return null; + var body = match.group(1)!.trim(); + String? alphaPart; + final slash = body.indexOf('/'); + if (slash >= 0) { + alphaPart = body.substring(slash + 1).trim(); + body = body.substring(0, slash).trim(); + } + final parts = body + .split(RegExp(r'[\s,]+')) + .where((part) => part.isNotEmpty) + .toList(); + if (alphaPart == null && parts.length == 4) alphaPart = parts.removeLast(); + if (parts.length != 3) return null; + final channels = []; + for (final part in parts) { + final value = _number(part, 255); + if (value == null) return null; + channels.add(value.clamp(0, 255).round()); + } + var alpha = 255; + if (alphaPart != null) { + final value = _number(alphaPart, 1); + if (value == null) return null; + alpha = (value.clamp(0, 1) * 255).round(); + } + return Color.fromARGB(alpha, channels[0], channels[1], channels[2]); +} + +/// Число или процент от [scale]. +double? _number(String part, double scale) { + if (part.endsWith('%')) { + final value = double.tryParse(part.substring(0, part.length - 1)); + return value == null ? null : value / 100 * scale; + } + return double.tryParse(part); +} + +/// Именованные цвета CSS (RGB без альфы). +const Map _named = { + 'aliceblue': 0xf0f8ff, + 'antiquewhite': 0xfaebd7, + 'aqua': 0x00ffff, + 'aquamarine': 0x7fffd4, + 'azure': 0xf0ffff, + 'beige': 0xf5f5dc, + 'bisque': 0xffe4c4, + 'black': 0x000000, + 'blanchedalmond': 0xffebcd, + 'blue': 0x0000ff, + 'blueviolet': 0x8a2be2, + 'brown': 0xa52a2a, + 'burlywood': 0xdeb887, + 'cadetblue': 0x5f9ea0, + 'chartreuse': 0x7fff00, + 'chocolate': 0xd2691e, + 'coral': 0xff7f50, + 'cornflowerblue': 0x6495ed, + 'cornsilk': 0xfff8dc, + 'crimson': 0xdc143c, + 'cyan': 0x00ffff, + 'darkblue': 0x00008b, + 'darkcyan': 0x008b8b, + 'darkgoldenrod': 0xb8860b, + 'darkgray': 0xa9a9a9, + 'darkgreen': 0x006400, + 'darkgrey': 0xa9a9a9, + 'darkkhaki': 0xbdb76b, + 'darkmagenta': 0x8b008b, + 'darkolivegreen': 0x556b2f, + 'darkorange': 0xff8c00, + 'darkorchid': 0x9932cc, + 'darkred': 0x8b0000, + 'darksalmon': 0xe9967a, + 'darkseagreen': 0x8fbc8f, + 'darkslateblue': 0x483d8b, + 'darkslategray': 0x2f4f4f, + 'darkslategrey': 0x2f4f4f, + 'darkturquoise': 0x00ced1, + 'darkviolet': 0x9400d3, + 'deeppink': 0xff1493, + 'deepskyblue': 0x00bfff, + 'dimgray': 0x696969, + 'dimgrey': 0x696969, + 'dodgerblue': 0x1e90ff, + 'firebrick': 0xb22222, + 'floralwhite': 0xfffaf0, + 'forestgreen': 0x228b22, + 'fuchsia': 0xff00ff, + 'gainsboro': 0xdcdcdc, + 'ghostwhite': 0xf8f8ff, + 'gold': 0xffd700, + 'goldenrod': 0xdaa520, + 'gray': 0x808080, + 'green': 0x008000, + 'greenyellow': 0xadff2f, + 'grey': 0x808080, + 'honeydew': 0xf0fff0, + 'hotpink': 0xff69b4, + 'indianred': 0xcd5c5c, + 'indigo': 0x4b0082, + 'ivory': 0xfffff0, + 'khaki': 0xf0e68c, + 'lavender': 0xe6e6fa, + 'lavenderblush': 0xfff0f5, + 'lawngreen': 0x7cfc00, + 'lemonchiffon': 0xfffacd, + 'lightblue': 0xadd8e6, + 'lightcoral': 0xf08080, + 'lightcyan': 0xe0ffff, + 'lightgoldenrodyellow': 0xfafad2, + 'lightgray': 0xd3d3d3, + 'lightgreen': 0x90ee90, + 'lightgrey': 0xd3d3d3, + 'lightpink': 0xffb6c1, + 'lightsalmon': 0xffa07a, + 'lightseagreen': 0x20b2aa, + 'lightskyblue': 0x87cefa, + 'lightslategray': 0x778899, + 'lightslategrey': 0x778899, + 'lightsteelblue': 0xb0c4de, + 'lightyellow': 0xffffe0, + 'lime': 0x00ff00, + 'limegreen': 0x32cd32, + 'linen': 0xfaf0e6, + 'magenta': 0xff00ff, + 'maroon': 0x800000, + 'mediumaquamarine': 0x66cdaa, + 'mediumblue': 0x0000cd, + 'mediumorchid': 0xba55d3, + 'mediumpurple': 0x9370db, + 'mediumseagreen': 0x3cb371, + 'mediumslateblue': 0x7b68ee, + 'mediumspringgreen': 0x00fa9a, + 'mediumturquoise': 0x48d1cc, + 'mediumvioletred': 0xc71585, + 'midnightblue': 0x191970, + 'mintcream': 0xf5fffa, + 'mistyrose': 0xffe4e1, + 'moccasin': 0xffe4b5, + 'navajowhite': 0xffdead, + 'navy': 0x000080, + 'oldlace': 0xfdf5e6, + 'olive': 0x808000, + 'olivedrab': 0x6b8e23, + 'orange': 0xffa500, + 'orangered': 0xff4500, + 'orchid': 0xda70d6, + 'palegoldenrod': 0xeee8aa, + 'palegreen': 0x98fb98, + 'paleturquoise': 0xafeeee, + 'palevioletred': 0xdb7093, + 'papayawhip': 0xffefd5, + 'peachpuff': 0xffdab9, + 'peru': 0xcd853f, + 'pink': 0xffc0cb, + 'plum': 0xdda0dd, + 'powderblue': 0xb0e0e6, + 'purple': 0x800080, + 'rebeccapurple': 0x663399, + 'red': 0xff0000, + 'rosybrown': 0xbc8f8f, + 'royalblue': 0x4169e1, + 'saddlebrown': 0x8b4513, + 'salmon': 0xfa8072, + 'sandybrown': 0xf4a460, + 'seagreen': 0x2e8b57, + 'seashell': 0xfff5ee, + 'sienna': 0xa0522d, + 'silver': 0xc0c0c0, + 'skyblue': 0x87ceeb, + 'slateblue': 0x6a5acd, + 'slategray': 0x708090, + 'slategrey': 0x708090, + 'snow': 0xfffafa, + 'springgreen': 0x00ff7f, + 'steelblue': 0x4682b4, + 'tan': 0xd2b48c, + 'teal': 0x008080, + 'thistle': 0xd8bfd8, + 'tomato': 0xff6347, + 'turquoise': 0x40e0d0, + 'violet': 0xee82ee, + 'wheat': 0xf5deb3, + 'white': 0xffffff, + 'whitesmoke': 0xf5f5f5, + 'yellow': 0xffff00, + 'yellowgreen': 0x9acd32, +}; diff --git a/lib/src/ui/popups_v3/personalization_screen_observer.dart b/lib/src/ui/popups_v3/personalization_screen_observer.dart new file mode 100644 index 0000000..42434ec --- /dev/null +++ b/lib/src/ui/popups_v3/personalization_screen_observer.dart @@ -0,0 +1,61 @@ +import 'package:flutter/widgets.dart'; + +import '../../multi_instance/rees46.dart'; +import '../../personalization_sdk.dart'; +import '../../popups_v3/popups_v3.dart'; + +/// Сообщает попапам v3 об открытых экранах навигатора: страница пришла (`push`), +/// вернулись на неё (`pop` верхней), заменили — `sdk.popups.screenOpened(код)`. +/// +/// Код экрана — то, что маркетолог пишет в `target_screens`: по умолчанию имя маршрута +/// (`RouteSettings.name`), иначе — что вернёт [screenName] (`null` — не сообщать). +/// Диалоги и всплывающие маршруты экраном не считаются. +/// +/// ```dart +/// MaterialApp(navigatorObservers: [PersonalizationScreenObserver(shopId: 'SHOP_ID')]); +/// ``` +class PersonalizationScreenObserver extends NavigatorObserver { + PersonalizationScreenObserver({this.sdk, this.shopId, this.screenName}); + + /// Инстанс SDK; без него — [shopId] или единственный (`REES46.getInstance`). + final PersonalizationSdk? sdk; + final String? shopId; + + /// Код экрана маршрута. + final String? Function(Route route)? screenName; + + /// Последний сообщённый экран. + String? get current => _current; + String? _current; + + @override + void didPush(Route route, Route? previousRoute) => + _report(route); + + @override + void didPop(Route route, Route? previousRoute) { + if (route is PageRoute && previousRoute != null) _report(previousRoute); + } + + @override + void didReplace({Route? newRoute, Route? oldRoute}) { + if (newRoute != null) _report(newRoute); + } + + void _report(Route route) { + if (route is! PageRoute) return; + final name = screenName?.call(route) ?? route.settings.name; + if (name == null || name.trim().isEmpty) return; + _current = name; + reportScreen(name); + } + + /// Сообщить экран [name] — например, при переключении вкладки на этот навигатор. + void reportScreen(String name) { + try { + (sdk ?? REES46.getInstance(shopId)).popups.screenOpened(name); + } catch (error) { + debugPrint('PersonalizationScreenObserver: screen $name — $error'); + } + } +} diff --git a/lib/src/ui/popups_v3/popup_markup.dart b/lib/src/ui/popups_v3/popup_markup.dart new file mode 100644 index 0000000..fa14cb0 --- /dev/null +++ b/lib/src/ui/popups_v3/popup_markup.dart @@ -0,0 +1,101 @@ +import 'package:flutter/painting.dart'; + +/// Кусок текста с облегчённой разметкой конструктора попапов. +class PopupMarkupSpan { + const PopupMarkupSpan( + this.text, { + this.bold = false, + this.italic = false, + this.underline = false, + this.strike = false, + this.overline = false, + }); + + final String text; + final bool bold; + final bool italic; + final bool underline; + final bool strike; + final bool overline; + + PopupMarkupSpan withText(String text) => PopupMarkupSpan( + text, + bold: bold, + italic: italic, + underline: underline, + strike: strike, + overline: overline, + ); + + @override + String toString() => + 'PopupMarkupSpan(${[text, if (bold) 'bold', if (italic) 'italic', if (underline) 'underline', if (strike) 'strike', if (overline) 'overline'].join(', ')})'; +} + +/// Регэксп разметки компилятора (`Context::RICH_TEXT_RE`): `***жирный курсив***`, +/// `**жирный**`, `~~зачёркнутый~~`, `__подчёркнутый__`, `^^надчёркнутый^^`, `*курсив*`. +final RegExp _richText = RegExp( + r'\*\*\*([^*]+)\*\*\*|\*\*([^*]+)\*\*|~~([^~]+)~~|__([^_]+)__|\^\^([^^]+)\^\^|\*([^*]+)\*', +); + +/// Разбор разметки [text] слева направо одним регэкспом, без вложенности — как +/// `gsub(RICH_TEXT_RE)` компилятора. HTML остаётся текстом, `\n` — перенос строки. +List parsePopupMarkup(String text) { + final spans = []; + var position = 0; + for (final match in _richText.allMatches(text)) { + if (match.start > position) { + spans.add(PopupMarkupSpan(text.substring(position, match.start))); + } + final group = [ + 1, + 2, + 3, + 4, + 5, + 6, + ].firstWhere((index) => match.group(index) != null); + final content = match.group(group)!; + spans.add(switch (group) { + 1 => PopupMarkupSpan(content, bold: true, italic: true), + 2 => PopupMarkupSpan(content, bold: true), + 3 => PopupMarkupSpan(content, strike: true), + 4 => PopupMarkupSpan(content, underline: true), + 5 => PopupMarkupSpan(content, overline: true), + _ => PopupMarkupSpan(content, italic: true), + }); + position = match.end; + } + if (position < text.length) { + spans.add(PopupMarkupSpan(text.substring(position))); + } + return spans; +} + +/// [spans] текстом Flutter со стилем [base]: жирный — 700, курсив, линии. +TextSpan popupMarkupTextSpan(List spans, TextStyle base) { + return TextSpan( + style: base, + children: [ + for (final span in spans) + TextSpan( + text: span.text, + style: TextStyle( + fontWeight: span.bold ? FontWeight.w700 : null, + fontStyle: span.italic ? FontStyle.italic : null, + decoration: _decoration(span), + decorationColor: base.color, + ), + ), + ], + ); +} + +TextDecoration? _decoration(PopupMarkupSpan span) { + final lines = [ + if (span.underline) TextDecoration.underline, + if (span.strike) TextDecoration.lineThrough, + if (span.overline) TextDecoration.overline, + ]; + return lines.isEmpty ? null : TextDecoration.combine(lines); +} diff --git a/lib/src/ui/popups_v3/popup_v3_design.dart b/lib/src/ui/popups_v3/popup_v3_design.dart new file mode 100644 index 0000000..cf843ef --- /dev/null +++ b/lib/src/ui/popups_v3/popup_v3_design.dart @@ -0,0 +1,1159 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; + +import '../../popups_v3/popup_v3.dart'; +import '../../popups_v3/popup_v3_values.dart'; +import 'css_color.dart'; +import 'popup_markup.dart'; + +/// Выравнивание по горизонтали. +enum PopupV3Align { left, center, right } + +/// Выравнивание по вертикали. +enum PopupV3VerticalAlign { top, center, bottom } + +PopupV3Align? _align(Object? value) => switch (value) { + 'left' => PopupV3Align.left, + 'center' => PopupV3Align.center, + 'right' => PopupV3Align.right, + _ => null, +}; + +PopupV3VerticalAlign? _verticalAlign(Object? value) => switch (value) { + 'top' => PopupV3VerticalAlign.top, + 'center' => PopupV3VerticalAlign.center, + 'bottom' => PopupV3VerticalAlign.bottom, + _ => null, +}; + +/// Переменные дизайна: статические из `design.variables` и витринные, которые SDK +/// подставляет при показе (`promo_code`). Неизвестный ключ остаётся токеном. +class PopupV3Variables { + PopupV3Variables({ + Map statics = const {}, + Map runtime = const {}, + this.platform, + }) : statics = { + for (final entry in statics.entries) + if (!runtimeKeys.contains(entry.key)) entry.key: entry.value, + }, + runtime = Map.unmodifiable(runtime); + + /// Из `design.variables`: объект или старый массив `{key, value}`. + factory PopupV3Variables.fromDesign( + Object? raw, { + Map runtime = const {}, + TargetPlatform? platform, + }) { + final statics = {}; + if (raw is Map) { + raw.forEach((key, value) => statics['$key'] = cssString(value)); + } else if (raw is List) { + for (final item in raw) { + if (item is! Map) continue; + final key = cssPresent(item['key']); + if (key != null) statics[key] = cssString(item['value']); + } + } + return PopupV3Variables( + statics: statics, + runtime: runtime, + platform: platform, + ); + } + + /// Витринные переменные: их значения не из дизайна, а от SDK при показе. + static const List runtimeKeys = [ + 'promo_code', + 'coupon_code', + 'campaign_end', + 'remaining', + 'progress', + 'cart_total', + 'wheel_prize', + ]; + + static final RegExp token = RegExp(r'\{\{\s*([a-zA-Z0-9_]+)\s*\}\}'); + + final Map statics; + final Map runtime; + + /// Платформа ссылок: `{{key}}` ссылки берёт сначала `key_ios` / `key_android`. + final TargetPlatform? platform; + + /// Статические переменные — до разбора разметки. + String applyStatic(String text) => text.replaceAllMapped( + token, + (match) => statics[match.group(1)!] ?? match.group(0)!, + ); + + /// Витринные переменные. + String applyRuntime(String text) => text.replaceAllMapped( + token, + (match) => runtime[match.group(1)!] ?? match.group(0)!, + ); + + /// Все переменные — в плейсхолдерах, адресах картинок и копируемом тексте. + String apply(String text) => applyRuntime(applyStatic(text)); + + /// Ссылка: для `{{key}}` сначала `key_ios` / `key_android` этой платформы, потом + /// `key`; витринные — как везде. + String applyLink(String text) { + final suffix = switch (platform ?? defaultTargetPlatform) { + TargetPlatform.iOS => 'ios', + TargetPlatform.android => 'android', + _ => null, + }; + final linked = text.replaceAllMapped(token, (match) { + final key = match.group(1)!; + return (suffix == null ? null : statics['${key}_$suffix']) ?? + statics[key] ?? + match.group(0)!; + }); + return applyRuntime(linked); + } + + /// Текст с разметкой: статические переменные, разбор, витринные — в готовые куски + /// (их значения разметкой не становятся). + List rich(String? text) { + if (text == null || text.isEmpty) return const []; + return [ + for (final span in parsePopupMarkup(applyStatic(text))) + span.withText(applyRuntime(span.text)), + ]; + } +} + +/// Тень элемента. +typedef PopupV3Shadow = ({double y, double blur, Color color}); + +/// «Коробка» элемента — общие стили обёртки, как `Context#box_declarations`. +class PopupV3Box { + const PopupV3Box({ + required this.background, + required this.textColor, + required this.borderWidth, + required this.borderColor, + required this.radius, + required this.paddingX, + required this.paddingY, + required this.fontFamily, + required this.fontSize, + required this.fontWeight, + required this.letterSpacing, + required this.lineHeight, + required this.opacity, + required this.shadow, + }); + + final Color background; + final Color textColor; + final double borderWidth; + final Color borderColor; + final double radius; + final double paddingX; + final double paddingY; + + /// `fontFamily` дизайна как есть; `null` — шрифт приложения. + final String? fontFamily; + final double fontSize; + final double fontWeight; + final double letterSpacing; + + /// Множитель высоты строки. + final double lineHeight; + final double opacity; + + /// `null` — без тени (нулевые смещение и размытие). + final PopupV3Shadow? shadow; +} + +/// Значения по умолчанию нового элемента в редакторе (`DEFAULTS` компилятора): их берём, +/// когда в документе ключа нет. Ключи поведения (`emailLayout`, `emailConsentFields`, +/// `formFields`, `formConsentFields`) сюда не входят: без них компилятор рисует по-своему, +/// и мы так же. +const Map> popupV3ElementDefaults = + >{ + 'text': { + 'fontSize': 16, + 'bgColor': 'transparent', + 'messageAlign': 'left', + }, + 'box': { + 'bgColor': '#f8fafc', + 'borderRadius': 12, + 'paddingX': 16, + 'paddingY': 16, + }, + 'button': { + 'buttonAction': 'link', + 'buttonAlign': 'center', + 'buttonBgColor': '#2563eb', + 'buttonTextColor': '#ffffff', + 'buttonFontSize': 14, + 'buttonPaddingX': 20, + 'buttonPaddingY': 10, + 'buttonRadius': 10, + }, + 'close': { + 'closeIconMode': 'text', + 'buttonAlign': 'right', + 'buttonBgColor': 'transparent', + 'buttonTextColor': '#71717a', + 'buttonFontSize': 22, + 'buttonPaddingX': 8, + 'buttonPaddingY': 2, + 'buttonRadius': 999, + }, + 'image': { + 'bgColor': 'transparent', + 'imageHeightMode': 'auto', + 'imageObjectFit': 'cover', + 'imageRadius': 8, + }, + 'emailCollector': { + 'borderRadius': 12, + 'buttonBgColor': '#2563eb', + 'buttonTextColor': '#ffffff', + }, + 'form': { + 'borderRadius': 12, + 'buttonBgColor': '#2563eb', + 'buttonTextColor': '#ffffff', + }, + 'promoCode': { + 'promoSource': 'personal', + 'promoShowCopy': true, + 'promoCodeBg': '#fef3c7', + 'promoCodeColor': '#92400e', + 'promoCodeRadius': 10, + 'promoCodeFontSize': 20, + 'messageAlign': 'center', + 'bgColor': 'transparent', + }, + 'survey': { + 'surveyType': 'nps', + 'surveyScaleBg': '#f3f4f6', + 'surveyScaleColor': '#111827', + 'surveyScaleActiveBg': '#2563eb', + 'surveyScaleActiveColor': '#ffffff', + 'buttonBgColor': '#2563eb', + 'buttonTextColor': '#ffffff', + }, + 'recommendation': {'bgColor': 'transparent'}, + }; + +/// Типы, которые тянутся на всю ширину ячейки (`STRETCH`). +const Set popupV3StretchTypes = { + 'image', + 'emailCollector', + 'form', + 'promoCode', + 'survey', + 'recommendation', +}; + +/// Типы со ссылкой на всём элементе (`LINKABLE`). +const Set popupV3LinkableTypes = {'text', 'box', 'image'}; + +/// Флаги подписки на email. +const List popupV3ConsentFields = [ + 'email_bulk', + 'email_chain', + 'email_transactional', +]; + +/// Элемент документа: тип и стиль. Значение ключа — из документа, без него — из +/// [popupV3ElementDefaults] типа; `null` и пустая строка — «нет значения». +class PopupV3Element { + PopupV3Element({ + required this.id, + required this.type, + required Map style, + }) : style = Map.unmodifiable(style), + defaults = popupV3ElementDefaults[type] ?? const {}; + + final String id; + final String type; + final Map style; + final Map defaults; + + bool get stretch => popupV3StretchTypes.contains(type); + + /// Значение [key]: документ, затем `DEFAULTS` типа. + Object? value(String key) { + final own = style[key]; + if (own != null && !(own is String && own.isEmpty)) return own; + return defaults[key]; + } + + /// Строка с содержимым или `null`. + String? text(String key) => cssPresent(value(key)); + + /// Строка как есть (`to_s`). + String string(String key) => cssString(value(key)); + + double number(String key, double fallback) => cssNum(value(key), fallback); + + /// Цвет [key] или [fallback] (hex). + Color color(String key, String fallback) => + parseCssColor(value(key)) ?? parseCssColor(fallback)!; + + /// Цвет [key] или `null`. + Color? colorOrNull(String key) => parseCssColor(value(key)); + + /// Коробка обёртки по правилам компилятора и переопределениям типа. + PopupV3Box get box { + final shadowRaw = value('shadowColor'); + final shadowText = shadowRaw is String ? shadowRaw.trim() : ''; + final shadowParsed = parseCssColor(shadowRaw); + // Как `Context#shadow_color`: к шестизначному hex (и к запасному #000000) + // дописывается альфа 55, остальные форматы — как есть. + final shadowColor = + shadowParsed == null || + RegExp(r'^#[0-9a-fA-F]{6}$').hasMatch(shadowText) + ? (shadowParsed ?? const Color(0xff000000)).withAlpha(0x55) + : shadowParsed; + final shadowY = number('shadowY', 0); + final shadowBlur = number('shadowBlur', 0); + var background = color('bgColor', '#ffffff'); + var textColor = color('textColor', '#111827'); + var borderWidth = number('borderWidth', 0); + var borderColor = color('borderColor', '#d4d4d8'); + var radius = number('borderRadius', 0); + var paddingX = number('paddingX', 0); + var paddingY = number('paddingY', 0); + PopupV3Shadow? shadow = shadowY == 0 && shadowBlur == 0 + ? null + : (y: shadowY, blur: shadowBlur, color: shadowColor); + switch (type) { + case 'button': + case 'close': + background = const Color(0x00000000); + borderWidth = 0; + case 'emailCollector': + case 'form': + textColor = color('textColor', '#0f172a'); + borderColor = color('borderColor', '#e2e8f0'); + radius = number('borderRadius', 12); + paddingX = number('paddingX', 12); + paddingY = number('paddingY', 12); + case 'recommendation': + background = const Color(0x00000000); + borderWidth = 0; + paddingX = 0; + paddingY = 0; + shadow = null; + } + return PopupV3Box( + background: background, + textColor: textColor, + borderWidth: math.max(0, borderWidth), + borderColor: borderColor, + radius: math.max(0, radius), + paddingX: math.max(0, paddingX), + paddingY: math.max(0, paddingY), + fontFamily: text('fontFamily'), + fontSize: number('fontSize', 12), + fontWeight: number('fontWeight', 500), + letterSpacing: number('letterSpacing', 0), + lineHeight: number('lineHeight', 1.35), + opacity: number('opacity', 1).clamp(0, 1).toDouble(), + shadow: shadow, + ); + } + + /// Выравнивание обёртки в ячейке (у растянутых типов — не нужно): `cellAlign`, у + /// кнопок — затем `buttonAlign`, иначе выравнивание ячейки [cellAlign]. + PopupV3Align alignIn(PopupV3Align cellAlign) { + final own = _align(value('cellAlign')); + if (own != null) return own; + if (type == 'button' || type == 'close') { + return _align(value('buttonAlign')) ?? cellAlign; + } + return cellAlign; + } + + /// Своя вертикаль в ячейке (`cellVerticalAlign`). + PopupV3VerticalAlign? get verticalAlign => + _verticalAlign(style['cellVerticalAlign']); + + /// Выравнивание текста (`messageAlign`). + TextAlign get messageAlign => switch (value('messageAlign')) { + 'center' => TextAlign.center, + 'right' => TextAlign.right, + _ => TextAlign.left, + }; + + /// Кегль текста: `messageFontSize`, затем `fontSize`, затем 12. + double get messageFontSize => + cssNum(value('messageFontSize'), number('fontSize', 12)); + + /// Насыщенность текста: `messageFontWeight`, затем `fontWeight`, затем 500. + double get messageFontWeight => + cssNum(value('messageFontWeight'), number('fontWeight', 500)); + + /// Ссылка на всём элементе (только у `text`, `box`, `image`). + String? link(PopupV3Variables variables) { + if (!popupV3LinkableTypes.contains(type)) return null; + final href = text('linkHref'); + return href == null ? null : cssPresent(variables.applyLink(href))?.trim(); + } + + // --- button / close --- + + /// Действие кнопки: `link`, `close` или `copy`; неизвестное — `link`. У крестика — + /// всегда `close`. + String get buttonAction { + if (type == 'close') return 'close'; + final action = value('buttonAction'); + return action == 'close' || action == 'copy' ? action as String : 'link'; + } + + /// Адрес кнопки-ссылки: `linkHref`, у старых документов `buttonHref`. + String? buttonHref(PopupV3Variables variables) { + final href = text('linkHref') ?? text('buttonHref'); + return href == null ? null : cssPresent(variables.applyLink(href))?.trim(); + } + + /// Что копирует кнопка: `copyText`, без него — текст кнопки как есть. + String copyText(PopupV3Variables variables) => + variables.apply(text('copyText') ?? string('buttonText')); + + /// Вид крестика: `text`, `image` или `svg`. + String get closeMode { + final mode = value('closeIconMode'); + return mode == 'image' || mode == 'svg' ? mode as String : 'text'; + } + + /// Размер иконки крестика: `closeIconSize`, затем `buttonFontSize`, 8–128. + double get closeIconSize => cssNum( + value('closeIconSize'), + number('buttonFontSize', 22), + ).clamp(8, 128).toDouble(); + + /// Картинка крестика (режим `image`, только http/https). + String? closeImageUrl(PopupV3Variables variables) { + if (closeMode != 'image') return null; + return popupV3ImageUrl(text('imageUrl'), variables); + } + + /// SVG крестика без скриптов (режим `svg`); не SVG — `null`. + String? get closeSvg { + if (closeMode != 'svg') return null; + final svg = string('closeSvg').trim(); + final start = RegExp(r'^]', caseSensitive: false); + if (!start.hasMatch(svg)) return null; + final cleaned = svg + .replaceAll( + RegExp( + r']*>.*?', + caseSensitive: false, + dotAll: true, + ), + '', + ) + .replaceAll( + RegExp( + r'''\s+on\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)''', + caseSensitive: false, + ), + '', + ) + .replaceAll(RegExp('javascript:', caseSensitive: false), ''); + return start.hasMatch(cleaned) ? cleaned : null; + } + + // --- image --- + + /// Рисовать ли картинку (`showImage: false` — нет). + bool get showImage => style['showImage'] != false; + + /// Высота картинки. + PopupV3ImageHeight get imageHeight { + final mode = text('imageHeightMode') ?? 'auto'; + return switch (mode) { + 'auto' => const PopupV3ImageHeight.auto(), + '%' => PopupV3ImageHeight.percent( + number('imageHeight', 100).clamp(1, 100).toDouble(), + ), + 'vh' => PopupV3ImageHeight.vh( + number('imageHeight', 40).clamp(1, 100).toDouble(), + ), + _ => PopupV3ImageHeight.px(number('imageHeight', 120)), + }; + } + + /// Ширина к высоте из `imageAspectRatio` вида `16 / 9`; иначе `null`. + double? get imageAspectRatio { + final match = RegExp( + r'^(\d+(?:\.\d+)?)\s*/\s*(\d+(?:\.\d+)?)$', + ).firstMatch(string('imageAspectRatio').trim()); + if (match == null) return null; + final width = double.parse(match.group(1)!); + final height = double.parse(match.group(2)!); + return width > 0 && height > 0 ? width / height : null; + } + + BoxFit get imageFit => switch (value('imageObjectFit')) { + 'contain' => BoxFit.contain, + 'fill' => BoxFit.fill, + 'none' => BoxFit.none, + _ => BoxFit.cover, + }; + + // --- emailCollector --- + + /// Поле и кнопка в строку (`inline`) или столбиком (всё остальное). + bool get emailInline => style['emailLayout'] == 'inline'; + + /// Флаги подписки: `emailConsentFields`, старые `emailConsents[].field`, подписи + /// `email*Label`, иначе все три — как `EmailCollector#consent_fields`. + List get emailConsentFields { + List known(Iterable values) => [ + for (final value in values) + if (popupV3ConsentFields.contains(value)) value as String, + ]; + final own = style['emailConsentFields']; + if (own is List) { + final fields = known(own); + if (fields.isNotEmpty) return fields; + } + final consents = style['emailConsents']; + if (consents is List) { + final fields = known([ + for (final item in consents) + if (item is Map) item['field'], + ]); + if (fields.isNotEmpty) return fields; + } + final labelled = [ + if (cssPresent(style['emailConsentBulkLabel']) != null) 'email_bulk', + if (cssPresent(style['emailConsentChainLabel']) != null) 'email_chain', + if (cssPresent(style['emailConsentTransactionalLabel']) != null) + 'email_transactional', + ]; + return labelled.isNotEmpty ? labelled : popupV3ConsentFields; + } + + /// Подпись согласия: `emailConsentLabel`, первая из `emailConsents`, + /// `emailConsentBulkLabel`; нет — `null` (текст по умолчанию). + String? get emailConsentLabel { + final own = cssPresent(style['emailConsentLabel']); + if (own != null) return own.trim(); + final consents = style['emailConsents']; + if (consents is List && consents.isNotEmpty && consents.first is Map) { + final label = cssPresent((consents.first as Map)['label']); + if (label != null) return label; + } + return cssPresent(style['emailConsentBulkLabel']); + } + + /// Сегмент после подписки или формы; пусто — `null`. + String? segmentId(String key) => cssPresent(style[key])?.trim(); + + // --- form --- + + /// Поля формы как `Form#normalized_fields`: только известные виды, не больше 8, id + /// из `[A-Za-z0-9_-]` (пусто — `field-N`), `required` — только `true`, + /// `propertyKey` — `[a-z0-9_]`. + List get formFields { + final raw = style['formFields']; + if (raw is! List) return const []; + final fields = []; + for (final item in raw) { + if (item is! Map || !PopupV3FormField.kinds.contains(item['kind'])) { + continue; + } + if (fields.length == 8) break; + final index = fields.length; + final id = cssString( + item['id'], + ).replaceAll(RegExp(r'[^A-Za-z0-9_-]'), ''); + fields.add( + PopupV3FormField( + id: id.isEmpty ? 'field-$index' : id, + kind: item['kind'] as String, + label: cssString(item['label']), + placeholder: cssString(item['placeholder']), + required: item['required'] == true, + propertyKey: cssString( + item['propertyKey'], + ).toLowerCase().replaceAll(RegExp(r'[^a-z0-9_]'), ''), + ), + ); + } + return fields; + } + + /// Флаги формы при отмеченном согласии; пусто — флагов нет. + List get formConsentFields { + final own = style['formConsentFields']; + if (own is! List) return const []; + return [ + for (final value in own) + if (popupV3ConsentFields.contains(value)) value as String, + ]; + } + + // --- promoCode --- + + /// Статический код или `null` у персонального. + bool get promoStatic => value('promoSource') == 'static'; + + /// Код промокода: статический или `{{promo_code}}` с подстановкой. + String promoCode(PopupV3Variables variables) => promoStatic + ? string('promoStaticCode').trim() + : variables.applyRuntime('{{promo_code}}'); + + bool get promoShowCopy => value('promoShowCopy') != false; + + /// Ссылка «применить» после копирования. + String? promoApplyHref(PopupV3Variables variables) { + final href = text('promoApplyHref'); + return href == null ? null : cssPresent(variables.applyLink(href))?.trim(); + } + + // --- survey --- + + /// Тип опроса: `nps`, `csat`, `ces`; неизвестный — `nps`. + String get surveyType { + final type = value('surveyType'); + return type == 'csat' || type == 'ces' ? type as String : 'nps'; + } + + /// Шкала оценок опроса. + List get surveyScale => switch (surveyType) { + 'csat' => [for (var rate = 1; rate <= 5; rate++) rate], + 'ces' => [for (var rate = 1; rate <= 7; rate++) rate], + _ => [for (var rate = 0; rate <= 10; rate++) rate], + }; + + // --- recommendation --- + + /// Код блока рекомендаций; пусто — элемент не рисуется. + String? get recommenderCode => cssPresent(style['recommenderCode'])?.trim(); + + @override + String toString() => 'PopupV3Element($id, $type)'; +} + +/// Адрес картинки с переменными; только http и https. +String? popupV3ImageUrl(String? raw, PopupV3Variables variables) { + if (raw == null) return null; + final url = variables.apply(raw).trim(); + final uri = Uri.tryParse(url); + if (uri == null || (uri.scheme != 'http' && uri.scheme != 'https')) { + return null; + } + return url; +} + +/// Высота картинки: по пропорциям, в px, в % или vh экрана. +class PopupV3ImageHeight { + const PopupV3ImageHeight.auto() : mode = 'auto', value = 0; + const PopupV3ImageHeight.px(this.value) : mode = 'px'; + const PopupV3ImageHeight.percent(this.value) : mode = '%'; + const PopupV3ImageHeight.vh(this.value) : mode = 'vh'; + + final String mode; + final double value; + + /// Высота в логических px на экране высотой [screenHeight]; `auto` — `null`. + double? resolve(double screenHeight) => switch (mode) { + 'auto' => null, + 'px' => value, + // % на mobile — от высоты экрана, как vh (у сайта — от контейнера). + _ => screenHeight * value / 100, + }; + + @override + bool operator ==(Object other) => + other is PopupV3ImageHeight && other.mode == mode && other.value == value; + + @override + int get hashCode => Object.hash(mode, value); + + @override + String toString() => 'PopupV3ImageHeight($mode $value)'; +} + +/// Поле формы профиля. +class PopupV3FormField { + const PopupV3FormField({ + required this.id, + required this.kind, + required this.label, + required this.placeholder, + required this.required, + required this.propertyKey, + }); + + static const List kinds = [ + 'email', + 'phone', + 'first_name', + 'last_name', + 'birthday', + 'gender', + 'custom', + ]; + + final String id; + final String kind; + final String label; + final String placeholder; + final bool required; + final String propertyKey; +} + +/// Ячейка строки: выравнивание и элементы по порядку. +class PopupV3Cell { + const PopupV3Cell({ + required this.align, + required this.verticalAlign, + required this.elements, + }); + + final PopupV3Align align; + + /// Вертикаль ячейки; если у элемента своя (`cellVerticalAlign`) — ячейка сверху, а + /// элемент встаёт сам. + final PopupV3VerticalAlign verticalAlign; + final List elements; +} + +/// Строка сетки. +class PopupV3Row { + const PopupV3Row({ + required this.id, + required this.fractions, + required this.gap, + required this.minHeight, + required this.cells, + this.background, + this.backgroundImage, + this.backgroundSize = 'cover', + this.backgroundPosition = 'center', + this.backgroundRepeat = 'no-repeat', + }); + + final String id; + + /// Доли колонок, в сумме 1. + final List fractions; + final double gap; + final double minHeight; + final List cells; + final Color? background; + final String? backgroundImage; + final String backgroundSize; + final String backgroundPosition; + final String backgroundRepeat; +} + +/// Затемнение под попапом. +typedef PopupV3Overlay = ({Color color, bool enabled}); + +/// Рамка, посчитанная для экрана. +class PopupV3FrameMetrics { + const PopupV3FrameMetrics({ + required this.width, + required this.maxWidth, + required this.height, + required this.minHeight, + required this.padding, + required this.radius, + }); + + /// Ширина рамки в логических px (до ограничения экраном). + final double width; + + /// Предел ширины; `null` — без предела. + final double? maxWidth; + + /// Высота; `null` — по содержимому. + final double? height; + final double minHeight; + final double padding; + final double radius; + + /// Итоговая ширина: [width] не шире [maxWidth] и [available]. + double resolveWidth(double available) => + math.max(0, math.min(available, math.min(width, maxWidth ?? width))); +} + +/// Рамка попапа (`frameStyle`): размеры с breakpoints, фон, граница, затемнение, +/// отступы баннера. +class PopupV3Frame { + PopupV3Frame(Map raw, {required this.layout}) + : _raw = raw, + background = parseCssColor(raw['bgColor']) ?? const Color(0xffffffff), + borderWidth = math.max(0, cssNum(raw['borderWidth'], 1)), + borderColor = + parseCssColor(raw['borderColor']) ?? const Color(0xffe5e7eb), + offsetX = math.max(0, cssNum(raw['offsetX'], 0)), + offsetY = math.max(0, cssNum(raw['offsetY'], 0)), + lockBackground = cssBool(raw['lockBackgroundScroll']) ?? false, + overlay = _overlay(raw, layout); + + final Map _raw; + final PopupV3Layout layout; + final Color background; + final double borderWidth; + final Color borderColor; + + /// Отступы баннера от краёв: X — слева и справа, Y — от своего края. + final double offsetX; + final double offsetY; + + /// Блокировать приложение под баннером без затемнения. + final bool lockBackground; + final PopupV3Overlay overlay; + + static PopupV3Overlay _overlay( + Map raw, + PopupV3Layout layout, + ) { + final enabled = + cssBool(raw['overlayEnabled']) ?? layout == PopupV3Layout.modal; + final color = parseCssColor(raw['overlayColor']) ?? const Color(0xff000000); + final opacity = cssNum(raw['overlayOpacity'], 0.5).clamp(0, 1).toDouble(); + return ( + color: color.withValues(alpha: color.a * opacity), + enabled: enabled, + ); + } + + /// Размеры для экрана [screen]: breakpoints, у которых `mediaMaxWidth` не меньше + /// ширины экрана, применяются от широкого к узкому (узкий побеждает). + PopupV3FrameMetrics metrics(Size screen) { + final style = Map.from(_raw); + final breakpoints = _raw['breakpoints']; + if (breakpoints is List) { + final matching = + >[ + for (final item in breakpoints) + if (item is Map && + cssNum(item['mediaMaxWidth'], -1) >= screen.width) + item, + ]..sort( + (a, b) => cssNum( + b['mediaMaxWidth'], + 0, + ).compareTo(cssNum(a['mediaMaxWidth'], 0)), + ); + for (final breakpoint in matching) { + for (final key in _breakpointKeys) { + final value = breakpoint[key]; + if (value != null && !(value is String && value.isEmpty)) { + style[key] = value; + } + } + } + } + double size(Object? value, Object? mode, double fallback, double base) { + final number = cssNum(value, fallback); + return switch (mode) { + '%' || 'vw' || 'vh' => base * number / 100, + _ => number, + }; + } + + final widthMode = cssPresent(style['widthMode']) ?? '%'; + final width = size( + style['width'], + widthMode == 'vh' ? 'vw' : widthMode, + 92, + screen.width, + ); + final maxWidthMode = cssPresent(style['maxWidthMode']) ?? 'px'; + final maxWidth = maxWidthMode == 'none' + ? null + : size(style['maxWidth'], maxWidthMode, 480, screen.width); + final heightMode = cssPresent(style['heightMode']) ?? 'auto'; + final height = heightMode == 'auto' + ? null + : size(style['height'], heightMode, 320, screen.height); + final minHeightMode = cssPresent(style['minHeightMode']) ?? 'px'; + final minHeight = size(style['minHeight'], minHeightMode, 0, screen.height); + return PopupV3FrameMetrics( + width: math.max(0, width), + maxWidth: maxWidth == null ? null : math.max(0, maxWidth), + height: height == null ? null : math.max(0, height), + minHeight: math.max(0, minHeight), + padding: math.max(0, cssNum(style['padding'], 20)), + radius: math.max(0, cssNum(style['borderRadius'], 16)), + ); + } + + static const List _breakpointKeys = [ + 'width', + 'widthMode', + 'height', + 'heightMode', + 'maxWidth', + 'maxWidthMode', + 'minHeight', + 'minHeightMode', + 'padding', + 'borderRadius', + ]; +} + +/// Документ design, разобранный один раз до показа: рамка, строки с ячейками и +/// элементами, переменные. Чистый: без виджетов. +class PopupV3Design { + PopupV3Design._({ + required this.frame, + required this.rows, + required this.variables, + required this.dropped, + }); + + /// Лимиты компилятора. + static const int maxRows = 50; + static const int maxColumns = 6; + static const int maxElements = 200; + + final PopupV3Frame frame; + final List rows; + final PopupV3Variables variables; + + /// Не попавшие в рендер элементы: id → причина (лог). + final Map dropped; + + /// Нечего показывать. + bool get isEmpty => + rows.every((row) => row.cells.every((cell) => cell.elements.isEmpty)); + + /// Все элементы по порядку строк и ячеек. + List get elements => [ + for (final row in rows) + for (final cell in row.cells) ...cell.elements, + ]; + + PopupV3Element? element(String id) { + for (final element in elements) { + if (element.id == id) return element; + } + return null; + } + + /// Разбор документа [design] попапа макета [layout]. Элементы неизвестных типов + /// (нет в [types]), с несуществующей строкой или колонкой выпадают в [dropped]. + /// Дизайн без строк — старый формат с `x/y`: элементы идут столбиком по `y`, при + /// равном `y` — по `x`. + factory PopupV3Design.parse( + Map design, { + required PopupV3Layout layout, + required Set types, + Map runtime = const {}, + TargetPlatform? platform, + }) { + final dropped = {}; + final frameRaw = design['frameStyle']; + final frame = PopupV3Frame( + frameRaw is Map + ? Map.from(frameRaw) + : {}, + layout: layout, + ); + final variables = PopupV3Variables.fromDesign( + design['variables'], + runtime: runtime, + platform: platform, + ); + + final rawElements = >[ + for (final item + in design['elements'] is List + ? design['elements'] as List + : const []) + if (item is Map) item, + ]; + if (rawElements.length > maxElements) { + for (final item in rawElements.skip(maxElements)) { + dropped['${item['id']}'] = 'over the limit of $maxElements elements'; + } + rawElements.removeRange(maxElements, rawElements.length); + } + + PopupV3Element? element(Map item) { + final id = cssString(item['id']); + final type = cssString(item['type']); + if (!types.contains(type)) { + dropped[id] = 'unknown type "$type"'; + return null; + } + final style = item['style']; + return PopupV3Element( + id: id, + type: type, + style: style is Map + ? Map.from(style) + : const {}, + ); + } + + final rawRows = >[ + for (final item + in design['rows'] is List + ? design['rows'] as List + : const []) + if (item is Map) item, + ]; + + if (rawRows.isEmpty) { + final sorted = rawElements.toList() + ..sort((a, b) { + final byY = cssNum(a['y'], 0).compareTo(cssNum(b['y'], 0)); + return byY != 0 + ? byY + : cssNum(a['x'], 0).compareTo(cssNum(b['x'], 0)); + }); + final elements = [ + for (final item in sorted) ?element(item), + ]; + return PopupV3Design._( + frame: frame, + rows: elements.isEmpty + ? const [] + : [ + PopupV3Row( + id: '', + fractions: const [1], + gap: 8, + minHeight: 0, + cells: [ + PopupV3Cell( + align: PopupV3Align.left, + verticalAlign: PopupV3VerticalAlign.top, + elements: elements, + ), + ], + ), + ], + variables: variables, + dropped: dropped, + ); + } + + if (rawRows.length > maxRows) rawRows.removeRange(maxRows, rawRows.length); + final byCell = >>{}; + for (final item in rawElements) { + final key = + '${cssString(item['rowId'])}:${cssNum(item['partIndex'], 0).toInt()}'; + (byCell[key] ??= >[]).add(item); + } + final placed = {}; + final rows = []; + for (final row in rawRows) { + final id = cssString(row['id']); + final fractions = _fractions(row); + final cellsRaw = row['cells'] is List ? row['cells'] as List : const []; + final rowAlign = _align(row['align']); + final rowVertical = _verticalAlign(row['verticalAlign']); + final cells = []; + for (var index = 0; index < fractions.length; index++) { + final cell = index < cellsRaw.length && cellsRaw[index] is Map + ? cellsRaw[index] as Map + : const {}; + final items = byCell['$id:$index'] ?? const >[]; + placed.add('$id:$index'); + final elements = [ + for (final item in items) ?element(item), + ]; + final overridden = items.any( + (item) => + item['style'] is Map && + _verticalAlign((item['style'] as Map)['cellVerticalAlign']) != + null, + ); + cells.add( + PopupV3Cell( + align: _align(cell['align']) ?? rowAlign ?? PopupV3Align.left, + verticalAlign: overridden + ? PopupV3VerticalAlign.top + : _verticalAlign(cell['verticalAlign']) ?? + rowVertical ?? + PopupV3VerticalAlign.top, + elements: elements, + ), + ); + } + final bgImage = popupV3ImageUrl(cssPresent(row['bgImageUrl']), variables); + rows.add( + PopupV3Row( + id: id, + fractions: fractions, + gap: math.max(0, cssNum(row['gap'], 8)), + minHeight: math.max(0, cssNum(row['minHeight'], 110)), + cells: cells, + background: cssPresent(row['bgColor']) == null + ? null + : parseCssColor(row['bgColor']), + backgroundImage: bgImage, + backgroundSize: + cssEnum(row['bgSize'], const [ + 'cover', + 'contain', + 'auto', + ]) ?? + 'cover', + backgroundPosition: + cssEnum(row['bgPosition'], const [ + 'center', + 'top', + 'bottom', + 'left', + 'right', + ]) ?? + 'center', + backgroundRepeat: + cssEnum(row['bgRepeat'], const [ + 'no-repeat', + 'repeat', + 'repeat-x', + 'repeat-y', + ]) ?? + 'no-repeat', + ), + ); + } + byCell.forEach((key, items) { + if (placed.contains(key)) return; + for (final item in items) { + dropped[cssString(item['id'])] = 'no row or column $key'; + } + }); + return PopupV3Design._( + frame: frame, + rows: rows, + variables: variables, + dropped: dropped, + ); + } + + /// Доли колонок: проценты `columns`, у старых документов — `parts` равных частей; + /// не больше 6. + static List _fractions(Map row) { + final columns = row['columns']; + var parts = []; + if (columns is List) { + parts = [ + for (final column in columns) + if (cssNum(column, 0) > 0) cssNum(column, 0), + ]; + } + if (parts.isEmpty) { + final count = cssNum(row['parts'], 1).toInt().clamp(1, maxColumns); + parts = List.filled(count, 1); + } + if (parts.length > maxColumns) parts = parts.sublist(0, maxColumns); + final sum = parts.fold(0, (total, part) => total + part); + return [for (final part in parts) part / sum]; + } +} diff --git a/lib/src/ui/popups_v3/popup_v3_elements.dart b/lib/src/ui/popups_v3/popup_v3_elements.dart new file mode 100644 index 0000000..9682696 --- /dev/null +++ b/lib/src/ui/popups_v3/popup_v3_elements.dart @@ -0,0 +1,344 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../popups_v3/popups_v3_api.dart'; +import '../components/personalization_products_list.dart'; +import '../components/personalization_toast.dart'; +import '../widgets/personalization_recommender_block.dart'; +import 'popup_v3_design.dart'; +import 'popup_v3_forms.dart'; +import 'popup_v3_view.dart'; + +/// Рисует содержимое элемента внутри его «коробки»; `null` — элемент не рисуется. +typedef PopupV3ElementBuilder = + Widget? Function(BuildContext context, PopupV3Element element); + +/// Реестр элементов по `type`. Нового типа (`countdown`, `wheel` …) достаточно +/// добавить сюда: документ берёт список известных типов отсюда, остальные +/// пропускает с записью в лог. +final Map popupV3ElementBuilders = + { + 'text': _text, + 'box': _text, + 'button': (context, element) => PopupV3Button(element: element), + 'close': (context, element) => PopupV3Button(element: element), + 'image': _image, + 'emailCollector': (context, element) => + PopupV3EmailCollector(element: element), + 'form': (context, element) => PopupV3ProfileForm(element: element), + 'promoCode': (context, element) => PopupV3PromoCode(element: element), + 'survey': (context, element) => PopupV3Survey(element: element), + 'recommendation': _recommendation, + }; + +Widget? _text(BuildContext context, PopupV3Element element) { + final scope = PopupV3Scope.of(context); + final spans = scope.variables.rich(element.text('message')); + if (spans.isEmpty) return const SizedBox.shrink(); + return PopupV3RichText( + spans, + textAlign: element.messageAlign, + style: popupV3TextStyle( + element.box, + fontSize: element.messageFontSize, + fontWeight: element.messageFontWeight, + ), + ); +} + +/// Кнопка (`link`, `close`, `copy`) и крестик. +class PopupV3Button extends StatelessWidget { + const PopupV3Button({super.key, required this.element}); + + final PopupV3Element element; + + bool get _close => element.type == 'close'; + + void _press(BuildContext context) { + final scope = PopupV3Scope.of(context); + switch (element.buttonAction) { + case 'close': + scope.onClose(); + case 'copy': + final text = element.copyText(scope.variables); + scope.actions.event(PopupV3Event.click); + Clipboard.setData(ClipboardData(text: text)); + PersonalizationToast.show(context, scope.texts.copied); + default: + scope.actions.event(PopupV3Event.click); + final href = element.buttonHref(scope.variables); + if (href != null) scope.followLink(href); + } + } + + @override + Widget build(BuildContext context) { + final scope = PopupV3Scope.of(context); + final box = element.box; + final color = element.color( + 'buttonTextColor', + _close ? '#71717a' : '#ffffff', + ); + final fontSize = element.number('buttonFontSize', _close ? 22 : 12); + final label = _label(scope, box, color, fontSize); + return Semantics( + button: true, + label: _close ? scope.texts.close : null, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => _press(context), + child: Container( + decoration: BoxDecoration( + color: element.color( + 'buttonBgColor', + _close ? 'transparent' : '#2563eb', + ), + borderRadius: BorderRadius.circular( + element.number('buttonRadius', _close ? 999 : 0), + ), + ), + padding: EdgeInsets.symmetric( + horizontal: element.number('buttonPaddingX', _close ? 8 : 0), + vertical: element.number('buttonPaddingY', _close ? 2 : 0), + ), + child: label, + ), + ), + ); + } + + Widget _label( + PopupV3Scope scope, + PopupV3Box box, + Color color, + double fontSize, + ) { + if (_close) { + final size = element.closeIconSize; + final image = element.closeImageUrl(scope.variables); + if (image != null) { + return SizedBox.square( + dimension: size, + child: Image.network( + image, + fit: BoxFit.contain, + semanticLabel: element.text('imageAlt') ?? scope.texts.close, + errorBuilder: (context, error, _) => + PopupV3CloseCross(size: size, color: color), + ), + ); + } + // Встроенный SVG без сторонней библиотеки не нарисовать — стандартный крестик. + if (element.closeSvg != null) { + return PopupV3CloseCross(size: size, color: color); + } + } + final text = + element.text('buttonText') ?? (_close ? '×' : scope.texts.detail); + return PopupV3RichText( + scope.variables.rich(text), + textAlign: TextAlign.center, + style: popupV3TextStyle(box, color: color, fontSize: fontSize, height: 1), + ); + } +} + +/// Крестик: две диагонали толщиной в 1/12 размера. +class PopupV3CloseCross extends StatelessWidget { + const PopupV3CloseCross({super.key, required this.size, required this.color}); + + final double size; + final Color color; + + @override + Widget build(BuildContext context) => + CustomPaint(size: Size.square(size), painter: _CrossPainter(color)); +} + +class _CrossPainter extends CustomPainter { + _CrossPainter(this.color); + + final Color color; + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..strokeWidth = size.width / 12 + ..strokeCap = StrokeCap.round; + final inset = size.width / 4; + canvas + ..drawLine( + Offset(inset, inset), + Offset(size.width - inset, size.height - inset), + paint, + ) + ..drawLine( + Offset(size.width - inset, inset), + Offset(inset, size.height - inset), + paint, + ); + } + + @override + bool shouldRepaint(_CrossPainter oldDelegate) => oldDelegate.color != color; +} + +Widget? _image(BuildContext context, PopupV3Element element) { + if (!element.showImage) return null; + final scope = PopupV3Scope.of(context); + final url = popupV3ImageUrl(element.text('imageUrl'), scope.variables); + if (url == null) return null; + final screen = MediaQuery.sizeOf(context); + final height = element.imageHeight.resolve(screen.height); + final ratio = height == null ? element.imageAspectRatio : null; + Widget image = Image.network( + url, + width: double.infinity, + height: height, + fit: element.imageFit, + semanticLabel: element.text('imageAlt') ?? scope.texts.image, + errorBuilder: (context, error, _) => const SizedBox.shrink(), + ); + if (ratio != null) image = AspectRatio(aspectRatio: ratio, child: image); + return Padding( + padding: EdgeInsets.only( + bottom: element.number('imageMarginBottom', 0).clamp(0, 1000).toDouble(), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(element.number('imageRadius', 0)), + child: image, + ), + ); +} + +/// Промокод: подпись, код моноширинным жирным и «Скопировать» → «Скопировано»; +/// после копирования — ссылка применения. +class PopupV3PromoCode extends StatefulWidget { + const PopupV3PromoCode({super.key, required this.element}); + + final PopupV3Element element; + + @override + State createState() => _PopupV3PromoCodeState(); +} + +class _PopupV3PromoCodeState extends State { + bool _copied = false; + + void _copy(String code) { + final scope = PopupV3Scope.of(context); + Clipboard.setData(ClipboardData(text: code)); + scope.actions.event(PopupV3Event.click); + setState(() => _copied = true); + final apply = widget.element.promoApplyHref(scope.variables); + if (apply != null) scope.followLink(apply); + } + + @override + Widget build(BuildContext context) { + final element = widget.element; + final scope = PopupV3Scope.of(context); + final box = element.box; + final code = element.promoCode(scope.variables); + final align = switch (element.value('messageAlign')) { + 'left' => CrossAxisAlignment.start, + 'right' => CrossAxisAlignment.end, + _ => CrossAxisAlignment.center, + }; + final codeColor = element.color('promoCodeColor', '#92400e'); + final copyText = _copied + ? (element.text('promoCopiedText') ?? scope.texts.copied) + : (element.text('promoCopyText') ?? scope.texts.copy); + final label = element.text('promoLabel'); + return Column( + crossAxisAlignment: align, + mainAxisSize: MainAxisSize.min, + children: [ + if (label != null) ...[ + PopupV3RichText( + scope.variables.rich(label), + textAlign: element.messageAlign, + style: popupV3TextStyle( + box, + fontSize: element.messageFontSize, + fontWeight: element.messageFontWeight, + ), + ), + const SizedBox(height: 6), + ], + Container( + decoration: BoxDecoration( + color: element.color('promoCodeBg', '#fef3c7'), + borderRadius: BorderRadius.circular( + element.number('promoCodeRadius', 10), + ), + ), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + code, + style: popupV3TextStyle( + box, + color: codeColor, + fontSize: element.number('promoCodeFontSize', 20), + fontWeight: 700, + letterSpacing: 1, + fontFamily: popupV3FontFamily('monospace'), + ), + ), + ), + if (element.promoShowCopy) ...[ + const SizedBox(width: 10), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => _copy(code), + child: Opacity( + opacity: 0.8, + child: PopupV3RichText( + scope.variables.rich(copyText), + style: popupV3TextStyle( + box, + color: codeColor, + fontSize: 11, + fontWeight: 500, + letterSpacing: 0, + ), + ), + ), + ), + ], + ], + ), + ), + ], + ); + } +} + +Widget? _recommendation(BuildContext context, PopupV3Element element) { + final code = element.recommenderCode; + if (code == null) return null; + final scope = PopupV3Scope.of(context); + return PopupV3KitTheme( + element: element, + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 40), + child: PersonalizationRecommenderBlock( + code: code, + sdk: scope.actions.sdk, + layout: PersonalizationProductsLayout.carousel, + // Товар — ссылка: событие `click`, как у сайта (там товары блока — ссылки). + // Открыл его или его ссылку хост — попап уходит, как после перехода; + // ссылка ушла системе — остаётся. + onProductTap: (product) { + scope.actions.event(PopupV3Event.click); + if (scope.actions.openProduct(product)) scope.onDismiss(); + }, + ), + ), + ); +} diff --git a/lib/src/ui/popups_v3/popup_v3_forms.dart b/lib/src/ui/popups_v3/popup_v3_forms.dart new file mode 100644 index 0000000..436884e --- /dev/null +++ b/lib/src/ui/popups_v3/popup_v3_forms.dart @@ -0,0 +1,944 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../../popups_v3/popups_v3_engine.dart'; +import '../components/personalization_checkbox.dart'; +import '../widgets/stories_api_v3.dart'; +import 'popup_markup.dart'; +import 'popup_v3_design.dart'; +import 'popup_v3_view.dart'; + +final RegExp _emailFormat = RegExp(r'^[^\s@]+@[^\s@]+\.[^\s@]+$'); +final RegExp _phoneFormat = RegExp(r'^\+?[\d\s\-()]{5,20}$'); + +/// Похож ли [value] на email. +bool popupV3ValidEmail(String value) => _emailFormat.hasMatch(value.trim()); + +/// Похож ли [value] на телефон. +bool popupV3ValidPhone(String value) => _phoneFormat.hasMatch(value.trim()); + +const Color _errorColor = Color(0xffb91c1c); + +/// Фон кнопки формы: `buttonBgColor`. +Color _buttonBackground(PopupV3Element element) => + element.color('buttonBgColor', '#2563eb'); + +/// Текст кнопки формы: `buttonTextColor`. +Color _buttonForeground(PopupV3Element element) => + element.color('buttonTextColor', '#ffffff'); + +/// Поле ввода формы попапа по стилям дизайна: фон, цвет, рамка, радиус. +class PopupV3Input extends StatelessWidget { + const PopupV3Input({ + super.key, + required this.controller, + required this.style, + required this.background, + required this.borderColor, + required this.radius, + required this.paddingY, + this.placeholder, + this.keyboardType, + this.maxLines = 1, + this.minLines, + this.enabled = true, + this.onSubmitted, + }); + + final TextEditingController controller; + final TextStyle style; + final Color background; + final Color borderColor; + final double radius; + final double paddingY; + final String? placeholder; + final TextInputType? keyboardType; + final int? maxLines; + final int? minLines; + final bool enabled; + final ValueChanged? onSubmitted; + + @override + Widget build(BuildContext context) { + final border = OutlineInputBorder( + borderRadius: BorderRadius.circular(radius), + borderSide: BorderSide(color: borderColor), + ); + return TextField( + controller: controller, + enabled: enabled, + style: style, + keyboardType: keyboardType, + maxLines: maxLines, + minLines: minLines, + cursorColor: style.color, + textInputAction: maxLines == 1 ? TextInputAction.done : null, + onSubmitted: onSubmitted, + onTapOutside: (_) => FocusManager.instance.primaryFocus?.unfocus(), + decoration: InputDecoration( + isDense: true, + filled: true, + fillColor: background, + hintText: placeholder, + hintStyle: style.copyWith(color: style.color?.withValues(alpha: 0.5)), + contentPadding: EdgeInsets.symmetric( + horizontal: 12, + vertical: paddingY, + ), + border: border, + enabledBorder: border, + disabledBorder: border, + focusedBorder: border, + ), + ); + } +} + +/// Кнопка отправки формы по стилям `button*` дизайна; пока идёт отправка — приглушена +/// и не нажимается. +class PopupV3SubmitButton extends StatelessWidget { + const PopupV3SubmitButton({ + super.key, + required this.element, + required this.label, + required this.busy, + required this.onPressed, + this.paddingX = 18, + }); + + final PopupV3Element element; + final String label; + final bool busy; + final VoidCallback onPressed; + final double paddingX; + + @override + Widget build(BuildContext context) { + final scope = PopupV3Scope.of(context); + return Semantics( + button: true, + enabled: !busy, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: busy ? null : onPressed, + child: Opacity( + opacity: busy ? 0.6 : 1, + child: Container( + decoration: BoxDecoration( + color: _buttonBackground(element), + borderRadius: BorderRadius.circular( + element.number('buttonRadius', 10), + ), + ), + padding: EdgeInsets.symmetric( + horizontal: element.number('buttonPaddingX', paddingX), + vertical: element.number('buttonPaddingY', 10), + ), + child: PopupV3RichText( + scope.variables.rich(label), + textAlign: TextAlign.center, + style: popupV3TextStyle( + element.box, + color: _buttonForeground(element), + fontSize: element.number('buttonFontSize', 14), + fontWeight: 500, + height: 1.25, + ), + ), + ), + ), + ), + ); + } +} + +/// Согласие: чекбокс кита и подпись с разметкой. +/// +/// Чекбокс — в цветах формы, а не темы кита: попап рисуется по дизайну и от темы +/// системы не зависит. Отмеченный — как кнопка формы ([element]), пустой — как +/// поле ввода ([inputBackground], [inputBorder]). +class PopupV3Consent extends StatelessWidget { + const PopupV3Consent({ + super.key, + required this.label, + required this.value, + required this.onChanged, + required this.style, + required this.element, + required this.inputBackground, + required this.inputBorder, + }); + + final String label; + final bool value; + final ValueChanged onChanged; + final TextStyle style; + + /// Элемент формы: цвета кнопки. + final PopupV3Element element; + + /// Фон поля ввода формы. + final Color inputBackground; + + /// Рамка поля ввода формы. + final Color inputBorder; + + @override + Widget build(BuildContext context) { + final scope = PopupV3Scope.of(context); + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => onChanged(!value), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + PersonalizationCheckbox( + state: value + ? PersonalizationCheckboxState.checked + : PersonalizationCheckboxState.unchecked, + onChanged: (state) => + onChanged(state == PersonalizationCheckboxState.checked), + checkedColor: _buttonBackground(element), + checkmarkColor: _buttonForeground(element), + uncheckedColor: inputBackground, + borderColor: inputBorder, + ), + const SizedBox(width: 8), + Expanded( + child: Padding( + padding: const EdgeInsets.only(top: 2), + child: PopupV3RichText(scope.variables.rich(label), style: style), + ), + ), + ], + ), + ); + } +} + +/// Текст ошибки формы. +class PopupV3Status extends StatelessWidget { + const PopupV3Status({super.key, required this.text, required this.box}); + + final String text; + final PopupV3Box box; + + @override + Widget build(BuildContext context) => Text( + text, + style: popupV3TextStyle( + box, + color: _errorColor, + fontSize: 12, + fontWeight: 400, + height: 1.35, + ), + ); +} + +/// Экран успеха формы: заголовок и текст. +class PopupV3Success extends StatelessWidget { + const PopupV3Success({ + super.key, + required this.box, + required this.title, + required this.message, + this.background = const Color(0x00000000), + this.color, + this.titleColor, + this.align = TextAlign.center, + this.radius = 0, + this.paddingX = 0, + this.paddingY = 0, + this.titleSize = 16, + this.messageSize = 13, + }); + + final PopupV3Box box; + final String? title; + final String? message; + final Color background; + final Color? color; + final Color? titleColor; + final TextAlign align; + final double radius; + final double paddingX; + final double paddingY; + final double titleSize; + final double messageSize; + + @override + Widget build(BuildContext context) { + final scope = PopupV3Scope.of(context); + final title = this.title ?? (message == null ? scope.texts.thanks : null); + return Container( + width: double.infinity, + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(radius), + ), + padding: EdgeInsets.symmetric(horizontal: paddingX, vertical: paddingY), + child: Column( + crossAxisAlignment: switch (align) { + TextAlign.left => CrossAxisAlignment.start, + TextAlign.right => CrossAxisAlignment.end, + _ => CrossAxisAlignment.center, + }, + mainAxisSize: MainAxisSize.min, + children: [ + if (title != null) + PopupV3RichText( + scope.variables.rich(title), + textAlign: align, + style: popupV3TextStyle( + box, + color: titleColor ?? color, + fontSize: titleSize, + fontWeight: 600, + height: 1.3, + ), + ), + if (message != null) ...[ + if (title != null) const SizedBox(height: 6), + PopupV3RichText( + scope.variables.rich(message), + textAlign: align, + style: popupV3TextStyle( + box, + color: color, + fontSize: messageSize, + fontWeight: 400, + height: 1.4, + ), + ), + ], + ], + ), + ); + } +} + +/// Шрифт полей форм: `fontSize` (13), не меньше 12. +double _inputFontSize(PopupV3Element element) => + math.max(element.number('fontSize', 13), 12); + +/// Форма подписки: email, кнопка, согласие (обязательно), ошибка, экран успеха. +class PopupV3EmailCollector extends StatefulWidget { + const PopupV3EmailCollector({super.key, required this.element}); + + final PopupV3Element element; + + @override + State createState() => _PopupV3EmailCollectorState(); +} + +class _PopupV3EmailCollectorState extends State { + final TextEditingController _email = TextEditingController(); + bool _consent = false; + bool _busy = false; + bool _done = false; + String? _error; + + @override + void dispose() { + _email.dispose(); + super.dispose(); + } + + Future _submit() async { + if (_busy) return; + final element = widget.element; + final scope = PopupV3Scope.of(context); + final email = _email.text.trim(); + if (!_consent || !popupV3ValidEmail(email)) { + setState( + () => _error = scope.variables.apply( + element.text('emailErrorMessage') ?? scope.texts.emailError, + ), + ); + return; + } + FocusManager.instance.primaryFocus?.unfocus(); + setState(() { + _busy = true; + _error = null; + }); + try { + await scope.actions.subscribeEmail( + email: email, + consentFields: element.emailConsentFields, + segmentId: element.segmentId('emailSegmentId'), + ); + if (mounted) setState(() => _done = true); + } catch (error) { + if (mounted) setState(() => _error = scope.texts.sendError); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + @override + Widget build(BuildContext context) { + final element = widget.element; + final scope = PopupV3Scope.of(context); + final box = element.box; + if (_done) { + final align = element.value('emailSuccessAlign'); + return PopupV3Success( + box: box, + title: element.text('emailSuccessTitle'), + message: element.text('emailSuccessMessage'), + background: element.color('emailSuccessBg', '#ecfdf5'), + color: element.color('emailSuccessColor', '#065f46'), + titleColor: element.color('emailSuccessTitleColor', '#047857'), + align: align == 'left' + ? TextAlign.left + : align == 'right' + ? TextAlign.right + : TextAlign.center, + radius: element.number('emailSuccessRadius', 12), + paddingX: element.number('emailSuccessPaddingX', 14), + paddingY: element.number('emailSuccessPaddingY', 16), + titleSize: element.number('emailSuccessTitleFontSize', 16), + messageSize: element.number('emailSuccessFontSize', 13), + ); + } + final paddingY = element.number('buttonPaddingY', 10); + final background = element.color('emailInputBg', '#f8fafc'); + final borderColor = element.color('emailInputBorderColor', '#cbd5e1'); + final input = PopupV3Input( + controller: _email, + enabled: !_busy, + keyboardType: TextInputType.emailAddress, + placeholder: scope.variables.apply( + element.text('emailPlaceholder') ?? scope.texts.email, + ), + style: popupV3TextStyle( + box, + color: element.color('emailInputColor', '#0f172a'), + fontSize: _inputFontSize(element), + fontWeight: 400, + height: 1.25, + ), + background: background, + borderColor: borderColor, + radius: element.number('emailInputRadius', 10), + paddingY: paddingY, + onSubmitted: (_) => _submit(), + ); + final button = PopupV3SubmitButton( + element: element, + label: element.text('emailSubmitText') ?? scope.texts.subscribe, + busy: _busy, + onPressed: _submit, + ); + final error = _error; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + if (element.emailInline) + Row( + children: [ + Expanded(child: input), + const SizedBox(width: 8), + button, + ], + ) + else ...[input, const SizedBox(height: 8), button], + const SizedBox(height: 8), + PopupV3Consent( + label: element.emailConsentLabel ?? scope.texts.emailConsent, + value: _consent, + onChanged: (value) => setState(() => _consent = value), + style: popupV3TextStyle( + box, + fontSize: 11, + fontWeight: 400, + height: 1.35, + ), + element: element, + inputBackground: background, + inputBorder: borderColor, + ), + if (error != null) ...[ + const SizedBox(height: 8), + PopupV3Status(text: error, box: box), + ], + ], + ); + } +} + +/// Форма профиля: до 8 полей, согласие, ошибка, отправка в профиль и сегмент. +class PopupV3ProfileForm extends StatefulWidget { + const PopupV3ProfileForm({super.key, required this.element}); + + final PopupV3Element element; + + @override + State createState() => _PopupV3ProfileFormState(); +} + +class _PopupV3ProfileFormState extends State { + late final List _fields = widget.element.formFields; + late final Map _controllers = + { + for (final field in _fields) + if (field.kind != 'gender' && field.kind != 'birthday') + field.id: TextEditingController(), + }; + final Map _choices = {}; + bool _consent = false; + bool _busy = false; + bool _done = false; + String? _error; + + @override + void dispose() { + for (final controller in _controllers.values) { + controller.dispose(); + } + super.dispose(); + } + + String _value(PopupV3FormField field) => + (_controllers[field.id]?.text ?? _choices[field.id] ?? '').trim(); + + /// Данные формы или `null`, если обязательное поле пусто либо email или телефон не + /// по формату. + PopupV3ProfileSubmission? _collect() { + final standard = {}; + final custom = {}; + for (final field in _fields) { + final value = _value(field); + if (value.isEmpty) { + if (field.required) return null; + continue; + } + if (field.kind == 'email' && !popupV3ValidEmail(value)) return null; + if (field.kind == 'phone' && !popupV3ValidPhone(value)) return null; + if (field.kind == 'custom') { + if (field.propertyKey.isNotEmpty) custom[field.propertyKey] = value; + } else { + standard[field.kind] = value; + } + } + return PopupV3ProfileSubmission( + email: standard['email'], + phone: standard['phone'], + firstName: standard['first_name'], + lastName: standard['last_name'], + birthday: standard['birthday'], + gender: standard['gender'], + custom: custom, + consentFields: _consent + ? widget.element.formConsentFields + : const [], + segmentId: widget.element.segmentId('formSegmentId'), + ); + } + + Future _submit() async { + if (_busy) return; + final scope = PopupV3Scope.of(context); + final submission = _collect(); + if (submission == null) { + setState( + () => _error = scope.variables.apply( + widget.element.text('formErrorMessage') ?? scope.texts.formError, + ), + ); + return; + } + FocusManager.instance.primaryFocus?.unfocus(); + setState(() { + _busy = true; + _error = null; + }); + try { + await scope.actions.submitProfile(submission); + if (mounted) setState(() => _done = true); + } catch (error) { + if (mounted) setState(() => _error = scope.texts.sendError); + } finally { + if (mounted) setState(() => _busy = false); + } + } + + Future _pickDate(PopupV3FormField field) async { + final now = DateTime.now(); + final current = DateTime.tryParse(_choices[field.id] ?? ''); + final picked = await showDatePicker( + context: context, + initialDate: current ?? DateTime(now.year - 25), + firstDate: DateTime(1900), + lastDate: now, + ); + if (picked == null || !mounted) return; + String two(int value) => value.toString().padLeft(2, '0'); + setState( + () => _choices[field.id] = + '${picked.year}-${two(picked.month)}-${two(picked.day)}', + ); + } + + @override + Widget build(BuildContext context) { + final element = widget.element; + final scope = PopupV3Scope.of(context); + final box = element.box; + if (_done) { + return PopupV3Success( + box: box, + title: element.text('formSuccessTitle'), + message: element.text('formSuccessMessage'), + ); + } + final inputStyle = popupV3TextStyle( + box, + color: element.color('formInputColor', '#0f172a'), + fontSize: _inputFontSize(element), + fontWeight: 400, + height: 1.25, + ); + final background = element.color('formInputBg', '#f8fafc'); + final borderColor = element.color('formInputBorderColor', '#cbd5e1'); + final radius = element.number('formInputRadius', 10); + final paddingY = element.number('buttonPaddingY', 10); + final labelStyle = popupV3TextStyle(box, fontSize: 11, fontWeight: 400); + final consentFields = element.formConsentFields; + final consentLabel = element.text('formConsentLabel'); + final error = _error; + + Widget choice(PopupV3FormField field, String value, String label) { + final selected = _choices[field.id] == value; + return Expanded( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: _busy + ? null + : () => setState( + () => selected + ? _choices.remove(field.id) + : _choices[field.id] = value, + ), + child: Container( + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(radius), + border: Border.all( + color: selected ? inputStyle.color! : borderColor, + width: selected ? 2 : 1, + ), + ), + padding: EdgeInsets.symmetric(vertical: paddingY, horizontal: 12), + child: Text( + label, + textAlign: TextAlign.center, + style: inputStyle.copyWith( + fontWeight: selected ? FontWeight.w600 : null, + ), + ), + ), + ), + ); + } + + Widget input(PopupV3FormField field) { + switch (field.kind) { + case 'gender': + return Row( + children: [ + choice(field, 'm', scope.texts.genderMale), + const SizedBox(width: 8), + choice(field, 'f', scope.texts.genderFemale), + ], + ); + case 'birthday': + final value = _choices[field.id]; + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: _busy ? null : () => _pickDate(field), + child: Container( + width: double.infinity, + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(radius), + border: Border.all(color: borderColor), + ), + padding: EdgeInsets.symmetric(vertical: paddingY, horizontal: 12), + child: Text( + value ?? scope.variables.apply(field.placeholder), + style: value == null + ? inputStyle.copyWith( + color: inputStyle.color?.withValues(alpha: 0.5), + ) + : inputStyle, + ), + ), + ); + default: + return PopupV3Input( + controller: _controllers[field.id]!, + enabled: !_busy, + keyboardType: switch (field.kind) { + 'email' => TextInputType.emailAddress, + 'phone' => TextInputType.phone, + _ => TextInputType.text, + }, + placeholder: scope.variables.apply(field.placeholder), + style: inputStyle, + background: background, + borderColor: borderColor, + radius: radius, + paddingY: paddingY, + ); + } + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + for (final field in _fields) ...[ + if (field.label.isNotEmpty) ...[ + PopupV3RichText([ + ...scope.variables.rich(field.label), + if (field.required) ...scope.variables.rich(' *'), + ], style: labelStyle), + const SizedBox(height: 4), + ], + input(field), + const SizedBox(height: 8), + ], + if (consentFields.isNotEmpty || consentLabel != null) ...[ + PopupV3Consent( + label: consentLabel ?? scope.texts.emailConsent, + value: _consent, + onChanged: (value) => setState(() => _consent = value), + style: popupV3TextStyle( + box, + fontSize: 11, + fontWeight: 400, + height: 1.35, + ), + element: element, + inputBackground: background, + inputBorder: borderColor, + ), + const SizedBox(height: 8), + ], + if (error != null) ...[ + PopupV3Status(text: error, box: box), + const SizedBox(height: 8), + ], + PopupV3SubmitButton( + element: element, + label: element.text('formSubmitText') ?? scope.texts.send, + busy: _busy, + onPressed: _submit, + ), + ], + ); + } +} + +/// Мини-опрос NPS / CSAT / CES: вопрос, шкала, после оценки — комментарий и кнопка, +/// затем «спасибо». Ошибка отправки — текстом, можно отправить снова. +class PopupV3Survey extends StatefulWidget { + const PopupV3Survey({super.key, required this.element}); + + final PopupV3Element element; + + @override + State createState() => _PopupV3SurveyState(); +} + +class _PopupV3SurveyState extends State { + final TextEditingController _comment = TextEditingController(); + int? _rate; + bool _busy = false; + bool _done = false; + String? _error; + + @override + void dispose() { + _comment.dispose(); + super.dispose(); + } + + Future _submit() async { + final rate = _rate; + if (_busy || rate == null) return; + final element = widget.element; + final scope = PopupV3Scope.of(context); + FocusManager.instance.primaryFocus?.unfocus(); + setState(() { + _busy = true; + _error = null; + }); + try { + await scope.actions.review( + kind: element.surveyType, + code: element.string('surveyCampaignCode').trim(), + rate: rate, + comment: _comment.text, + ); + if (mounted) setState(() => _done = true); + } catch (error) { + // Ответ сервера («Channel not found») — в скобках: без него не понять, что + // не так с кампанией или каналом опроса. + final reason = error is StoriesV3Exception ? error.message : null; + if (mounted) { + setState( + () => _error = reason == null + ? scope.texts.sendError + : '${scope.texts.sendError} ($reason)', + ); + } + } finally { + if (mounted) setState(() => _busy = false); + } + } + + @override + Widget build(BuildContext context) { + final element = widget.element; + final scope = PopupV3Scope.of(context); + final box = element.box; + if (_done) { + return PopupV3RichText( + scope.variables.rich( + element.text('surveyThanksText') ?? scope.texts.thanks, + ), + style: popupV3TextStyle(box, fontWeight: 600), + ); + } + final question = element.text('surveyQuestion'); + final minLabel = element.text('surveyMinLabel'); + final maxLabel = element.text('surveyMaxLabel'); + final scaleBg = element.color('surveyScaleBg', '#f3f4f6'); + final scaleColor = element.color('surveyScaleColor', '#111827'); + final activeBg = element.color('surveyScaleActiveBg', '#2563eb'); + final activeColor = element.color('surveyScaleActiveColor', '#ffffff'); + final labelStyle = popupV3TextStyle(box, fontSize: 11); + final error = _error; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + if (question != null) ...[ + PopupV3RichText( + scope.variables.rich(question), + style: popupV3TextStyle(box, fontWeight: 600), + ), + const SizedBox(height: 10), + ], + Wrap( + spacing: 6, + runSpacing: 6, + children: [ + for (final rate in element.surveyScale) + Semantics( + button: true, + selected: rate == _rate, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: _busy ? null : () => setState(() => _rate = rate), + // Не шире своей цифры (не меньше 30): с `alignment` у Container + // ячейка растянулась бы на всю строку Wrap. + child: Container( + constraints: const BoxConstraints(minWidth: 30), + height: 30, + padding: const EdgeInsets.symmetric(horizontal: 6), + decoration: BoxDecoration( + color: rate == _rate ? activeBg : scaleBg, + borderRadius: BorderRadius.circular(8), + ), + child: Center( + widthFactor: 1, + child: Text( + '$rate', + style: popupV3TextStyle( + box, + color: rate == _rate ? activeColor : scaleColor, + fontSize: 13, + fontWeight: 600, + height: 1, + ), + ), + ), + ), + ), + ), + ], + ), + if (minLabel != null || maxLabel != null) ...[ + const SizedBox(height: 10), + Opacity( + opacity: 0.7, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: PopupV3RichText( + scope.variables.rich(minLabel), + style: labelStyle, + ), + ), + const SizedBox(width: 8), + Expanded( + child: PopupV3RichText( + scope.variables.rich(maxLabel), + style: labelStyle, + textAlign: TextAlign.right, + ), + ), + ], + ), + ), + ], + if (_rate != null) ...[ + const SizedBox(height: 10), + PopupV3Input( + controller: _comment, + enabled: !_busy, + maxLines: 3, + minLines: 3, + keyboardType: TextInputType.multiline, + placeholder: scope.variables.apply( + element.string('surveyCommentPlaceholder'), + ), + style: popupV3TextStyle( + box, + color: const Color(0xff111827), + fontSize: 13, + fontWeight: 400, + height: 1.3, + ), + background: const Color(0xffffffff), + borderColor: const Color(0xffcbd5e1), + radius: 10, + paddingY: 8, + ), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerLeft, + child: PopupV3SubmitButton( + element: element, + label: element.text('surveySubmitText') ?? scope.texts.send, + busy: _busy, + onPressed: _submit, + ), + ), + ], + if (error != null) ...[ + const SizedBox(height: 8), + PopupV3Status(text: error, box: box), + ], + ], + ); + } +} diff --git a/lib/src/ui/popups_v3/popup_v3_grid.dart b/lib/src/ui/popups_v3/popup_v3_grid.dart new file mode 100644 index 0000000..263b3c5 --- /dev/null +++ b/lib/src/ui/popups_v3/popup_v3_grid.dart @@ -0,0 +1,314 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +import 'popup_v3_design.dart'; + +/// Строка сетки попапа: ячейки по долям ширины с промежутком [gap], высота — самая +/// высокая ячейка, но не меньше [minHeight]; каждая ячейка растягивается на высоту +/// строки. Содержимое за краями строки обрезается (`overflow: hidden`). +class PopupV3RowLayout extends MultiChildRenderObjectWidget { + const PopupV3RowLayout({ + super.key, + required this.fractions, + required this.gap, + required this.minHeight, + required super.children, + }); + + final List fractions; + final double gap; + final double minHeight; + + @override + RenderPopupV3Row createRenderObject(BuildContext context) => + RenderPopupV3Row(fractions: fractions, gap: gap, minHeight: minHeight); + + @override + void updateRenderObject(BuildContext context, RenderPopupV3Row renderObject) { + renderObject + ..fractions = fractions + ..gap = gap + ..minHeight = minHeight; + } +} + +class PopupV3RowParentData extends ContainerBoxParentData {} + +class RenderPopupV3Row extends RenderBox + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { + RenderPopupV3Row({ + required List fractions, + required double gap, + required double minHeight, + }) : _fractions = fractions, + _gap = gap, + _minHeight = minHeight; + + List _fractions; + set fractions(List value) { + if (listEquals(value, _fractions)) return; + _fractions = value; + markNeedsLayout(); + } + + double _gap; + set gap(double value) { + if (value == _gap) return; + _gap = value; + markNeedsLayout(); + } + + double _minHeight; + set minHeight(double value) { + if (value == _minHeight) return; + _minHeight = value; + markNeedsLayout(); + } + + @override + void setupParentData(RenderBox child) { + if (child.parentData is! PopupV3RowParentData) { + child.parentData = PopupV3RowParentData(); + } + } + + List _widths(double width) { + final count = childCount; + final available = math.max(0.0, width - _gap * math.max(0, count - 1)); + return [ + for (var index = 0; index < count; index++) + available * (index < _fractions.length ? _fractions[index] : 0), + ]; + } + + @override + void performLayout() { + final width = constraints.maxWidth.isFinite + ? constraints.maxWidth + : constraints.minWidth; + final widths = _widths(width); + // Первый проход — естественная высота каждой ячейки, второй — ячейка на всю + // высоту строки (в ней работает вертикальное выравнивание). + var height = _minHeight; + var child = firstChild; + var index = 0; + while (child != null) { + child.layout( + BoxConstraints(minWidth: widths[index], maxWidth: widths[index]), + parentUsesSize: true, + ); + height = math.max(height, child.size.height); + child = childAfter(child); + index++; + } + height = constraints.constrainHeight(height); + child = firstChild; + index = 0; + var x = 0.0; + while (child != null) { + // Не жёсткие ограничения: с жёсткими ячейка стала бы границей перекладки, и + // выросшее содержимое (форма опроса после оценки) не раздвинуло бы строку. + child.layout( + BoxConstraints( + minWidth: widths[index], + maxWidth: widths[index], + minHeight: height, + ), + parentUsesSize: true, + ); + (child.parentData! as PopupV3RowParentData).offset = Offset(x, 0); + x += widths[index] + _gap; + child = childAfter(child); + index++; + } + size = constraints.constrain(Size(width, height)); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) => + defaultHitTestChildren(result, position: position); + + @override + void paint(PaintingContext context, Offset offset) { + _clip.layer = context.pushClipRect( + needsCompositing, + offset, + Offset.zero & size, + defaultPaint, + oldLayer: _clip.layer, + ); + } + + final LayerHandle _clip = LayerHandle(); + + @override + void dispose() { + _clip.layer = null; + super.dispose(); + } +} + +/// Как элемент стоит в ячейке. +class PopupV3CellSlot extends ParentDataWidget { + const PopupV3CellSlot({ + super.key, + required this.align, + required this.verticalAlign, + required super.child, + }); + + /// По горизонтали; `null` — на всю ширину ячейки. + final PopupV3Align? align; + + /// Своя вертикаль элемента (`cellVerticalAlign`). + final PopupV3VerticalAlign? verticalAlign; + + @override + void applyParentData(RenderObject renderObject) { + final data = renderObject.parentData! as PopupV3CellParentData; + if (data.align == align && data.verticalAlign == verticalAlign) return; + data + ..align = align + ..verticalAlign = verticalAlign; + renderObject.parent?.markNeedsLayout(); + } + + @override + Type get debugTypicalAncestorWidgetClass => PopupV3CellLayout; +} + +/// Ячейка: элементы столбиком с промежутком [gap]. Ячейка выше содержимого — элементы +/// встают по [verticalAlign]; элемент со своей вертикалью отодвигается сам, как +/// `margin: auto` во flex-колонке. +class PopupV3CellLayout extends MultiChildRenderObjectWidget { + const PopupV3CellLayout({ + super.key, + required this.gap, + required this.verticalAlign, + required super.children, + }); + + final double gap; + final PopupV3VerticalAlign verticalAlign; + + @override + RenderPopupV3Cell createRenderObject(BuildContext context) => + RenderPopupV3Cell(gap: gap, verticalAlign: verticalAlign); + + @override + void updateRenderObject( + BuildContext context, + RenderPopupV3Cell renderObject, + ) { + renderObject + ..gap = gap + ..verticalAlign = verticalAlign; + } +} + +class PopupV3CellParentData extends ContainerBoxParentData { + PopupV3Align? align; + PopupV3VerticalAlign? verticalAlign; +} + +class RenderPopupV3Cell extends RenderBox + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { + RenderPopupV3Cell({ + required double gap, + required PopupV3VerticalAlign verticalAlign, + }) : _gap = gap, + _verticalAlign = verticalAlign; + + double _gap; + set gap(double value) { + if (value == _gap) return; + _gap = value; + markNeedsLayout(); + } + + PopupV3VerticalAlign _verticalAlign; + set verticalAlign(PopupV3VerticalAlign value) { + if (value == _verticalAlign) return; + _verticalAlign = value; + markNeedsLayout(); + } + + @override + void setupParentData(RenderBox child) { + if (child.parentData is! PopupV3CellParentData) { + child.parentData = PopupV3CellParentData(); + } + } + + @override + void performLayout() { + final width = constraints.maxWidth.isFinite + ? constraints.maxWidth + : constraints.minWidth; + var content = 0.0; + var autos = 0; + var child = firstChild; + while (child != null) { + final data = child.parentData! as PopupV3CellParentData; + child.layout( + data.align == null + ? BoxConstraints.tightFor(width: width) + : BoxConstraints(maxWidth: width), + parentUsesSize: true, + ); + content += child.size.height; + autos += switch (data.verticalAlign) { + PopupV3VerticalAlign.center => 2, + PopupV3VerticalAlign.bottom => 1, + _ => 0, + }; + child = childAfter(child); + } + if (childCount > 1) content += _gap * (childCount - 1); + final height = constraints.hasBoundedHeight + ? constraints.constrainHeight(math.max(content, constraints.minHeight)) + : math.max(content, constraints.minHeight); + final free = math.max(0.0, height - content); + final perAuto = autos == 0 ? 0.0 : free / autos; + var y = autos > 0 + ? 0.0 + : switch (_verticalAlign) { + PopupV3VerticalAlign.center => free / 2, + PopupV3VerticalAlign.bottom => free, + PopupV3VerticalAlign.top => 0.0, + }; + child = firstChild; + while (child != null) { + final data = child.parentData! as PopupV3CellParentData; + if (data.verticalAlign == PopupV3VerticalAlign.center || + data.verticalAlign == PopupV3VerticalAlign.bottom) { + y += perAuto; + } + final x = switch (data.align) { + PopupV3Align.center => (width - child.size.width) / 2, + PopupV3Align.right => width - child.size.width, + _ => 0.0, + }; + data.offset = Offset(x, y); + y += child.size.height + _gap; + if (data.verticalAlign == PopupV3VerticalAlign.center) y += perAuto; + child = childAfter(child); + } + size = constraints.constrain(Size(width, height)); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) => + defaultHitTestChildren(result, position: position); + + @override + void paint(PaintingContext context, Offset offset) => + defaultPaint(context, offset); +} diff --git a/lib/src/ui/popups_v3/popup_v3_host.dart b/lib/src/ui/popups_v3/popup_v3_host.dart new file mode 100644 index 0000000..a7ae9ff --- /dev/null +++ b/lib/src/ui/popups_v3/popup_v3_host.dart @@ -0,0 +1,554 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../../popups_v3/popup_v3.dart'; +import '../../popups_v3/popups_v3_api.dart'; +import '../../popups_v3/popups_v3_engine.dart'; +import 'popup_v3_design.dart'; +import 'popup_v3_elements.dart'; +import 'popup_v3_texts.dart'; +import 'popup_v3_view.dart'; + +/// Показ попапов v3 над приложением — записями в оверлее корневого навигатора, поверх +/// страниц. Окно и полный экран вместе с затемнением всегда выше баннеров: баннер, +/// показанный при открытом окне, ложится под его затемнение. Касания мимо баннера уходят +/// в приложение, если у него нет затемнения и `lockBackgroundScroll`. +/// +/// Окну нужен ещё и прозрачный маршрут диалога: он закрывает окно системным «назад» и +/// не пускает касания к страницам. Рисовать окно самим маршрутом нельзя: навигатор +/// держит чужие записи оверлея (баннеры) над записями маршрутов. +class PopupV3Host implements PopupsV3Presenter { + PopupV3Host({PopupV3Texts? texts, this.platform}) : _texts = texts; + + final PopupV3Texts? _texts; + + /// Платформа ссылок (`key_ios` / `key_android`); `null` — текущая. + final TargetPlatform? platform; + + /// Сколько ждать навигатор приложения на холодном старте. + static const Duration navigatorWait = Duration(seconds: 10); + + static const Duration _transition = Duration(milliseconds: 220); + + /// Записи открытых окон по оверлеям: баннер встаёт ниже них. + static final List<({OverlayState overlay, OverlayEntry entry})> _modals = + <({OverlayState overlay, OverlayEntry entry})>[]; + + @override + Future present( + PopupV3 popup, + Map variables, + PopupV3Actions actions, + ) async { + final design = PopupV3Design.parse( + popup.design, + layout: popup.layout, + types: popupV3ElementBuilders.keys.toSet(), + runtime: variables, + platform: platform, + ); + design.dropped.forEach( + (id, reason) => debugPrint( + 'PersonalizationPopupsV3: popup ${popup.id} element $id skipped — $reason', + ), + ); + if (design.isEmpty) { + debugPrint( + 'PersonalizationPopupsV3: popup ${popup.id} not shown — empty design', + ); + return null; + } + final navigator = await _navigator(); + if (navigator == null || !navigator.mounted) { + debugPrint( + 'PersonalizationPopupsV3: popup ${popup.id} not shown — the app has no navigator', + ); + return null; + } + final shown = PopupV3Shown._(actions); + final texts = _texts ?? PopupV3Texts.device; + Widget content(Widget child) => PopupV3Scope( + design: design, + actions: actions, + texts: texts, + onClose: shown.close, + onDismiss: shown.dismiss, + child: Material(type: MaterialType.transparency, child: child), + ); + final overlay = navigator.overlay; + if (overlay == null) return null; + if (popup.isModal) { + _presentModal(navigator, overlay, popup, design, shown, content); + } else { + _presentBanner(overlay, popup, design, shown, content); + } + return shown; + } + + void _presentModal( + NavigatorState navigator, + OverlayState overlay, + PopupV3 popup, + PopupV3Design design, + PopupV3Shown shown, + Widget Function(Widget child) content, + ) { + final fullscreen = popup.layout == PopupV3Layout.fullscreen; + final dim = design.frame.overlay; + final dimmed = !fullscreen && dim.enabled; + final layer = GlobalKey<_ModalLayerState>(); + late final OverlayEntry entry; + late final ({OverlayState overlay, OverlayEntry entry}) record; + var removed = false; + void remove() { + if (removed) return; + removed = true; + _modals.remove(record); + try { + entry.remove(); + } catch (_) { + // Оверлей ушёл вместе с навигатором. + } + shown._gone(); + } + + final route = _PopupV3Route( + barrierDismissible: false, + barrierColor: const Color(0x00000000), + transitionDuration: Duration.zero, + pageBuilder: (context, _, _) => const SizedBox.shrink(), + ); + entry = OverlayEntry( + builder: (context) => content( + _ModalLayer( + key: layer, + popup: popup, + design: design, + barrierColor: dimmed ? dim.color : const Color(0x00000000), + barrierLabel: + Localizations.of( + context, + MaterialLocalizations, + )?.modalBarrierDismissLabel ?? + 'Dismiss', + onBarrierTap: dimmed ? shown.close : null, + onRemoved: remove, + ), + ), + ); + record = (overlay: overlay, entry: entry); + // Ушёл маршрут («назад», закрытие, навигатор) — окно уезжает и убирается. + void hide() { + final state = layer.currentState; + if (state == null) { + remove(); + } else { + state.hide(); + } + } + + shown._remove = () { + final routeNavigator = route.navigator; + if (routeNavigator == null || !route.isActive) { + hide(); + } else if (route.isCurrent) { + routeNavigator.pop(); + } else { + routeNavigator.removeRoute(route); + } + }; + _modals.add(record); + overlay.insert(entry); + unawaited(navigator.push(route)); + unawaited(route.gone.then((_) => hide())); + } + + void _presentBanner( + OverlayState overlay, + PopupV3 popup, + PopupV3Design design, + PopupV3Shown shown, + Widget Function(Widget child) content, + ) { + late final OverlayEntry entry; + final layer = GlobalKey<_BannerLayerState>(); + var removed = false; + void remove() { + if (removed) return; + removed = true; + entry.remove(); + shown._gone(); + } + + entry = OverlayEntry( + builder: (context) => content( + _BannerLayer( + key: layer, + popup: popup, + design: design, + onClose: shown.close, + onRemoved: remove, + ), + ), + ); + shown._remove = () { + final state = layer.currentState; + if (state == null) { + remove(); + } else { + state.hide(); + } + }; + // Под открытым окном: его затемнение накрывает и баннер. + OverlayEntry? below; + for (final modal in _modals) { + if (identical(modal.overlay, overlay)) { + below = modal.entry; + break; + } + } + overlay.insert(entry, below: below); + } + + Future _navigator() async { + const poll = Duration(milliseconds: 100); + for (var waited = Duration.zero; waited < navigatorWait; waited += poll) { + final navigator = _rootNavigator(); + if (navigator != null) return navigator; + await Future.delayed(poll); + } + return _rootNavigator(); + } + + /// Корневой навигатор приложения — первый вниз по дереву. + 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; + } +} + +/// Показанный попап v3: закрытие пользователем шлёт `close`, [dismiss] — нет. +class PopupV3Shown implements PopupsV3Shown { + PopupV3Shown._(this._actions); + + final PopupV3Actions _actions; + final Completer _closed = Completer(); + VoidCallback? _remove; + bool _silent = false; + + @override + Future get closed => _closed.future; + + /// Закрыть пользователем: крестик, кнопка `close`, затемнение, «назад», свайп. + void close() => _remove?.call(); + + @override + void dismiss() { + _silent = true; + _remove?.call(); + } + + void _gone() { + if (_closed.isCompleted) return; + if (!_silent) _actions.event(PopupV3Event.close); + _closed.complete(); + } +} + +/// Прозрачный маршрут окна: системное «назад» и блокировка страниц под окном. [gone] — +/// маршрут ушёл по любой причине. +class _PopupV3Route extends RawDialogRoute { + _PopupV3Route({ + required super.pageBuilder, + super.barrierDismissible, + super.barrierColor, + super.transitionDuration, + }); + + 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(); + } +} + +/// Окно по центру (поля 16 сверху и снизу, над клавиатурой) или полный экран в +/// безопасной зоне (фон рамки — и под системными полосами). +class _ModalPage extends StatelessWidget { + const _ModalPage({required this.popup, required this.design}); + + final PopupV3 popup; + final PopupV3Design design; + + static const double _margin = 16; + + @override + Widget build(BuildContext context) { + final size = MediaQuery.sizeOf(context); + final safe = MediaQuery.paddingOf(context); + final keyboard = MediaQuery.viewInsetsOf(context).bottom; + final bottom = math.max(safe.bottom, keyboard); + if (popup.layout == PopupV3Layout.fullscreen) { + return ColoredBox( + color: design.frame.background, + child: Padding( + padding: EdgeInsets.fromLTRB(safe.left, safe.top, safe.right, bottom), + child: PopupV3FrameView( + design: design, + layout: popup.layout, + screen: size, + maxWidth: math.max(0, size.width - safe.horizontal), + maxHeight: math.max(0, size.height - safe.top - bottom), + ), + ), + ); + } + final top = safe.top + _margin; + final available = math.max(0.0, size.height - top - bottom - _margin); + return Padding( + padding: EdgeInsets.fromLTRB( + safe.left, + top, + safe.right, + bottom + _margin, + ), + child: Center( + child: PopupV3FrameView( + design: design, + layout: popup.layout, + screen: size, + maxWidth: math.max(0, size.width - safe.horizontal), + maxHeight: available, + ), + ), + ); + } +} + +/// Окно с затемнением: затемнение проявляется, окно — ещё и из 95 % масштаба; тап по +/// затемнению — [onBarrierTap] (без него затемнение только не пускает касания). +class _ModalLayer extends StatefulWidget { + const _ModalLayer({ + super.key, + required this.popup, + required this.design, + required this.barrierColor, + required this.barrierLabel, + required this.onBarrierTap, + required this.onRemoved, + }); + + final PopupV3 popup; + final PopupV3Design design; + final Color barrierColor; + final String barrierLabel; + final VoidCallback? onBarrierTap; + final VoidCallback onRemoved; + + @override + State<_ModalLayer> createState() => _ModalLayerState(); +} + +class _ModalLayerState extends State<_ModalLayer> + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: PopupV3Host._transition, + )..forward(); + late final Animation _curve = CurvedAnimation( + parent: _controller, + curve: Curves.easeOutCubic, + reverseCurve: Curves.easeInCubic, + ); + bool _hiding = false; + + /// Исчезнуть и убраться. + void hide() { + if (_hiding) return; + _hiding = true; + _controller.reverse().whenComplete(widget.onRemoved); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final fullscreen = widget.popup.layout == PopupV3Layout.fullscreen; + final page = _ModalPage(popup: widget.popup, design: widget.design); + return IgnorePointer( + ignoring: _hiding, + child: Stack( + children: [ + Positioned.fill( + child: Semantics( + label: widget.onBarrierTap == null ? null : widget.barrierLabel, + button: widget.onBarrierTap != null, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: widget.onBarrierTap, + child: FadeTransition( + opacity: _curve, + child: ColoredBox(color: widget.barrierColor), + ), + ), + ), + ), + Positioned.fill( + child: FadeTransition( + opacity: _curve, + child: fullscreen + ? page + : ScaleTransition( + scale: Tween(begin: 0.95, end: 1).animate(_curve), + child: page, + ), + ), + ), + ], + ), + ); + } +} + +/// Баннер сверху или снизу: отступы `offsetX/offsetY` от краёв безопасной зоны, поле 16 +/// с противоположной стороны. Въезжает от края, свайп к краю закрывает. Затемнение — +/// если включено (тап по нему закрывает); `lockBackgroundScroll` без затемнения — касания +/// мимо баннера не доходят до приложения. +class _BannerLayer extends StatefulWidget { + const _BannerLayer({ + super.key, + required this.popup, + required this.design, + required this.onClose, + required this.onRemoved, + }); + + final PopupV3 popup; + final PopupV3Design design; + final VoidCallback onClose; + final VoidCallback onRemoved; + + @override + State<_BannerLayer> createState() => _BannerLayerState(); +} + +class _BannerLayerState extends State<_BannerLayer> + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: PopupV3Host._transition, + )..forward(); + late final Animation _curve = CurvedAnimation( + parent: _controller, + curve: Curves.easeOutCubic, + reverseCurve: Curves.easeInCubic, + ); + bool _hiding = false; + + /// Уехать к краю и убраться. + void hide() { + if (_hiding) return; + _hiding = true; + _controller.reverse().whenComplete(widget.onRemoved); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + static const double _margin = 16; + + @override + Widget build(BuildContext context) { + final popup = widget.popup; + final frame = widget.design.frame; + final size = MediaQuery.sizeOf(context); + final safe = MediaQuery.paddingOf(context); + final keyboard = MediaQuery.viewInsetsOf(context).bottom; + final top = popup.placement == PopupV3Placement.top; + final bottomInset = math.max(safe.bottom, keyboard); + final edge = (top ? safe.top : bottomInset) + frame.offsetY; + final opposite = (top ? bottomInset : safe.top) + _margin; + final banner = PopupV3FrameView( + design: widget.design, + layout: popup.layout, + screen: size, + maxWidth: math.max(0, size.width - safe.horizontal - 2 * frame.offsetX), + maxHeight: math.max(0, size.height - edge - opposite), + ); + final overlay = frame.overlay; + return Stack( + children: [ + if (overlay.enabled) + Positioned.fill( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: widget.onClose, + child: FadeTransition( + opacity: _curve, + child: ColoredBox(color: overlay.color), + ), + ), + ) + else if (frame.lockBackground) + const Positioned.fill(child: AbsorbPointer()), + Positioned( + left: safe.left + frame.offsetX, + right: safe.right + frame.offsetX, + top: top ? edge : null, + bottom: top ? null : edge, + child: SlideTransition( + position: Tween( + begin: Offset(0, top ? -1 : 1), + end: Offset.zero, + ).animate(_curve), + child: FadeTransition( + opacity: _curve, + child: Align( + alignment: top ? Alignment.topCenter : Alignment.bottomCenter, + heightFactor: 1, + child: Dismissible( + key: ValueKey('popup-v3-banner-${popup.id}'), + direction: top ? DismissDirection.up : DismissDirection.down, + onDismissed: (_) { + _hiding = true; + widget.onRemoved(); + }, + child: banner, + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/src/ui/popups_v3/popup_v3_texts.dart b/lib/src/ui/popups_v3/popup_v3_texts.dart new file mode 100644 index 0000000..8c09d9a --- /dev/null +++ b/lib/src/ui/popups_v3/popup_v3_texts.dart @@ -0,0 +1,88 @@ +import 'dart:ui' show PlatformDispatcher; + +/// Тексты попапа v3 на случай пустого поля в дизайне: русские или английские по языку +/// устройства. На сайте их подставляет компилятор из локали ЛК (`popups.compiler.*`). +class PopupV3Texts { + const PopupV3Texts._({ + required this.close, + required this.detail, + required this.image, + required this.email, + required this.subscribe, + required this.emailConsent, + required this.emailError, + required this.formError, + required this.send, + required this.copy, + required this.copied, + required this.thanks, + required this.genderMale, + required this.genderFemale, + required this.sendError, + }); + + /// Подпись кнопки закрытия для скринридера. + final String close; + + /// Кнопка без текста. + final String detail; + + /// Подпись картинки без `imageAlt`. + final String image; + + /// Плейсхолдер поля email. + final String email; + final String subscribe; + final String emailConsent; + final String emailError; + final String formError; + final String send; + final String copy; + final String copied; + final String thanks; + final String genderMale; + final String genderFemale; + + /// Отправка формы или опроса не удалась (сеть, сервер). + final String sendError; + + static const PopupV3Texts ru = PopupV3Texts._( + close: 'Закрыть', + detail: 'Подробнее', + image: 'Изображение', + email: 'Email', + subscribe: 'Подписаться', + emailConsent: 'Я согласен(на) получать рассылку', + emailError: 'Введите корректный email и отметьте согласие', + formError: 'Заполните обязательные поля', + send: 'Отправить', + copy: 'Скопировать', + copied: 'Скопировано', + thanks: 'Спасибо!', + genderMale: 'Мужской', + genderFemale: 'Женский', + sendError: 'Не удалось отправить. Попробуйте ещё раз', + ); + + static const PopupV3Texts en = PopupV3Texts._( + close: 'Close', + detail: 'Learn more', + image: 'Image', + email: 'Email', + subscribe: 'Subscribe', + emailConsent: 'I agree to receive emails', + emailError: 'Enter a valid email and accept the terms', + formError: 'Fill in the required fields', + send: 'Send', + copy: 'Copy', + copied: 'Copied', + thanks: 'Thank you!', + genderMale: 'Male', + genderFemale: 'Female', + sendError: 'Could not send. Please try again', + ); + + /// По языку устройства: русский — для `ru`, остальные — английский. + static PopupV3Texts get device => + PlatformDispatcher.instance.locale.languageCode == 'ru' ? ru : en; +} diff --git a/lib/src/ui/popups_v3/popup_v3_view.dart b/lib/src/ui/popups_v3/popup_v3_view.dart new file mode 100644 index 0000000..363b5ca --- /dev/null +++ b/lib/src/ui/popups_v3/popup_v3_view.dart @@ -0,0 +1,357 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../../popups_v3/popup_v3.dart'; +import '../../popups_v3/popups_v3_api.dart'; +import '../../popups_v3/popups_v3_engine.dart'; +import '../personalization_theme.dart'; +import 'popup_markup.dart'; +import 'popup_v3_design.dart'; +import 'popup_v3_elements.dart'; +import 'popup_v3_grid.dart'; +import 'popup_v3_texts.dart'; + +/// Что элементам попапа нужно от показа: документ, действия, тексты, закрытие. +class PopupV3Scope extends InheritedWidget { + const PopupV3Scope({ + super.key, + required this.design, + required this.actions, + required this.texts, + required this.onClose, + required this.onDismiss, + required super.child, + }); + + final PopupV3Design design; + final PopupV3Actions actions; + final PopupV3Texts texts; + + /// Закрыть попап пользователем (крестик, кнопка `close`): событие `close`. + final VoidCallback onClose; + + /// Убрать попап без события (ссылку или товар забрал хост). + final VoidCallback onDismiss; + + PopupV3Variables get variables => design.variables; + + static PopupV3Scope of(BuildContext context) { + final scope = context.dependOnInheritedWidgetOfExactType(); + assert(scope != null, 'PopupV3Scope is missing above a popup v3 element'); + return scope!; + } + + /// Открыть ссылку элемента: событие `click`, затем ссылка ([followLink]). + void openLink(String url) { + actions.event(PopupV3Event.click); + followLink(url); + } + + /// Ссылка без события: открыл её хост — попап уходит без `close`, как после + /// перехода; ушла системе — остаётся. + void followLink(String url) { + if (actions.openLink(url)) onDismiss(); + } + + @override + bool updateShouldNotify(PopupV3Scope oldWidget) => + design != oldWidget.design || + actions != oldWidget.actions || + texts != oldWidget.texts; +} + +/// Фон попапа под элементом [element]: его фон, если он не прозрачный, иначе фон +/// рамки, иначе белый, как рамка по умолчанию; полупрозрачные — друг поверх друга. +Color popupV3BackgroundUnder(PopupV3Design design, PopupV3Element element) => + Color.alphaBlend( + element.box.background, + Color.alphaBlend(design.frame.background, const Color(0xffffffff)), + ); + +/// Компоненты кита в элементе [element] — в теме кита по фону попапа под ним +/// ([popupV3BackgroundUnder]), а не по теме системы: попап рисуется по цветам дизайна. +/// Окна поверх приложения (тост) — не часть рамки и остаются по теме приложения. +class PopupV3KitTheme extends StatelessWidget { + const PopupV3KitTheme({ + super.key, + required this.element, + required this.child, + }); + + final PopupV3Element element; + final Widget child; + + @override + Widget build(BuildContext context) => PersonalizationBrightness( + brightness: PersonalizationBrightness.on( + popupV3BackgroundUnder(PopupV3Scope.of(context).design, element), + ), + child: child, + ); +} + +/// Насыщенность шрифта по числу CSS (100–900). +FontWeight popupV3FontWeight(double value) { + final index = ((value / 100).round() - 1).clamp(0, 8); + return FontWeight.values[index]; +} + +/// Шрифт по `fontFamily` дизайна: моноширинный и с засечками — системные по ключевому +/// слову, остальное — шрифт приложения (шрифтов приложения по имени не ищем). +String? popupV3FontFamily(String? family) { + final name = family?.toLowerCase() ?? ''; + final ios = + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS; + if (name.contains('mono') || name.contains('courier')) { + return ios ? 'Menlo' : 'monospace'; + } + if (name.contains('serif') && !name.contains('sans')) { + return ios ? 'Georgia' : 'serif'; + } + return null; +} + +/// Стиль текста коробки [box]; поля можно перекрыть. +TextStyle popupV3TextStyle( + PopupV3Box box, { + double? fontSize, + double? fontWeight, + Color? color, + double? height, + double? letterSpacing, + String? fontFamily, +}) => TextStyle( + color: color ?? box.textColor, + fontSize: fontSize ?? box.fontSize, + fontWeight: popupV3FontWeight(fontWeight ?? box.fontWeight), + letterSpacing: letterSpacing ?? box.letterSpacing, + height: height ?? box.lineHeight, + fontFamily: fontFamily ?? popupV3FontFamily(box.fontFamily), + decoration: TextDecoration.none, +); + +/// Текст с разметкой и переменными. +class PopupV3RichText extends StatelessWidget { + const PopupV3RichText( + this.spans, { + super.key, + required this.style, + this.textAlign = TextAlign.left, + }); + + final List spans; + final TextStyle style; + final TextAlign textAlign; + + @override + Widget build(BuildContext context) => + Text.rich(popupMarkupTextSpan(spans, style), textAlign: textAlign); +} + +/// Попап целиком: рамка (фон, граница, радиус, поля) и сетка. Рамка не выше +/// [maxHeight]: если содержимое выше, оно прокручивается внутри неё, а рамка +/// остаётся на месте. +class PopupV3FrameView extends StatelessWidget { + const PopupV3FrameView({ + super.key, + required this.design, + required this.layout, + required this.screen, + required this.maxWidth, + required this.maxHeight, + }); + + final PopupV3Design design; + final PopupV3Layout layout; + + /// Размер экрана — для `%`, `vw`, `vh` и breakpoints. + final Size screen; + + /// Сколько места у рамки. + final double maxWidth; + final double maxHeight; + + @override + Widget build(BuildContext context) { + final frame = design.frame; + final metrics = frame.metrics(screen); + final fullscreen = layout == PopupV3Layout.fullscreen; + final width = fullscreen ? maxWidth : metrics.resolveWidth(maxWidth); + final minHeight = fullscreen + ? maxHeight + : math.min(metrics.minHeight, maxHeight); + final fixed = fullscreen + ? null + : metrics.height?.clamp(minHeight, maxHeight); + final radius = fullscreen ? 0.0 : metrics.radius; + final border = fullscreen ? 0.0 : frame.borderWidth; + return Container( + width: width, + constraints: BoxConstraints( + minHeight: fixed ?? minHeight, + maxHeight: fixed ?? maxHeight, + ), + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + color: frame.background, + borderRadius: BorderRadius.circular(radius), + border: border > 0 + ? Border.all(color: frame.borderColor, width: border) + : null, + ), + padding: EdgeInsets.all(metrics.padding), + child: SingleChildScrollView( + // Без перетаскивания, пока всё помещается: свайп баннера к краю закрывает его. + physics: const ClampingScrollPhysics(), + child: PopupV3Grid(design: design), + ), + ); + } +} + +/// Строки документа столбиком с промежутком 8. +class PopupV3Grid extends StatelessWidget { + const PopupV3Grid({super.key, required this.design}); + + final PopupV3Design design; + + @override + Widget build(BuildContext context) { + final rows = design.rows; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final (index, row) in rows.indexed) ...[ + if (index > 0) const SizedBox(height: 8), + PopupV3RowView(row: row), + ], + ], + ); + } +} + +/// Строка: фон цветом или картинкой и ячейки по долям. +class PopupV3RowView extends StatelessWidget { + const PopupV3RowView({super.key, required this.row}); + + final PopupV3Row row; + + @override + Widget build(BuildContext context) { + Widget child = PopupV3RowLayout( + fractions: row.fractions, + gap: row.gap, + minHeight: row.minHeight, + children: [ + for (final cell in row.cells) + PopupV3CellLayout( + gap: row.gap, + verticalAlign: cell.verticalAlign, + children: [ + for (final element in cell.elements) + PopupV3CellSlot( + key: ValueKey('popup-v3-${element.id}'), + align: element.stretch ? null : element.alignIn(cell.align), + verticalAlign: element.verticalAlign, + child: PopupV3ElementView(element: element), + ), + ], + ), + ], + ); + final image = row.backgroundImage; + if (row.background != null || image != null) { + child = DecoratedBox( + decoration: BoxDecoration( + color: row.background, + image: image == null + ? null + : DecorationImage( + image: NetworkImage(image), + fit: switch (row.backgroundSize) { + 'contain' => BoxFit.contain, + 'auto' => BoxFit.none, + _ => BoxFit.cover, + }, + alignment: switch (row.backgroundPosition) { + 'top' => Alignment.topCenter, + 'bottom' => Alignment.bottomCenter, + 'left' => Alignment.centerLeft, + 'right' => Alignment.centerRight, + _ => Alignment.center, + }, + repeat: switch (row.backgroundRepeat) { + 'repeat' => ImageRepeat.repeat, + 'repeat-x' => ImageRepeat.repeatX, + 'repeat-y' => ImageRepeat.repeatY, + _ => ImageRepeat.noRepeat, + }, + onError: (error, _) => + debugPrint('PersonalizationPopupsV3: row image — $error'), + ), + ), + child: child, + ); + } + return child; + } +} + +/// Элемент: содержимое по типу из реестра в «коробке» общих стилей; у `text`, `box` и +/// `image` — ссылка на всём элементе. +class PopupV3ElementView extends StatelessWidget { + const PopupV3ElementView({super.key, required this.element}); + + final PopupV3Element element; + + @override + Widget build(BuildContext context) { + final builder = popupV3ElementBuilders[element.type]; + if (builder == null) return const SizedBox.shrink(); + final content = builder(context, element); + if (content == null) return const SizedBox.shrink(); + final box = element.box; + final shadow = box.shadow; + Widget child = Container( + decoration: BoxDecoration( + color: box.background, + borderRadius: BorderRadius.circular(box.radius), + border: box.borderWidth > 0 + ? Border.all(color: box.borderColor, width: box.borderWidth) + : null, + boxShadow: shadow == null + ? null + : [ + BoxShadow( + color: shadow.color, + offset: Offset(0, shadow.y), + blurRadius: shadow.blur, + ), + ], + ), + padding: EdgeInsets.symmetric( + horizontal: box.paddingX, + vertical: box.paddingY, + ), + child: DefaultTextStyle.merge( + style: popupV3TextStyle(box), + child: content, + ), + ); + if (box.opacity < 1) child = Opacity(opacity: box.opacity, child: child); + final scope = PopupV3Scope.of(context); + final link = element.link(scope.variables); + if (link != null) { + child = GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => scope.openLink(link), + child: child, + ); + } + return child; + } +} diff --git a/lib/src/ui/widgets/personalization_category_screen.dart b/lib/src/ui/widgets/personalization_category_screen.dart new file mode 100644 index 0000000..0b539ff --- /dev/null +++ b/lib/src/ui/widgets/personalization_category_screen.dart @@ -0,0 +1,175 @@ +import 'package:flutter/widgets.dart'; + +import '../../category/category_params.dart'; +import '../../category/category_response.dart'; +import '../../personalization_sdk.dart'; +import '../components/personalization_product.dart'; +import 'personalization_results_screen_base.dart'; +import 'personalization_search_results_screen.dart'; +import 'product_mapping.dart'; + +/// Экран категории с данными SDK — сестра [PersonalizationSearchResultsScreen] на том же +/// ядре: заголовок с названием категории и числом товаров, плитка ⇄ список, фильтры и +/// их теги, сортировка, счётчик, «загрузить ещё» или бесконечная прокрутка, пустое +/// состояние, ошибка с повтором. Виджет сам ходит в `getCategory` и держит состояние. +/// +/// Источник — [categoryId]. Названия категории в ответе нет: заголовок задаёт хост через +/// [titleText], назад — [onBack]. Счётчик под заголовком — «N products» +/// ([foundPrefix] / [foundSuffix]). +/// +/// Инстанс SDK: [sdk] явно, иначе [shopId] или единственный зарегистрированный +/// (`REES46.getInstance`). +/// +/// Фасеты — как у поиска: бренды, диапазон цены и произвольные фасеты магазина +/// (`filters`) по тому же правилу [facets] / [maxFacets], с теми же подписями значений +/// ([facetValueTitle], `title` значений-объектов) и числами товаров. Цветов и размеров +/// (`industrial_filters`) у категории нет, их секций тоже. На iOS выпущенный нативный SDK +/// отдаёт из ответа категории только бренды. +/// +/// Цена и сортировка: API категории их понимает, а нативные SDK, против которых собран +/// плагин, пока нет. До их релиза секции цены и кнопки сортировки на экране нет, а +/// [sortBy] / [sortDir] уходят в запрос без эффекта. +/// +/// Трекинг: просмотр категории (`categoryView`) — один раз на категорию, а не на +/// страницы, фильтры, сортировку и повторы. Нажатие на карточку источник не ставит и +/// отдаёт товар через [onProductTap], кнопка карточки — через [onProductAction]. +/// +/// Ошибки — как у поиска: [onError], на первой странице [errorText] с кнопкой +/// [retryText], на следующей — повтор на месте «загрузить ещё». +class PersonalizationCategoryScreen + extends PersonalizationResultsScreenBase { + const PersonalizationCategoryScreen({ + super.key, + super.sdk, + super.shopId, + required this.categoryId, + super.titleText, + super.pageSize, + super.sortBy, + super.sortDir, + super.locations, + super.infiniteScroll, + super.showFilters, + super.showSort, + super.facets, + super.maxFacets, + super.productActionText, + super.showRating, + super.layout, + super.imageAspect, + super.onBack, + super.onSortTap, + super.onProductTap, + super.onProductAction, + super.onError, + super.foundPrefix = '', + super.foundSuffix = 'products', + super.countPrefix, + super.countSeparator, + super.loadMoreText, + super.emptyText = 'No products in this category yet.', + super.errorText, + super.retryText, + super.filtersTitle, + super.resetText, + super.applyText, + super.showMoreText, + super.showLessText, + super.priceTitle, + super.fromLabel, + super.toLabel, + super.brandsTitle, + super.colorsTitle, + super.sizesTitle, + super.facetTitle, + super.facetValueTitle, + super.showValueCounts, + super.iconBuilder, + }); + + /// Id категории (слаг, как в `getCategory`); смена перезапрашивает первую страницу. + final String categoryId; + + static const String defaultErrorText = + PersonalizationResultsScreenBase.defaultErrorText; + static const String defaultRetryText = + PersonalizationResultsScreenBase.defaultRetryText; + + @override + State createState() => + _PersonalizationCategoryScreenState(); +} + +class _PersonalizationCategoryScreenState + extends + PersonalizationResultsScreenState< + Product, + PersonalizationCategoryScreen + > { + /// Инстанс и категория, чей просмотр уже ушёл: просмотр — один на категорию. + (PersonalizationSdk, String)? _tracked; + + String get _id => widget.categoryId.trim(); + + @override + String get screenName => 'PersonalizationCategoryScreen'; + + @override + bool get hasSource => _id.isNotEmpty; + + @override + bool sourceChanged(PersonalizationCategoryScreen oldWidget) => + oldWidget.categoryId != widget.categoryId; + + @override + String get defaultTitle => ''; + + @override + bool get appliesPriceAndSort => categoryPriceAndSortApplied; + + @override + void onNewResults(PersonalizationSdk sdk) { + final key = (sdk, _id); + if (_tracked == key) return; + _tracked = key; + sdk.tracking.categoryView(_id).catchError((Object error) { + debugPrint('$screenName: category view not tracked — $error'); + }); + } + + @override + Future> fetch( + PersonalizationSdk sdk, + int page, + PersonalizationSearchApplied applied, + ) async { + final response = await sdk.getCategory( + _id, + limit: widget.pageSize, + page: page, + brands: applied.brandsParam, + locations: widget.locations, + filters: applied.facetsParam, + priceMin: applied.priceMinParam, + priceMax: applied.priceMaxParam, + sortBy: widget.sortBy, + sortDir: widget.sortDir, + ); + final range = response.priceRange; + return PersonalizationResultsPage( + products: response.products, + total: response.productsTotal, + priceRange: range == null ? null : (min: range.min, max: range.max), + brands: response.brands, + brandCounts: response.brandCounts, + filters: response.filters, + ); + } + + @override + PersonalizationProduct card(Product product) => + productFromCatalog(product, actionText: widget.productActionText); + + @override + String idOf(Product product) => product.id; +} diff --git a/lib/src/ui/widgets/personalization_instant_search_field.dart b/lib/src/ui/widgets/personalization_instant_search_field.dart index e6b7949..cfbebd9 100644 --- a/lib/src/ui/widgets/personalization_instant_search_field.dart +++ b/lib/src/ui/widgets/personalization_instant_search_field.dart @@ -8,6 +8,7 @@ import '../../search/search_params.dart'; import '../../search/search_response.dart'; import '../../tracking/tracking_models.dart'; import '../components/personalization_instant_search.dart'; +import 'product_mapping.dart'; import 'search_support.dart'; /// Мгновенный поиск с данными SDK: поле ввода, недавние запросы, подсказки, категории и @@ -309,7 +310,7 @@ class _PersonalizationInstantSearchFieldState for (final product in (source ?? const []).take( widget.productsLimit, )) { - final card = toCardProduct(product, null); + final card = productFromSearch(product); products.add( PersonalizationSuggestion( id: card.id, diff --git a/lib/src/ui/widgets/personalization_load_state.dart b/lib/src/ui/widgets/personalization_load_state.dart new file mode 100644 index 0000000..e392d11 --- /dev/null +++ b/lib/src/ui/widgets/personalization_load_state.dart @@ -0,0 +1,102 @@ +import 'package:flutter/foundation.dart'; + +/// Состояние загрузки данных виджета: запроса не было, грузится, есть данные, пусто или +/// ошибка. Внутреннее: не экспортируется из кита. +sealed class PersonalizationLoadState { + const PersonalizationLoadState(); +} + +/// Запроса ещё не было. +final class PersonalizationLoadIdle extends PersonalizationLoadState { + const PersonalizationLoadIdle(); +} + +/// Запрос в полёте. +final class PersonalizationLoadLoading extends PersonalizationLoadState { + const PersonalizationLoadLoading(); +} + +/// Данные пришли и в них есть что показать. +final class PersonalizationLoadContent extends PersonalizationLoadState { + const PersonalizationLoadContent(this.data); + + final T data; +} + +/// Ответ пришёл, но показать нечего. +final class PersonalizationLoadEmpty extends PersonalizationLoadState { + const PersonalizationLoadEmpty(); +} + +/// Запрос не удался; [retry] контроллера повторяет его. +final class PersonalizationLoadError extends PersonalizationLoadState { + const PersonalizationLoadError(this.error); + + final Object error; +} + +/// Загрузка с повтором: ведёт [PersonalizationLoadState] и помнит последний запрос, +/// чтобы его повторить. +/// +/// Пустота ответа — [isEmpty]; без него пусты пустые коллекции и словари, остальное — +/// данные. Ответ прошлого запроса, пришедший после нового (или после [reset] и +/// [dispose]), отбрасывается. После [dispose] [load], [retry] и [reset] ничего не делают. +class PersonalizationLoadController + extends ValueNotifier> { + PersonalizationLoadController({bool Function(T data)? isEmpty}) + : _isEmpty = isEmpty ?? _emptyCollection, + super(PersonalizationLoadIdle()); + + final bool Function(T data) _isEmpty; + Future Function()? _load; + int _seq = 0; + bool _disposed = false; + + /// Грузит [load]: [PersonalizationLoadLoading], затем данные, пусто или ошибка. + Future load(Future Function() load) { + if (_disposed) return Future.value(); + _load = load; + return _run(load); + } + + /// Повторяет последний запрос; если запроса не было — ничего не делает. + Future retry() { + final load = _load; + return load == null || _disposed ? Future.value() : _run(load); + } + + /// Назад к [PersonalizationLoadIdle] без запроса; ответ запроса в полёте отбросится. + void reset() { + if (_disposed) return; + _seq++; + _load = null; + value = PersonalizationLoadIdle(); + } + + Future _run(Future Function() load) async { + final seq = ++_seq; + value = PersonalizationLoadLoading(); + try { + final data = await load(); + if (_disposed || seq != _seq) return; + value = _isEmpty(data) + ? PersonalizationLoadEmpty() + : PersonalizationLoadContent(data); + } catch (error) { + if (_disposed || seq != _seq) return; + value = PersonalizationLoadError(error); + } + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } + + static bool _emptyCollection(Object? data) => switch (data) { + Iterable() => data.isEmpty, + Map() => data.isEmpty, + _ => false, + }; +} diff --git a/lib/src/ui/widgets/personalization_recommender_block.dart b/lib/src/ui/widgets/personalization_recommender_block.dart new file mode 100644 index 0000000..cad24a6 --- /dev/null +++ b/lib/src/ui/widgets/personalization_recommender_block.dart @@ -0,0 +1,455 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/widgets.dart'; + +import '../../collection/collection_response.dart'; +import '../../multi_instance/rees46.dart'; +import '../../personalization_sdk.dart'; +import '../../recommendation/recommendation_params.dart'; +import '../../recommendation/recommendation_response.dart'; +import '../../tracking/tracking_models.dart'; +import '../components/personalization_product.dart'; +import '../components/personalization_product_image.dart'; +import '../components/personalization_products_block.dart'; +import '../components/personalization_products_list.dart'; +import 'personalization_load_state.dart'; +import 'personalization_request_cache.dart'; +import 'product_mapping.dart'; + +/// Управление [PersonalizationRecommenderBlock] снаружи. +class PersonalizationRecommenderBlockController { + _PersonalizationRecommenderBlockState? _block; + + /// Загрузить блок заново — мимо кэша и мимо запроса в полёте. Показанный блок до + /// ответа остаётся на экране: новые товары его заменят, пустой ответ или ошибка + /// скроют. Завершается, когда ответ пришёл; блока в дереве нет — сразу. + Future reload() => _block?._start(force: true) ?? Future.value(); +} + +/// Блок рекомендаций с данными SDK: сам грузит товары и показывает их +/// [PersonalizationProductsBlock] — заголовок, карусель, плитка или список. +/// +/// Паттерн Recommender из Figma (Card — Recommender/Carousel 90:655, Recommender/Grid +/// 126:1944, Recommender/List 126:2551). Источник — ровно один: блок рекомендаций [code] +/// (`getRecommendation`; для «похожих» и «с этим покупают» — [itemId] и [categoryId], +/// ещё [locations]) или коллекция [collectionId] +/// ([PersonalizationRecommenderBlock.collection], `getCollection`). +/// +/// Инстанс SDK: [sdk] явно, иначе [shopId] или единственный зарегистрированный +/// (`REES46.getInstance`). +/// +/// Пока ответа нет, блока нет: он не занимает места и заглушек не рисует. Пришли +/// товары — блок проявляется за 150 мс. Товаров меньше [minProducts], ответ пуст или +/// запрос не удался — блок остаётся скрытым, ошибка уходит в [onError]. [onLoaded] после +/// каждого ответа получает число показанных товаров, у скрытого блока — 0. +/// +/// Ответы общие на процесс и живут в кэше 10 минут: второй блок с теми же параметрами +/// (лента пересоздала ячейку) показывает товары в первом же кадре, без запроса. +/// [PersonalizationRecommenderBlockController.reload] грузит мимо кэша. Смена источника, +/// его параметров, [sdk] или [shopId] — новая загрузка. +/// +/// Нажатие на товар блока [code] и на кнопку карточки (есть, если задан [actionText]) +/// запоминают источник `dynamic` с кодом блока (`tracking.setSource`), потом отдают +/// товар в [onProductTap] и [onProductAction]: «в корзину» прямо из блока — главный +/// случай атрибуции. У коллекции источник не ставится. +class PersonalizationRecommenderBlock extends StatefulWidget { + /// Блок рекомендаций [code]. + const PersonalizationRecommenderBlock({ + super.key, + required String this.code, + this.itemId, + this.categoryId, + this.locations, + this.sdk, + this.shopId, + this.controller, + this.layout = PersonalizationProductsLayout.carousel, + this.title, + this.limit, + this.minProducts = 1, + this.imageAspect = PersonalizationProductImageAspect.square, + this.actionText, + this.showAllText, + this.onShowAll, + this.showDots = false, + this.showRating = false, + this.onProductTap, + this.onProductAction, + this.onLoaded, + this.onError, + this.iconBuilder, + }) : collectionId = null, + assert(limit == null || limit > 0); + + /// Товары коллекции [collectionId]. Своего заголовка у коллекции нет: строка + /// заголовка — только если задан [title]. + const PersonalizationRecommenderBlock.collection({ + super.key, + required String this.collectionId, + this.sdk, + this.shopId, + this.controller, + this.layout = PersonalizationProductsLayout.carousel, + this.title, + this.limit, + this.minProducts = 1, + this.imageAspect = PersonalizationProductImageAspect.square, + this.actionText, + this.showAllText, + this.onShowAll, + this.showDots = false, + this.showRating = false, + this.onProductTap, + this.onProductAction, + this.onLoaded, + this.onError, + this.iconBuilder, + }) : code = null, + itemId = null, + categoryId = null, + locations = null, + assert(limit == null || limit > 0); + + /// Код блока рекомендаций; у коллекции — `null`. + final String? code; + + /// Товар, который сейчас смотрит пользователь, — для «похожих» и «с этим покупают». + final String? itemId; + + /// Категория, которую сейчас смотрит пользователь. + final String? categoryId; + + /// Список id локаций через запятую. + final String? locations; + + /// Id коллекции; у блока рекомендаций — `null`. + final String? collectionId; + + final PersonalizationSdk? sdk; + final String? shopId; + final PersonalizationRecommenderBlockController? controller; + final PersonalizationProductsLayout layout; + + /// Заголовок блока. `null` — из ответа (у коллекции — без заголовка), пустая строка — + /// без строки заголовка. + final String? title; + + /// Сколько товаров показать, не больше; `null` — все из ответа. + final int? limit; + + /// Сколько товаров нужно блоку: меньше — блок скрыт. Пустой блок не показывается и + /// при значении меньше 1. + final int minProducts; + + /// Пропорция картинок карточек, см. [PersonalizationProductsBlock.imageAspect]. + final PersonalizationProductImageAspect imageAspect; + + /// Подпись кнопки на карточке; `null` — без кнопки. + final String? actionText; + + /// Подпись кнопки «показать все» у карусели; `null` — без кнопки. + final String? showAllText; + final VoidCallback? onShowAll; + + /// У карусели точки под лентой; по умолчанию выключены. + final bool showDots; + + /// Рисовать ли рейтинг. В ответах API рейтинга нет, поэтому по умолчанию выключено. + final bool showRating; + + /// Нажатие на карточку: товар с [PersonalizationProduct.url] и + /// [PersonalizationProduct.deeplink] своей платформы. + final ValueChanged? onProductTap; + final ValueChanged? onProductAction; + + /// Ответ пришёл: сколько товаров показано, 0 — блок скрыт. + final ValueChanged? onLoaded; + final ValueChanged? onError; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + State createState() => + _PersonalizationRecommenderBlockState(); +} + +class _PersonalizationRecommenderBlockState + extends State + with SingleTickerProviderStateMixin { + /// Ответ — сырой ответ SDK: [RecommendationResponse] или [CollectionResponse]. + final PersonalizationLoadController _load = + PersonalizationLoadController(isEmpty: _noProducts); + late final AnimationController _fade = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 150), + ); + PersonalizationSdk? _sdk; + PersonalizationCacheSubscription? _subscription; + Completer? _pending; + + /// Что видно, пока грузится следующий ответ: свежий ответ из кэша у нового источника, + /// прежний — у [PersonalizationRecommenderBlockController.reload]. `null` — блока нет. + Object? _stale; + + /// Карточки ответа [_mappedFrom] с кнопкой [_mappedAction] — не собирать их в каждом + /// build. + Object? _mappedFrom; + String? _mappedAction; + List _cards = const []; + + @override + void initState() { + super.initState(); + widget.controller?._block = this; + _load.addListener(_changed); + _start(); + } + + @override + void didUpdateWidget(PersonalizationRecommenderBlock oldWidget) { + super.didUpdateWidget(oldWidget); + final previous = oldWidget.controller; + if (previous != widget.controller) { + if (previous?._block == this) previous?._block = null; + widget.controller?._block = this; + } + if (oldWidget.sdk != widget.sdk || + oldWidget.shopId != widget.shopId || + oldWidget.code != widget.code || + oldWidget.collectionId != widget.collectionId || + oldWidget.itemId != widget.itemId || + oldWidget.categoryId != widget.categoryId || + oldWidget.locations != widget.locations) { + _start(); + } + } + + @override + void dispose() { + if (widget.controller?._block == this) widget.controller?._block = null; + _cancel(); + _load + ..removeListener(_changed) + ..dispose(); + _fade.dispose(); + super.dispose(); + } + + /// Ответ на экране: пришедший или тот, что виден, пока грузится следующий. + Object? get _shown => switch (_load.value) { + PersonalizationLoadContent(:final data) => data, + PersonalizationLoadLoading() => _stale, + _ => null, + }; + + /// Резолвит инстанс и грузит блок. [force] — мимо кэша, прежний блок стоит на экране + /// до ответа; иначе — новый источник: виден сразу только свежий ответ из кэша. + Future _start({bool force = false}) { + final shown = _shown; + _cancel(); + final PersonalizationSdk sdk; + try { + sdk = widget.sdk ?? REES46.getInstance(widget.shopId); + } catch (error) { + debugPrint( + 'PersonalizationRecommenderBlock: cannot resolve an SDK for ' + 'shopId=${widget.shopId} — $error', + ); + _sdk = null; + _stale = null; + return _load.load(() => Future.error(error)); + } + _sdk = sdk; + final key = _key(sdk); + _stale = force ? shown : PersonalizationRequestCache.shared.peek(key); + // Видимое сразу не проявляется заново: проявление — только после пустоты. + _fade.value = _stale == null ? 0 : 1; + final load = _request(sdk); + return _load.load(() => _fetch(key, load, force: force)); + } + + String _key(PersonalizationSdk sdk) { + final code = widget.code; + if (code == null) { + return PersonalizationRequestCache.keyOf(sdk.shopId, 'collection', { + 'collection_id': widget.collectionId, + }); + } + return PersonalizationRequestCache.keyOf(sdk.shopId, 'recommend', { + 'code': code, + 'item_id': widget.itemId, + 'category_id': widget.categoryId, + 'locations': widget.locations, + }); + } + + /// Запрос в SDK по нынешним параметрам — собирается сразу, а не при вызове. + Future Function() _request(PersonalizationSdk sdk) { + final code = widget.code; + if (code == null) { + final collectionId = widget.collectionId!; + return () => sdk.getCollection(collectionId); + } + final params = RecommendationParams( + itemId: widget.itemId, + categoryId: widget.categoryId, + locations: widget.locations, + ); + return () => sdk.getRecommendation(code, params: params); + } + + Future _fetch( + String key, + Future Function() load, { + required bool force, + }) { + final answer = _pending = Completer(); + _subscription = PersonalizationRequestCache.shared.fetch( + key, + load, + onValue: answer.complete, + onError: answer.completeError, + force: force, + ); + return answer.future; + } + + /// Отписка от ответа в полёте. Его ожидание завершается ошибкой, которую контроллер + /// загрузки отбросит как устаревшую: иначе перебитый [_start] (и `reload()` хоста, + /// который его ждёт) не завершился бы никогда. + void _cancel() { + _subscription?.cancel(); + _subscription = null; + final pending = _pending; + _pending = null; + if (pending != null && !pending.isCompleted) { + pending.completeError(const _Superseded()); + } + } + + /// Ответ или ошибка пришли — колбэки хоста и проявление блока. Состояние приходит + /// асинхронно, не посреди сборки. + void _changed() { + switch (_load.value) { + case PersonalizationLoadContent(:final data): + _stale = null; + if (_fade.value == 0 && !_fade.isAnimating) _fade.forward(); + widget.onLoaded?.call(_visible(data).length); + case PersonalizationLoadEmpty(): + _stale = null; + _fade.value = 0; + widget.onLoaded?.call(0); + case PersonalizationLoadError(:final error): + _stale = null; + _fade.value = 0; + widget.onError?.call(error); + case PersonalizationLoadIdle() || + PersonalizationLoadLoading(): + break; + } + } + + static bool _noProducts(Object answer) => switch (answer) { + RecommendationResponse(:final products) => products.isEmpty, + CollectionResponse(:final products) => products.isEmpty, + _ => true, + }; + + /// Карточки, которые покажет блок: не больше [PersonalizationRecommenderBlock.limit]; + /// меньше [PersonalizationRecommenderBlock.minProducts] — ни одной. + List _visible(Object answer) { + final actionText = widget.actionText; + if (!identical(answer, _mappedFrom) || actionText != _mappedAction) { + _mappedFrom = answer; + _mappedAction = actionText; + _cards = switch (answer) { + RecommendationResponse(:final products) => [ + for (final product in products) + productFromRecommendation(product, actionText: actionText), + ], + CollectionResponse(:final products) => [ + for (final product in products) + productFromCatalog(product, actionText: actionText), + ], + _ => const [], + }; + } + final limit = widget.limit; + final cards = limit == null || _cards.length <= limit + ? _cards + : _cards.sublist(0, limit); + return cards.length < math.max(1, widget.minProducts) + ? const [] + : cards; + } + + /// Нажатие на карточку или её кнопку: сначала источник `dynamic` у блока [code], + /// потом колбэк хоста. + void _attributed( + PersonalizationProduct product, + ValueChanged? callback, + ) { + final code = widget.code; + final sdk = _sdk; + if (code != null && sdk != null) unawaited(_trackSource(sdk, code)); + callback?.call(product); + } + + /// Источник `dynamic` для следующих событий; сбой трекинга нажатию не мешает. + static Future _trackSource(PersonalizationSdk sdk, String code) async { + try { + await sdk.tracking.setSource( + TrackingSource(type: TrackingSourceType.dynamicBlock, code: code), + ); + } catch (error) { + debugPrint('PersonalizationRecommenderBlock: setSource failed — $error'); + } + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder>( + valueListenable: _load, + builder: (context, _, _) { + final answer = _shown; + if (answer == null) return const SizedBox.shrink(); + final cards = _visible(answer); + if (cards.isEmpty) return const SizedBox.shrink(); + return FadeTransition( + opacity: _fade, + child: PersonalizationProductsBlock( + layout: widget.layout, + title: + widget.title ?? + (answer is RecommendationResponse ? answer.title : null), + showAllText: widget.showAllText, + onShowAll: widget.onShowAll, + showDots: widget.showDots, + products: cards, + imageAspect: widget.imageAspect, + // Без колбэка хоста кнопка не нажимается — как у блока товаров. + onProductAction: widget.onProductAction == null + ? null + : (product) => _attributed(product, widget.onProductAction), + onProductTap: (product) => + _attributed(product, widget.onProductTap), + showRating: widget.showRating, + iconBuilder: widget.iconBuilder, + ), + ); + }, + ); + } +} + +/// Ожидание ответа перебито новой загрузкой или уходом блока из дерева. +class _Superseded implements Exception { + const _Superseded(); +} diff --git a/lib/src/ui/widgets/personalization_request_cache.dart b/lib/src/ui/widgets/personalization_request_cache.dart new file mode 100644 index 0000000..4fe5853 --- /dev/null +++ b/lib/src/ui/widgets/personalization_request_cache.dart @@ -0,0 +1,261 @@ +import 'dart:async'; +import 'dart:collection'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; + +/// Кэш ответов SDK для виджетов с данными — в памяти процесса. +/// +/// Ключ — магазин, вид запроса и его параметры ([keyOf]). Ответ живёт [ttl] (10 минут), +/// записей не больше [capacity] (32): сверх неё вытесняются самые старые. Ошибка не +/// кэшируется: следующий запрос уходит заново. +/// +/// Одинаковые запросы, пока первый в полёте, склеиваются в один, но не навсегда: запрос +/// старше [joinWindow] (30 секунд) новых ожидающих не принимает — следующий уходит в сеть +/// новым поколением. Ответ старого поколения достаётся только его ожидающим и в кэш не +/// ложится, если есть поколение новее или после его старта был [clear]. Отписка +/// последнего ожидающего снимает запрос из полёта. `force` («Повторить») идёт мимо +/// готового ответа и мимо запроса в полёте. +/// +/// Внутренний: не экспортируется из кита. Общий на процесс — [shared]; тесты и виджеты +/// со своим жизненным циклом создают свой. +class PersonalizationRequestCache { + PersonalizationRequestCache({ + this.ttl = const Duration(minutes: 10), + this.capacity = 32, + this.joinWindow = const Duration(seconds: 30), + Duration Function()? clock, + }) : assert(capacity > 0), + _now = clock ?? _monotonic(); + + /// Кэш, общий для всех виджетов процесса. + static final PersonalizationRequestCache shared = + PersonalizationRequestCache(); + + final Duration ttl; + final int capacity; + + /// Сколько запрос в полёте принимает новых ожидающих. + final Duration joinWindow; + + /// Монотонные часы: перевод системного времени не старит и не молодит ответы. + final Duration Function() _now; + + static Duration Function() _monotonic() { + final watch = Stopwatch()..start(); + return () => watch.elapsed; + } + + /// Порядок вставки — возраст записи: первая — самая старая. + final LinkedHashMap _entries = + LinkedHashMap(); + + /// Запрос в полёте, к которому присоединяются, — по ключу. + final Map _inFlight = {}; + + /// Поколение последнего начатого запроса — по ключу: только его ответ ложится в кэш. + final Map _newest = {}; + + /// Счётчик поколений и поколение на момент последнего [clear]. + int _generation = 0; + int _clearedAt = 0; + + /// Ключ запроса: магазин, вид запроса (`recommend`, `search` …) и параметры. + /// Параметры сортируются по имени, пустые (`null`) пропускаются — порядок, в котором + /// их собрал виджет, на ключ не влияет. Всё кодируется JSON, а не склеивается как есть: + /// значение с `&` или `=` не совпадёт с другим набором параметров. + static String keyOf( + String? shopId, + String kind, [ + Map params = const {}, + ]) { + final names = params.keys.where((name) => params[name] != null).toList() + ..sort(); + return jsonEncode([ + shopId, + kind, + [ + for (final name in names) [name, params[name]], + ], + ], toEncodable: (value) => value.toString()); + } + + /// Подписывает на ответ по [key]: свежий из кэша, ответ запроса того же ключа, который + /// уже в полёте, иначе — нового запроса [load]. Колбэки зовутся асинхронно и один раз; + /// после [PersonalizationCacheSubscription.cancel] — ни разу. + PersonalizationCacheSubscription fetch( + String key, + Future Function() load, { + required void Function(T value) onValue, + void Function(Object error)? onError, + bool force = false, + }) { + final waiter = _Waiter((value) => onValue(value as T), onError); + var entry = _entries[key]; + if (entry != null && _now() - entry.storedAt >= ttl) { + _entries.remove(key); + entry = null; + } + if (!force) { + if (entry != null) { + final value = entry.value; + scheduleMicrotask(() => _deliver(waiter, value)); + return PersonalizationCacheSubscription._(() => waiter.done = true); + } + final flight = _inFlight[key]; + if (flight != null && _now() - flight.startedAt < joinWindow) { + return _join(key, flight, waiter); + } + } + final flight = _Flight(++_generation, _now()); + _inFlight[key] = flight; + _newest[key] = flight.generation; + final subscription = _join(key, flight, waiter); + Future.sync(load).then( + (value) { + if (_finish(key, flight) && flight.generation > _clearedAt) { + _store(key, value); + } + for (final waiter in flight.takeWaiters()) { + _deliver(waiter, value); + } + }, + onError: (Object error) { + _finish(key, flight); + for (final waiter in flight.takeWaiters()) { + _fail(waiter, error); + } + }, + ); + return subscription; + } + + /// Свежий ответ по [key] прямо сейчас, без запроса и без подписки; нет его или он + /// устарел — `null`. Виджет, пересозданный лентой, рисует его в первом же кадре, а не + /// пустым до асинхронного ответа [fetch]. + Object? peek(String key) { + final entry = _entries[key]; + if (entry == null || _now() - entry.storedAt >= ttl) return null; + return entry.value; + } + + /// Сколько ответов лежит в кэше (вместе с устаревшими, ещё не вытесненными). + int get length => _entries.length; + + /// Забывает все ответы и запросы в полёте. Те доходят до своих ожидающих, но в кэш + /// уже не попадают. + void clear() { + _entries.clear(); + _inFlight.clear(); + _newest.clear(); + _clearedAt = _generation; + } + + PersonalizationCacheSubscription _join( + String key, + _Flight flight, + _Waiter waiter, + ) { + flight.waiters.add(waiter); + return PersonalizationCacheSubscription._(() { + if (waiter.done) return; + waiter.done = true; + flight.waiters.remove(waiter); + if (flight.waiters.isEmpty && identical(_inFlight[key], flight)) { + _inFlight.remove(key); + } + }); + } + + /// Запрос [flight] завершился: снимает его из полёта. `true` — он новейший по ключу, + /// и его ответ можно класть в кэш. + bool _finish(String key, _Flight flight) { + if (identical(_inFlight[key], flight)) _inFlight.remove(key); + if (_newest[key] != flight.generation) return false; + _newest.remove(key); + return true; + } + + void _store(String key, Object? value) { + // Обновлённая запись — снова самая новая. + _entries.remove(key); + _entries[key] = _Entry(value, _now()); + while (_entries.length > capacity) { + _entries.remove(_entries.keys.first); + } + } + + static void _deliver(_Waiter waiter, Object? value) { + if (waiter.done) return; + waiter.done = true; + _guard(() => waiter.onValue(value)); + } + + static void _fail(_Waiter waiter, Object error) { + if (waiter.done) return; + waiter.done = true; + final onError = waiter.onError; + if (onError != null) _guard(() => onError(error)); + } + + /// Колбэк одного ожидающего, бросивший исключение, не мешает остальным: исключение + /// уходит в [FlutterError.reportError]. + static void _guard(void Function() callback) { + try { + callback(); + } catch (error, stack) { + FlutterError.reportError( + FlutterErrorDetails( + exception: error, + stack: stack, + library: 'rees46_sdk', + context: ErrorDescription('while delivering a cached SDK answer'), + ), + ); + } + } +} + +/// Подписка на ответ [PersonalizationRequestCache.fetch]. +class PersonalizationCacheSubscription { + PersonalizationCacheSubscription._(this._cancel); + + final void Function() _cancel; + + /// Отписаться: колбэки больше не вызываются. Отписка последнего ожидающего снимает + /// запрос из полёта. + void cancel() => _cancel(); +} + +class _Entry { + const _Entry(this.value, this.storedAt); + + final Object? value; + final Duration storedAt; +} + +/// Один запрос в сеть и те, кто ждёт его ответа. +class _Flight { + _Flight(this.generation, this.startedAt); + + final int generation; + final Duration startedAt; + final List<_Waiter> waiters = <_Waiter>[]; + + /// Забирает ожидающих для раздачи ответа. + List<_Waiter> takeWaiters() { + final taken = List<_Waiter>.of(waiters); + waiters.clear(); + return taken; + } +} + +class _Waiter { + _Waiter(this.onValue, this.onError); + + final void Function(Object? value) onValue; + final void Function(Object error)? onError; + + /// Ответ отдан или ожидающий отписался. + bool done = false; +} diff --git a/lib/src/ui/widgets/personalization_results_screen_base.dart b/lib/src/ui/widgets/personalization_results_screen_base.dart new file mode 100644 index 0000000..2b6d260 --- /dev/null +++ b/lib/src/ui/widgets/personalization_results_screen_base.dart @@ -0,0 +1,913 @@ +import 'dart:convert'; + +import 'package:flutter/widgets.dart'; + +import '../../multi_instance/rees46.dart'; +import '../../personalization_sdk.dart'; +import '../../search/search_response.dart' show SearchFilter; +import '../components/personalization_catalog.dart'; +import '../components/personalization_filters.dart'; +import '../components/personalization_product.dart'; +import '../components/personalization_product_image.dart'; +import '../components/personalization_products_list.dart'; +import '../components/personalization_search_results_title.dart'; +import '../personalization_theme.dart'; + +/// Значения фильтров, ушедшие в запрос. +@immutable +class PersonalizationSearchApplied { + const PersonalizationSearchApplied({ + this.brands = const {}, + this.priceMin, + this.priceMax, + this.colors = const {}, + this.sizes = const {}, + this.facets = const >{}, + }); + + final Set brands; + final String? priceMin; + final String? priceMax; + final Set colors; + final Set sizes; + final Map> facets; + + bool get isEmpty => + brands.isEmpty && + (priceMin ?? '').isEmpty && + (priceMax ?? '').isEmpty && + colors.isEmpty && + sizes.isEmpty && + facets.values.every((values) => values.isEmpty); + + PersonalizationSearchApplied copyWith({ + Set? brands, + String? Function()? priceMin, + String? Function()? priceMax, + Set? colors, + Set? sizes, + Map>? facets, + }) => PersonalizationSearchApplied( + brands: brands ?? this.brands, + priceMin: priceMin == null ? this.priceMin : priceMin(), + priceMax: priceMax == null ? this.priceMax : priceMax(), + colors: colors ?? this.colors, + sizes: sizes ?? this.sizes, + facets: facets ?? this.facets, + ); +} + +/// Применённые фильтры параметрами запроса. Внутреннее: не экспортируется из кита. +extension PersonalizationAppliedParams on PersonalizationSearchApplied { + /// Бренды через запятую, `null` — не выбраны. + String? get brandsParam => brands.isEmpty ? null : brands.join(','); + + /// Границы цены числом; не число — без границы. + double? get priceMinParam => double.tryParse((priceMin ?? '').trim()); + double? get priceMaxParam => double.tryParse((priceMax ?? '').trim()); + + /// Отмеченные значения фасетов по имени, без фасетов, где ничего не отмечено. + Map> get facetsParam => >{ + for (final entry in facets.entries) + if (entry.value.isNotEmpty) entry.key: entry.value.toList(), + }; +} + +/// Страница выдачи в общем для экранов виде: ответ поиска или категории. Фасеты +/// читаются только из первой страницы. Внутреннее: не экспортируется из кита. +@immutable +class PersonalizationResultsPage

{ + const PersonalizationResultsPage({ + required this.products, + required this.total, + this.priceRange, + this.brands = const [], + this.brandCounts = const {}, + this.colors = const [], + this.colorCounts = const {}, + this.sizes = const [], + this.sizeCounts = const {}, + this.filters = const {}, + }); + + final List

products; + final int total; + + /// Границы цен в выдаче, `null` — сервер их не прислал. + final ({double min, double max})? priceRange; + final List brands; + + /// Число товаров по значению, где оно есть в ответе. + final Map brandCounts; + + /// Цвета и размеры (`industrial_filters`); у категории их нет. + final List colors; + final Map colorCounts; + final List sizes; + final Map sizeCounts; + + /// Произвольные фасеты магазина по имени. + final Map filters; +} + +/// Какие произвольные фасеты показать на экране фильтров и в каком порядке. +/// +/// Явный список [wanted] главнее: те его фасеты, что есть в ответе, в порядке хоста. +/// Без него — фасеты с более чем одним значением по убыванию `count` (сколько товаров +/// их имеют; при равенстве — по имени), первые [maxFacets]; `null` или 0 — все. +/// Приоритета у фасетов в ответе нет, а их бывают сотни. +/// +/// Фасет с отмеченными значениями ([checked]) виден всегда, иначе его не снять: не +/// попавшие в выборку идут следом в том же порядке. +List visibleFacets( + Map filters, { + Set? wanted, + int? maxFacets, + Set checked = const {}, +}) { + int byCount(String a, String b) { + final count = (filters[b]?.count ?? 0).compareTo(filters[a]?.count ?? 0); + return count != 0 ? count : a.compareTo(b); + } + + final List shown; + if (wanted != null) { + shown = [ + for (final name in wanted) + if (filters.containsKey(name)) name, + ]; + } else { + final ranked = [ + for (final entry in filters.entries) + if (entry.value.values.length > 1) entry.key, + ]..sort(byCount); + final limit = maxFacets ?? 0; + shown = limit > 0 && ranked.length > limit + ? ranked.sublist(0, limit) + : ranked; + } + final rest = [ + for (final name in checked) + if (!shown.contains(name)) name, + ]..sort(byCount); + return [...shown, ...rest]; +} + +/// Подпись значения-объекта: строка, которая после trim начинается с `{`, разбирается +/// как JSON-объект и несёт непустую строку `title`, подписывается этим `title`. Иначе — +/// `null`: значение показывается как есть. Только по формату — ни имён фасетов, ни языка. +String? jsonValueTitle(String value) { + final trimmed = value.trim(); + if (!trimmed.startsWith('{')) return null; + try { + final decoded = jsonDecode(trimmed); + final title = decoded is Map ? decoded['title'] : null; + if (title is String && title.trim().isNotEmpty) return title.trim(); + } on FormatException { + // Битый JSON — обычная строка. + } + return null; +} + +/// Подпись значения [value] фасета [facet] без числа товаров: подпись хоста ([custom]), +/// если она не пустая, иначе `title` значения-объекта ([jsonValueTitle]), иначе само +/// значение. В запрос всегда уходит исходное значение. +String facetValueLabel( + String facet, + String value, + String? Function(String facet, String value)? custom, +) { + final fromHost = custom?.call(facet, value); + if (fromHost != null && fromHost.trim().isNotEmpty) return fromHost; + return jsonValueTitle(value) ?? value; +} + +/// Общее ядро экранов выдачи кита — [PersonalizationSearchResultsScreen] и +/// [PersonalizationCategoryScreen]: инстанс SDK, страницы, «загрузить ещё» или +/// бесконечная прокрутка, фильтры с тегами, сортировка, пустое состояние, ошибка с +/// повтором и всё визуальное. Экраны отличаются источником выдачи, заголовком и +/// трекингом. Внутреннее: сам класс не экспортируется из кита, его поля видны через +/// экраны. +abstract class PersonalizationResultsScreenBase

extends StatefulWidget { + const PersonalizationResultsScreenBase({ + super.key, + this.sdk, + this.shopId, + this.titleText, + this.pageSize = 20, + this.sortBy, + this.sortDir, + this.locations, + this.infiniteScroll = false, + this.showFilters = true, + this.showSort = true, + this.facets, + this.maxFacets = 10, + this.productActionText, + this.showRating = false, + this.layout = PersonalizationProductsLayout.grid, + this.imageAspect = PersonalizationProductImageAspect.square, + this.onBack, + this.onSortTap, + this.onProductTap, + this.onProductAction, + this.onError, + required this.foundPrefix, + required this.foundSuffix, + this.countPrefix = 'Showing', + this.countSeparator = 'of', + this.loadMoreText = 'Load more', + required this.emptyText, + this.errorText = defaultErrorText, + this.retryText = defaultRetryText, + this.filtersTitle = 'Filters', + this.resetText = 'Reset', + this.applyText = 'Apply', + this.showMoreText = 'Show more', + this.showLessText = 'Show less', + this.priceTitle = 'Price', + this.fromLabel = 'From', + this.toLabel = 'to', + this.brandsTitle = 'Brand', + this.colorsTitle = 'Color', + this.sizesTitle = 'Size', + this.facetTitle, + this.facetValueTitle, + this.showValueCounts = true, + this.iconBuilder, + }); + + final PersonalizationSdk? sdk; + final String? shopId; + + /// Заголовок экрана; `null` — свой у каждого экрана. + final String? titleText; + final int pageSize; + + /// `popular`, `price`, `discount`, `sales_rate`, `date`; `null` — релевантность. + final String? sortBy; + + /// `asc` / `desc`. + final String? sortDir; + + /// Список id локаций через запятую. + final String? locations; + + /// Бесконечная прокрутка вместо кнопки «загрузить ещё». + final bool infiniteScroll; + final bool showFilters; + final bool showSort; + + /// Какие фасеты из `filters` показывать, в этом порядке; `null` — фасеты с более + /// чем одним значением, самые частые первыми, не больше [maxFacets]. + final Set? facets; + + /// Сколько фасетов показывать без явного [facets]; `null` или 0 — все. + final int? maxFacets; + + /// Подпись кнопки на карточке; `null` — без кнопки. + final String? productActionText; + + /// Рисовать ли рейтинг на карточках. В ответах API рейтинга нет, поэтому по + /// умолчанию выключено. + final bool showRating; + final PersonalizationProductsLayout layout; + final PersonalizationProductImageAspect imageAspect; + + final VoidCallback? onBack; + final VoidCallback? onSortTap; + final ValueChanged

? onProductTap; + final ValueChanged

? onProductAction; + final ValueChanged? onError; + + /// Счётчик в заголовке: «[foundPrefix] N [foundSuffix]»; пустой префикс не рисуется. + final String foundPrefix; + final String foundSuffix; + final String countPrefix; + final String countSeparator; + final String? loadMoreText; + final String? emptyText; + + /// Текст вместо выдачи, когда первая страница не загрузилась. `null` или пустая + /// строка — [defaultErrorText]: экран ошибки без текста не остаётся. + final String? errorText; + + /// Кнопка повтора под [errorText] и на месте «загрузить ещё», когда не загрузилась + /// следующая страница. `null` или пустая строка — [defaultRetryText]: без кнопки + /// после ошибки не восстановиться, бесконечная прокрутка ждёт её. + final String? retryText; + + static const String defaultErrorText = + 'Something went wrong. Check your connection and try again.'; + static const String defaultRetryText = 'Retry'; + final String filtersTitle; + final String? resetText; + final String? applyText; + final String? showMoreText; + final String? showLessText; + final String priceTitle; + final String fromLabel; + final String toLabel; + final String brandsTitle; + final String colorsTitle; + final String sizesTitle; + + /// Заголовок произвольного фасета по его имени в ответе; `null` или пустая строка — + /// заголовок кита по умолчанию (имя с пробелами вместо `_` и заглавной буквой). + final String? Function(String name)? facetTitle; + + /// Подпись значения произвольного фасета (`filters`) — на чекбоксе и в теге. `null` или + /// пустая строка — `title` значения-объекта (JSON с непустым `title`), иначе само + /// значение. В запрос уходит исходное значение. Брендов, цветов и размеров не касается. + final String? Function(String facet, String value)? facetValueTitle; + + /// Число товаров рядом со значением фильтра — «Значение (N)», где ответ его несёт. + /// В тегах применённых фильтров числа нет. + final bool showValueCounts; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; +} + +/// Состояние экрана выдачи: вся логика ядра. Экран задаёт источник ([fetch]), заголовок +/// по умолчанию, трекинг ([onNewResults], [productTapped]) и карточку товара. +abstract class PersonalizationResultsScreenState< + P, + W extends PersonalizationResultsScreenBase

+> + extends State { + static const String _sectionPrice = 'price'; + static const String _sectionBrands = 'brands'; + static const String _sectionColors = 'colors'; + static const String _sectionSizes = 'sizes'; + static const String _sectionFacet = 'facet:'; + + PersonalizationSdk? _sdk; + late PersonalizationProductsLayout _layout = widget.layout; + List

_products =

[]; + int _total = 0; + int _page = 0; + bool _loading = false; + + /// Первая страница текущего источника пришла: только тогда пустая выдача — «ничего + /// не найдено», а не загрузка, пустой источник или ошибка. + bool _answered = false; + + /// Следующая страница пришла пустой: выдача кончилась, что бы ни говорил `total`. + bool _ended = false; + + /// Страница, запрос которой упал, `null` — ошибки нет. Первая — экран ошибки, следующая — + /// повтор на месте «загрузить ещё»; пока она не повторена, лента дальше не грузится. + int? _failedPage; + PersonalizationResultsPage

? _facetSource; + PersonalizationSearchApplied _applied = const PersonalizationSearchApplied(); + + /// Секции открытого экрана фильтров, `null` — закрыт. Собираются на открытии и на новых + /// фасетах, а не в каждом build: новый список сбрасывает в [PersonalizationFilters] + /// несохранённые галочки и введённые цены. + List? _filterSections; + int _seq = 0; + final ScrollController _scroll = ScrollController(); + + // --- Что задаёт экран --------------------------------------------------------------------- + + /// Имя экрана в логе. + String get screenName; + + /// Источник выдачи задан (у поиска — непустая фраза); без него запросов нет. + bool get hasSource; + + /// Источник сменился — выдача с первой страницы. + bool sourceChanged(W oldWidget); + + /// Заголовок, когда [PersonalizationResultsScreenBase.titleText] не задан. + String get defaultTitle; + + /// Запрос применяет цену и сортировку; нет — секции цены и кнопки сортировки нет. + bool get appliesPriceAndSort => true; + + /// Страница [page] выдачи с фильтрами [applied]. + Future> fetch( + PersonalizationSdk sdk, + int page, + PersonalizationSearchApplied applied, + ); + + /// Новая выдача уходит в запрос: первая страница заново, не повтор и не следующая. + void onNewResults(PersonalizationSdk sdk) {} + + /// Нажатие на карточку; по умолчанию сразу уходит хосту. + void productTapped(P product) => widget.onProductTap?.call(product); + + PersonalizationProduct card(P product); + String idOf(P product); + + /// Инстанс SDK экрана, `null` — не нашёлся. + PersonalizationSdk? get sdk => _sdk; + + // --- Жизненный цикл и запросы ------------------------------------------------------------- + + @override + void initState() { + super.initState(); + _scroll.addListener(_onScroll); + _resolve(); + } + + @override + void didUpdateWidget(W oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.sdk != widget.sdk || oldWidget.shopId != widget.shopId) { + _resolve(); + } else if (sourceChanged(oldWidget) || + oldWidget.sortBy != widget.sortBy || + oldWidget.sortDir != widget.sortDir) { + _reload(); + } + } + + @override + void dispose() { + _scroll.dispose(); + super.dispose(); + } + + void _resolve() { + PersonalizationSdk? sdk = widget.sdk; + if (sdk == null) { + try { + sdk = REES46.getInstance(widget.shopId); + } catch (error) { + debugPrint( + '$screenName: cannot resolve an SDK for ' + 'shopId=${widget.shopId} — $error', + ); + widget.onError?.call(error); + } + } + _sdk = sdk; + _reload(); + } + + /// Первая страница заново. + void _reload() { + // Ответ запроса в полёте отбросится по _seq и флаг не снимет — снимаем здесь, иначе + // на пустом источнике лоадер крутится вечно, а loadMore заблокирован. + setState(() { + _products =

[]; + _total = 0; + _page = 0; + _loading = false; + _answered = false; + _ended = false; + _failedPage = null; + }); + _toTop(); + final sdk = _sdk; + if (sdk == null || !hasSource) { + _seq++; + return; + } + onNewResults(sdk); + _request(sdk, 1); + } + + /// Новая выдача — с начала ленты, а не с места, где пользователь бросил прошлую. + /// После кадра: перезапрос приходит и из didUpdateWidget, посреди сборки. + void _toTop() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _scroll.hasClients) _scroll.jumpTo(0); + }); + } + + /// Следующая страница, если она есть и запрос не в полёте. + void _loadMore() { + final sdk = _sdk; + if (sdk == null || + !hasSource || + _loading || + _ended || + _failedPage != null || + _products.length >= _total) { + return; + } + _request(sdk, _page + 1); + } + + /// Повтор упавшей страницы. + void _retry() { + final sdk = _sdk; + final page = _failedPage; + if (sdk == null || page == null || !hasSource || _loading) return; + setState(() => _failedPage = null); + _request(sdk, page); + } + + /// Бесконечная прокрутка: следующая страница — за полэкрана до конца ленты. Запрос в + /// полёте повторно не уходит, это держит [_loadMore]. + void _onScroll() { + if (!widget.infiniteScroll || !_scroll.hasClients) return; + final position = _scroll.position; + if (position.pixels >= + position.maxScrollExtent - position.viewportDimension / 2) { + _loadMore(); + } + } + + Future _request(PersonalizationSdk sdk, int nextPage) async { + final seq = ++_seq; + setState(() => _loading = true); + try { + final response = await fetch(sdk, nextPage, _applied); + if (!mounted || seq != _seq) return; + setState(() { + _loading = false; + _failedPage = null; + _page = nextPage; + _total = response.total; + _ended = response.products.isEmpty; + _products = nextPage == 1 + ? response.products + :

[..._products, ...response.products]; + if (nextPage == 1) { + _answered = true; + _facetSource = response; + // Фасеты сменились под открытым экраном фильтров — секции из нового ответа. + if (_filterSections != null) _filterSections = _buildSections(); + } + }); + } catch (error) { + if (!mounted || seq != _seq) return; + setState(() { + _loading = false; + _failedPage = nextPage; + }); + widget.onError?.call(error); + } + } + + void _apply(PersonalizationSearchApplied next) { + setState(() { + _applied = next; + _filterSections = null; + }); + _reload(); + } + + P? _find(String id) { + for (final product in _products) { + if (idOf(product) == id) return product; + } + return null; + } + + // --- Фасеты ⇄ секции экрана фильтров ------------------------------------------------------ + + String _facetTitle(String name) { + final custom = widget.facetTitle?.call(name); + if (custom != null && custom.isNotEmpty) return custom; + final spaced = name.replaceAll('_', ' '); + return spaced.isEmpty + ? spaced + : spaced[0].toUpperCase() + spaced.substring(1); + } + + /// Подпись значения произвольного фасета, см. [facetValueLabel]. + String _valueLabel(String facet, String value) => + facetValueLabel(facet, value, widget.facetValueTitle); + + /// Чекбоксы значений: id — исходное значение, подпись — [label] и число товаров из + /// [counts], если оно есть и [PersonalizationResultsScreenBase.showValueCounts]. + List _options( + Iterable values, + Set checked, { + String Function(String value)? label, + Map? counts, + }) { + final seen = {}; + return [ + for (final value in [...values, ...checked]) + if (seen.add(value)) + PersonalizationFilterOption( + id: value, + label: _counted(label?.call(value) ?? value, counts?[value]), + checked: checked.contains(value), + ), + ]; + } + + String _counted(String label, int? count) => + widget.showValueCounts && count != null ? '$label ($count)' : label; + + PersonalizationFilterOptions _optionsSection( + String id, + String title, + Iterable values, + Set checked, { + String Function(String value)? label, + Map? counts, + }) => PersonalizationFilterOptions( + id: id, + title: title, + options: _options(values, checked, label: label, counts: counts), + showMoreText: widget.showMoreText, + showLessText: widget.showLessText, + ); + + List _buildSections() { + final source = _facetSource; + final applied = _applied; + final sections = []; + if (appliesPriceAndSort && + (source?.priceRange != null || + applied.priceMin != null || + applied.priceMax != null)) { + // Границы диапазона — подсказками: в запрос уходит только то, что ввёл пользователь. + final range = source?.priceRange; + sections.add( + PersonalizationFilterRange( + id: _sectionPrice, + title: widget.priceTitle, + fromLabel: widget.fromLabel, + toLabel: widget.toLabel, + from: applied.priceMin, + to: applied.priceMax, + fromPlaceholder: range == null ? null : _bound(range.min), + toPlaceholder: range == null ? null : _bound(range.max), + ), + ); + } + void options( + String id, + String title, + List? values, + Map? counts, + Set checked, + ) { + final listed = values ?? const []; + if (listed.isEmpty && checked.isEmpty) return; + sections.add(_optionsSection(id, title, listed, checked, counts: counts)); + } + + options( + _sectionBrands, + widget.brandsTitle, + source?.brands, + source?.brandCounts, + applied.brands, + ); + options( + _sectionColors, + widget.colorsTitle, + source?.colors, + source?.colorCounts, + applied.colors, + ); + options( + _sectionSizes, + widget.sizesTitle, + source?.sizes, + source?.sizeCounts, + applied.sizes, + ); + final filters = source?.filters ?? const {}; + final names = visibleFacets( + filters, + wanted: widget.facets, + maxFacets: widget.maxFacets, + checked: { + for (final entry in applied.facets.entries) + if (entry.value.isNotEmpty) entry.key, + }, + ); + for (final name in names) { + final counts = filters[name]?.values ?? const {}; + String label(String value) => _valueLabel(name, value); + // По подписи, а не по исходному значению: у значений-объектов это JSON. + final values = counts.keys.toList() + ..sort((a, b) => label(a).compareTo(label(b))); + sections.add( + _optionsSection( + '$_sectionFacet$name', + _facetTitle(name), + values, + applied.facets[name] ?? const {}, + label: label, + counts: counts, + ), + ); + } + return sections; + } + + static String _orDefault(String? text, String fallback) => + (text ?? '').isEmpty ? fallback : text!; + + /// Граница цены без хвоста «.0»: сервер отдаёт число, форматированной строки у него нет. + static String _bound(double value) => value == value.floorToDouble() + ? value.toInt().toString() + : value.toString(); + + PersonalizationSearchApplied _fromSections( + List sections, + ) { + var next = const PersonalizationSearchApplied(); + final facets = >{}; + for (final section in sections) { + switch (section) { + case PersonalizationFilterRange(): + if (section.id != _sectionPrice) break; + String? clean(String? value) { + final trimmed = (value ?? '').trim(); + return trimmed.isEmpty ? null : trimmed; + } + next = next.copyWith( + priceMin: () => clean(section.from), + priceMax: () => clean(section.to), + ); + case PersonalizationFilterOptions(): + final checked = { + for (final option in section.options) + if (option.checked) option.id, + }; + if (section.id == _sectionBrands) { + next = next.copyWith(brands: checked); + } else if (section.id == _sectionColors) { + next = next.copyWith(colors: checked); + } else if (section.id == _sectionSizes) { + next = next.copyWith(sizes: checked); + } else if (section.id.startsWith(_sectionFacet)) { + facets[section.id.substring(_sectionFacet.length)] = checked; + } + } + } + return next.copyWith(facets: facets); + } + + List _appliedTags() { + final applied = _applied; + final tags = []; + void tag(String label, PersonalizationSearchApplied without) => tags.add( + PersonalizationSearchFilter( + label: label, + onRemove: () => _apply(without), + ), + ); + + for (final brand in applied.brands.toList()..sort()) { + tag(brand, applied.copyWith(brands: applied.brands.difference({brand}))); + } + final priceMin = (applied.priceMin ?? '').trim(); + final priceMax = (applied.priceMax ?? '').trim(); + if (priceMin.isNotEmpty || priceMax.isNotEmpty) { + final label = [priceMin, priceMax].where((v) => v.isNotEmpty).join(' – '); + tag( + '${widget.priceTitle} $label', + applied.copyWith(priceMin: () => null, priceMax: () => null), + ); + } + for (final color in applied.colors.toList()..sort()) { + tag(color, applied.copyWith(colors: applied.colors.difference({color}))); + } + for (final size in applied.sizes.toList()..sort()) { + tag(size, applied.copyWith(sizes: applied.sizes.difference({size}))); + } + for (final name in applied.facets.keys.toList()..sort()) { + String label(String value) => _valueLabel(name, value); + final values = applied.facets[name]!.toList() + ..sort((a, b) => label(a).compareTo(label(b))); + // Подпись — как на чекбоксе, но без числа товаров. + for (final value in values) { + tag( + label(value), + applied.copyWith( + facets: >{ + ...applied.facets, + name: applied.facets[name]!.difference({value}), + }, + ), + ); + } + } + return tags; + } + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + final hasMore = + _products.isNotEmpty && !_ended && _products.length < _total; + final firstPageFailed = _failedPage == 1; + final nextPageFailed = (_failedPage ?? 0) > 1; + final errorText = _orDefault( + widget.errorText, + PersonalizationResultsScreenBase.defaultErrorText, + ); + final retryText = _orDefault( + widget.retryText, + PersonalizationResultsScreenBase.defaultRetryText, + ); + + final header = PersonalizationSearchResultsTitle( + title: widget.titleText ?? defaultTitle, + selectedViewIndex: _layout == PersonalizationProductsLayout.grid ? 0 : 1, + onViewChanged: (index) => setState(() { + _layout = index == 0 + ? PersonalizationProductsLayout.grid + : PersonalizationProductsLayout.list; + }), + onBack: widget.onBack, + onFilters: () => setState(() => _filterSections = _buildSections()), + onSort: widget.onSortTap, + showFiltersButton: widget.showFilters, + showSortButton: widget.showSort && appliesPriceAndSort, + // Число — только когда первая страница нынешнего запроса ответила: «Найдено 0» на + // лоадере, после новых фильтров или сортировки и над ошибкой вводило бы в заблуждение. + // Кнопки фильтров и сортировки остаются на месте. + results: PersonalizationSearchResults( + prefix: widget.foundPrefix, + count: _answered ? _total : null, + suffix: widget.foundSuffix, + ), + filters: _appliedTags(), + iconBuilder: widget.iconBuilder, + ); + + final catalog = PersonalizationCatalog( + controller: _scroll, + // Поля экрана — поля ленты: карточки прокручиваются под ними. + padding: const EdgeInsets.all(16), + header: header, + layout: _layout, + products: [ + for (final product in _products) card(product), + ], + imageAspect: widget.imageAspect, + showRating: widget.showRating, + emptyText: firstPageFailed + ? errorText + : (_answered ? widget.emptyText : null), + emptyActionText: firstPageFailed ? retryText : null, + onEmptyAction: _retry, + loading: _loading, + count: _products.isEmpty + ? null + : PersonalizationCatalogCount( + prefix: widget.countPrefix, + shown: _products.length, + separator: widget.countSeparator, + total: _total, + ), + loadMoreText: nextPageFailed + ? retryText + : (hasMore && !widget.infiniteScroll ? widget.loadMoreText : null), + onLoadMore: nextPageFailed ? _retry : _loadMore, + onProductTap: (card) { + final product = _find(card.id); + if (product != null) productTapped(product); + }, + onProductAction: (card) { + final product = _find(card.id); + if (product != null) widget.onProductAction?.call(product); + }, + iconBuilder: widget.iconBuilder, + ); + + final filterSections = _filterSections; + return ColoredBox( + color: colors.backgroundGeneric, + child: Stack( + fit: StackFit.expand, + children: [ + // Каталог прокручивается сам, а не во внешнем скролле: там его лента + // раскладывалась бы целиком, и каждая догруженная страница оставалась бы + // построенной всеми карточками. + catalog, + if (filterSections != null) + ColoredBox( + color: colors.backgroundGeneric, + // Экран фильтров на всю высоту: заголовок и кнопки на месте, прокручиваются секции. + child: Padding( + padding: const EdgeInsets.all(16), + child: PersonalizationFilters( + title: widget.filtersTitle, + sections: filterSections, + resetText: widget.resetText, + applyText: widget.applyText, + onClose: () => setState(() => _filterSections = null), + onReset: () => _apply(const PersonalizationSearchApplied()), + onApply: (sections) => _apply(_fromSections(sections)), + iconBuilder: widget.iconBuilder, + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/src/ui/widgets/personalization_search_results_screen.dart b/lib/src/ui/widgets/personalization_search_results_screen.dart index 360bb58..01592fe 100644 --- a/lib/src/ui/widgets/personalization_search_results_screen.dart +++ b/lib/src/ui/widgets/personalization_search_results_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/widgets.dart'; -import '../../multi_instance/rees46.dart'; import '../../personalization_sdk.dart'; import '../../search/search_params.dart'; import '../../search/search_response.dart'; @@ -8,55 +7,12 @@ import '../../tracking/tracking_models.dart'; import '../components/personalization_catalog.dart'; import '../components/personalization_filters.dart'; import '../components/personalization_product.dart'; -import '../components/personalization_product_image.dart'; -import '../components/personalization_products_list.dart'; import '../components/personalization_search_results_title.dart'; -import '../personalization_theme.dart'; -import 'search_support.dart'; +import 'personalization_results_screen_base.dart'; +import 'product_mapping.dart'; -/// Значения фильтров, ушедшие в запрос. -@immutable -class PersonalizationSearchApplied { - const PersonalizationSearchApplied({ - this.brands = const {}, - this.priceMin, - this.priceMax, - this.colors = const {}, - this.sizes = const {}, - this.facets = const >{}, - }); - - final Set brands; - final String? priceMin; - final String? priceMax; - final Set colors; - final Set sizes; - final Map> facets; - - bool get isEmpty => - brands.isEmpty && - (priceMin ?? '').isEmpty && - (priceMax ?? '').isEmpty && - colors.isEmpty && - sizes.isEmpty && - facets.values.every((values) => values.isEmpty); - - PersonalizationSearchApplied copyWith({ - Set? brands, - String? Function()? priceMin, - String? Function()? priceMax, - Set? colors, - Set? sizes, - Map>? facets, - }) => PersonalizationSearchApplied( - brands: brands ?? this.brands, - priceMin: priceMin == null ? this.priceMin : priceMin(), - priceMax: priceMax == null ? this.priceMax : priceMax(), - colors: colors ?? this.colors, - sizes: sizes ?? this.sizes, - facets: facets ?? this.facets, - ); -} +export 'personalization_results_screen_base.dart' + show PersonalizationSearchApplied; /// Экран полной выдачи с данными SDK: заголовок с числом найденного, плитка ⇄ список, /// теги применённых фильтров, счётчик, «загрузить ещё» или бесконечная прокрутка, @@ -65,131 +21,88 @@ class PersonalizationSearchApplied { /// Паттерн SearchResultsScreen из Figma (страница 1:30), источник — `searchFull(query)`. /// Визуальный слой — [PersonalizationSearchResultsTitle] в заголовке /// [PersonalizationCatalog]; фильтры — [PersonalizationFilters] поверх выдачи внутри этого -/// же виджета, так что экран занимает весь отведённый ему экран хоста. +/// же виджета, так что экран занимает весь отведённый ему экран хоста. Ядро общее с +/// экраном категории (`PersonalizationCategoryScreen`). /// /// Инстанс SDK: [sdk] явно, иначе [shopId] или единственный зарегистрированный /// (`REES46.getInstance`). /// /// Фасеты строятся из ответа: диапазон цены (`price_range`), бренды, цвета и размеры -/// (`industrial_filters`) и произвольные фасеты магазина (`filters`), из которых -/// показываются только те, где больше одного значения. Применённые значения идут тегами в -/// заголовок и параметрами в следующий запрос. Заголовок произвольного фасета — его имя -/// через [facetTitle]. +/// (`industrial_filters`) и произвольные фасеты магазина (`filters`). Из произвольных +/// показываются те, где больше одного значения, самые частые (`count`) первыми и не +/// больше [maxFacets]; явный список [facets] главнее. Применённые значения идут тегами +/// в заголовок и параметрами в следующий запрос. Заголовок произвольного фасета — его +/// имя через [facetTitle]. Подпись значения — [facetValueTitle] хоста, иначе `title` +/// значения-объекта (JSON), иначе само значение; рядом число товаров из ответа +/// ([showValueCounts]), в тегах — без числа. /// /// Сортировки: кнопка в заголовке отдаёт [onSortTap] хосту (пикер в макете не нарисован), /// выбранное хост кладёт в [sortBy] / [sortDir]. Каждый новый запрос трекается событием /// `search`; нажатие на карточку запоминает источник `full_search` и отдаёт товар через /// [onProductTap], кнопка карточки — через [onProductAction]. -class PersonalizationSearchResultsScreen extends StatefulWidget { +/// +/// Ошибка запроса уходит в [onError] и видна на экране: не загрузилась первая страница — +/// вместо выдачи [errorText] и кнопка [retryText]; не загрузилась следующая — кнопка +/// «загрузить ещё» становится [retryText]. Повтор запрашивает ту же страницу. +class PersonalizationSearchResultsScreen + extends PersonalizationResultsScreenBase { const PersonalizationSearchResultsScreen({ super.key, - this.sdk, - this.shopId, + super.sdk, + super.shopId, required this.query, - this.titleText, - this.pageSize = 20, - this.sortBy, - this.sortDir, - this.locations, - this.infiniteScroll = false, - this.showFilters = true, - this.showSort = true, - this.facets, - this.productActionText, - this.layout = PersonalizationProductsLayout.grid, - this.imageAspect = PersonalizationProductImageAspect.square, - this.onBack, - this.onSortTap, - this.onProductTap, - this.onProductAction, - this.onError, - this.foundPrefix = 'Found', - this.foundSuffix = 'products', - this.countPrefix = 'Showing', - this.countSeparator = 'of', - this.loadMoreText = 'Load more', - this.emptyText = 'No results for your request.', - this.filtersTitle = 'Filters', - this.resetText = 'Reset', - this.applyText = 'Apply', - this.showMoreText = 'Show more', - this.showLessText = 'Show less', - this.priceTitle = 'Price', - this.fromLabel = 'From', - this.toLabel = 'to', - this.brandsTitle = 'Brand', - this.colorsTitle = 'Color', - this.sizesTitle = 'Size', - this.facetTitle, - this.iconBuilder, + super.titleText, + super.pageSize, + super.sortBy, + super.sortDir, + super.locations, + super.infiniteScroll, + super.showFilters, + super.showSort, + super.facets, + super.maxFacets, + super.productActionText, + super.showRating, + super.layout, + super.imageAspect, + super.onBack, + super.onSortTap, + super.onProductTap, + super.onProductAction, + super.onError, + super.foundPrefix = 'Found', + super.foundSuffix = 'products', + super.countPrefix, + super.countSeparator, + super.loadMoreText, + super.emptyText = 'No results for your request.', + super.errorText, + super.retryText, + super.filtersTitle, + super.resetText, + super.applyText, + super.showMoreText, + super.showLessText, + super.priceTitle, + super.fromLabel, + super.toLabel, + super.brandsTitle, + super.colorsTitle, + super.sizesTitle, + super.facetTitle, + super.facetValueTitle, + super.showValueCounts, + super.iconBuilder, }); - final PersonalizationSdk? sdk; - final String? shopId; - - /// Поисковая фраза; смена перезапрашивает первую страницу. + /// Поисковая фраза; смена перезапрашивает первую страницу. Она же заголовок, когда + /// [titleText] не задан. final String query; - /// Заголовок экрана; `null` — сама фраза. - final String? titleText; - final int pageSize; - - /// `popular`, `price`, `discount`, `sales_rate`, `date`; `null` — релевантность. - final String? sortBy; - - /// `asc` / `desc`. - final String? sortDir; - - /// Список id локаций через запятую. - final String? locations; - - /// Бесконечная прокрутка вместо кнопки «загрузить ещё». - final bool infiniteScroll; - final bool showFilters; - final bool showSort; - - /// Какие фасеты из `filters` показывать; `null` — все с более чем одним значением. - final Set? facets; - - /// Подпись кнопки на карточке; `null` — без кнопки. - final String? productActionText; - final PersonalizationProductsLayout layout; - final PersonalizationProductImageAspect imageAspect; - - final VoidCallback? onBack; - final VoidCallback? onSortTap; - final ValueChanged? onProductTap; - final ValueChanged? onProductAction; - final ValueChanged? onError; - - final String foundPrefix; - final String foundSuffix; - final String countPrefix; - final String countSeparator; - final String? loadMoreText; - final String? emptyText; - final String filtersTitle; - final String? resetText; - final String? applyText; - final String? showMoreText; - final String? showLessText; - final String priceTitle; - final String fromLabel; - final String toLabel; - final String brandsTitle; - final String colorsTitle; - final String sizesTitle; - - /// Заголовок произвольного фасета по его имени в ответе. - final String Function(String name)? facetTitle; - - final Widget Function( - BuildContext context, - String asset, - double size, - Color color, - )? - iconBuilder; + static const String defaultErrorText = + PersonalizationResultsScreenBase.defaultErrorText; + static const String defaultRetryText = + PersonalizationResultsScreenBase.defaultRetryText; @override State createState() => @@ -197,502 +110,84 @@ class PersonalizationSearchResultsScreen extends StatefulWidget { } class _PersonalizationSearchResultsScreenState - extends State { - static const String _sectionPrice = 'price'; - static const String _sectionBrands = 'brands'; - static const String _sectionColors = 'colors'; - static const String _sectionSizes = 'sizes'; - static const String _sectionFacet = 'facet:'; - - PersonalizationSdk? _sdk; - late PersonalizationProductsLayout _layout = widget.layout; - List _products = const []; - int _total = 0; - int _page = 0; - bool _loading = false; - - /// Первая страница текущей фразы пришла: только тогда пустая выдача — «ничего не найдено», - /// а не загрузка, пустая фраза или ошибка. - bool _answered = false; - SearchFullResponse? _facetSource; - PersonalizationSearchApplied _applied = const PersonalizationSearchApplied(); - - /// Секции открытого экрана фильтров, `null` — закрыт. Собираются на открытии и на новых - /// фасетах, а не в каждом build: новый список сбрасывает в [PersonalizationFilters] - /// несохранённые галочки и введённые цены. - List? _filterSections; - int _seq = 0; - final ScrollController _scroll = ScrollController(); + extends + PersonalizationResultsScreenState< + SearchProduct, + PersonalizationSearchResultsScreen + > { + String get _text => widget.query.trim(); @override - void initState() { - super.initState(); - _scroll.addListener(_onScroll); - _resolve(); - } + String get screenName => 'PersonalizationSearchResultsScreen'; @override - void didUpdateWidget(PersonalizationSearchResultsScreen oldWidget) { - super.didUpdateWidget(oldWidget); - if (oldWidget.sdk != widget.sdk || oldWidget.shopId != widget.shopId) { - _resolve(); - } else if (oldWidget.query != widget.query || - oldWidget.sortBy != widget.sortBy || - oldWidget.sortDir != widget.sortDir) { - _reload(); - } - } + bool get hasSource => _text.isNotEmpty; @override - void dispose() { - _scroll.dispose(); - super.dispose(); - } - - void _resolve() { - PersonalizationSdk? sdk = widget.sdk; - if (sdk == null) { - try { - sdk = REES46.getInstance(widget.shopId); - } catch (error) { - debugPrint( - 'PersonalizationSearchResultsScreen: cannot resolve an SDK for ' - 'shopId=${widget.shopId} — $error', - ); - widget.onError?.call(error); - } - } - _sdk = sdk; - _reload(); - } + bool sourceChanged(PersonalizationSearchResultsScreen oldWidget) => + oldWidget.query != widget.query; - String get _text => widget.query.trim(); + @override + String get defaultTitle => widget.query; - /// Первая страница заново. - void _reload() { - // Ответ запроса в полёте отбросится по _seq и флаг не снимет — снимаем здесь, иначе - // на пустой фразе лоадер крутится вечно, а loadMore заблокирован. - setState(() { - _products = const []; - _total = 0; - _page = 0; - _loading = false; - _answered = false; - }); - _toTop(); - final sdk = _sdk; - if (sdk == null || _text.isEmpty) { - _seq++; - return; - } + /// Каждая новая выдача — новый поиск: фраза, фильтры, сортировка. + @override + void onNewResults(PersonalizationSdk sdk) { sdk.tracking.search(_text); - _request(sdk, 1); } - /// Новая выдача — с начала ленты, а не с места, где пользователь бросил прошлую. - /// После кадра: перезапрос приходит и из didUpdateWidget, посреди сборки. - void _toTop() { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted && _scroll.hasClients) _scroll.jumpTo(0); - }); - } - - /// Следующая страница, если она есть и запрос не в полёте. - void _loadMore() { - final sdk = _sdk; - if (sdk == null || - _text.isEmpty || - _loading || - _products.length >= _total) { - return; - } - _request(sdk, _page + 1); - } - - /// Бесконечная прокрутка: следующая страница — за полэкрана до конца ленты. Запрос в - /// полёте повторно не уходит, это держит [_loadMore]. - void _onScroll() { - if (!widget.infiniteScroll || !_scroll.hasClients) return; - final position = _scroll.position; - if (position.pixels >= - position.maxScrollExtent - position.viewportDimension / 2) { - _loadMore(); - } - } - - Future _request(PersonalizationSdk sdk, int nextPage) async { - final seq = ++_seq; - setState(() => _loading = true); - final applied = _applied; - final params = SearchParams( - page: nextPage, - limit: widget.pageSize, - sortBy: widget.sortBy, - sortDir: widget.sortDir, - locations: widget.locations, - brands: applied.brands.isEmpty ? null : applied.brands.join(','), - priceMin: double.tryParse((applied.priceMin ?? '').trim()), - priceMax: double.tryParse((applied.priceMax ?? '').trim()), - colors: applied.colors.isEmpty ? null : applied.colors.toList(), - fashionSizes: applied.sizes.isEmpty ? null : applied.sizes.toList(), - filters: >{ - for (final entry in applied.facets.entries) - if (entry.value.isNotEmpty) entry.key: entry.value.toList(), - }, + @override + Future> fetch( + PersonalizationSdk sdk, + int page, + PersonalizationSearchApplied applied, + ) async { + final response = await sdk.searchFull( + _text, + params: SearchParams( + page: page, + limit: widget.pageSize, + sortBy: widget.sortBy, + sortDir: widget.sortDir, + locations: widget.locations, + brands: applied.brandsParam, + priceMin: applied.priceMinParam, + priceMax: applied.priceMaxParam, + colors: applied.colors.isEmpty ? null : applied.colors.toList(), + fashionSizes: applied.sizes.isEmpty ? null : applied.sizes.toList(), + filters: applied.facetsParam, + ), + ); + final range = response.priceRange; + final industrial = response.industrialFilters; + return PersonalizationResultsPage( + products: response.products, + total: response.productsTotal, + priceRange: range == null ? null : (min: range.min, max: range.max), + brands: response.brands, + brandCounts: response.brandCounts, + colors: industrial?.colors ?? const [], + colorCounts: industrial?.colorCounts ?? const {}, + sizes: industrial?.fashionSizes ?? const [], + sizeCounts: industrial?.fashionSizeCounts ?? const {}, + filters: response.filters, ); - try { - final response = await sdk.searchFull(_text, params: params); - if (!mounted || seq != _seq) return; - setState(() { - _loading = false; - _page = nextPage; - _total = response.productsTotal; - _products = nextPage == 1 - ? response.products - : [..._products, ...response.products]; - if (nextPage == 1) { - _answered = true; - _facetSource = response; - // Фасеты сменились под открытым экраном фильтров — секции из нового ответа. - if (_filterSections != null) _filterSections = _buildSections(); - } - }); - } catch (error) { - if (!mounted || seq != _seq) return; - setState(() => _loading = false); - widget.onError?.call(error); - } - } - - void _apply(PersonalizationSearchApplied next) { - setState(() { - _applied = next; - _filterSections = null; - }); - _reload(); } - void _productTapped(SearchProduct product) { + @override + void productTapped(SearchProduct product) { if (_text.isNotEmpty) { - _sdk?.tracking.setSource( + sdk?.tracking.setSource( TrackingSource(type: TrackingSourceType.fullSearch, code: _text), ); } - widget.onProductTap?.call(product); - } - - SearchProduct? _find(String id) { - for (final product in _products) { - if (product.id == id) return product; - } - return null; - } - - // --- Фасеты ⇄ секции экрана фильтров ------------------------------------------------------ - - String _facetTitle(String name) { - final custom = widget.facetTitle; - if (custom != null) return custom(name); - final spaced = name.replaceAll('_', ' '); - return spaced.isEmpty - ? spaced - : spaced[0].toUpperCase() + spaced.substring(1); - } - - List _options( - Iterable values, - Set checked, - ) { - final seen = {}; - return [ - for (final value in [...values, ...checked]) - if (seen.add(value)) - PersonalizationFilterOption( - id: value, - label: value, - checked: checked.contains(value), - ), - ]; - } - - List _buildSections() { - final source = _facetSource; - final applied = _applied; - final sections = []; - if (source?.priceRange != null || - applied.priceMin != null || - applied.priceMax != null) { - // Границы диапазона — подсказками: в запрос уходит только то, что ввёл пользователь. - final range = source?.priceRange; - sections.add( - PersonalizationFilterRange( - id: _sectionPrice, - title: widget.priceTitle, - fromLabel: widget.fromLabel, - toLabel: widget.toLabel, - from: applied.priceMin, - to: applied.priceMax, - fromPlaceholder: range == null ? null : _bound(range.min), - toPlaceholder: range == null ? null : _bound(range.max), - ), - ); - } - final brands = source?.brands ?? const []; - if (brands.isNotEmpty || applied.brands.isNotEmpty) { - sections.add( - PersonalizationFilterOptions( - id: _sectionBrands, - title: widget.brandsTitle, - options: _options(brands, applied.brands), - showMoreText: widget.showMoreText, - showLessText: widget.showLessText, - ), - ); - } - final colors = source?.industrialFilters?.colors ?? const []; - if (colors.isNotEmpty || applied.colors.isNotEmpty) { - sections.add( - PersonalizationFilterOptions( - id: _sectionColors, - title: widget.colorsTitle, - options: _options(colors, applied.colors), - showMoreText: widget.showMoreText, - showLessText: widget.showLessText, - ), - ); - } - final sizes = source?.industrialFilters?.fashionSizes ?? const []; - if (sizes.isNotEmpty || applied.sizes.isNotEmpty) { - sections.add( - PersonalizationFilterOptions( - id: _sectionSizes, - title: widget.sizesTitle, - options: _options(sizes, applied.sizes), - showMoreText: widget.showMoreText, - showLessText: widget.showLessText, - ), - ); - } - final wanted = widget.facets; - final filters = source?.filters ?? const {}; - for (final name in filters.keys.toList()..sort()) { - final values = filters[name]!.values.keys.toList()..sort(); - final checked = applied.facets[name] ?? const {}; - final visible = wanted == null - ? values.length > 1 - : wanted.contains(name); - if (!visible && checked.isEmpty) continue; - sections.add( - PersonalizationFilterOptions( - id: '$_sectionFacet$name', - title: _facetTitle(name), - options: _options(values, checked), - showMoreText: widget.showMoreText, - showLessText: widget.showLessText, - ), - ); - } - return sections; - } - - /// Граница цены без хвоста «.0»: сервер отдаёт число, форматированной строки у него нет. - static String _bound(double value) => value == value.floorToDouble() - ? value.toInt().toString() - : value.toString(); - - PersonalizationSearchApplied _fromSections( - List sections, - ) { - var next = const PersonalizationSearchApplied(); - final facets = >{}; - for (final section in sections) { - switch (section) { - case PersonalizationFilterRange(): - if (section.id != _sectionPrice) break; - String? clean(String? value) { - final trimmed = (value ?? '').trim(); - return trimmed.isEmpty ? null : trimmed; - } - next = next.copyWith( - priceMin: () => clean(section.from), - priceMax: () => clean(section.to), - ); - case PersonalizationFilterOptions(): - final checked = { - for (final option in section.options) - if (option.checked) option.id, - }; - if (section.id == _sectionBrands) { - next = next.copyWith(brands: checked); - } else if (section.id == _sectionColors) { - next = next.copyWith(colors: checked); - } else if (section.id == _sectionSizes) { - next = next.copyWith(sizes: checked); - } else if (section.id.startsWith(_sectionFacet)) { - facets[section.id.substring(_sectionFacet.length)] = checked; - } - } - } - return next.copyWith(facets: facets); - } - - List _appliedTags() { - final applied = _applied; - final tags = []; - for (final brand in applied.brands.toList()..sort()) { - tags.add( - PersonalizationSearchFilter( - label: brand, - onRemove: () => _apply( - applied.copyWith(brands: applied.brands.difference({brand})), - ), - ), - ); - } - final priceMin = (applied.priceMin ?? '').trim(); - final priceMax = (applied.priceMax ?? '').trim(); - if (priceMin.isNotEmpty || priceMax.isNotEmpty) { - final label = [priceMin, priceMax].where((v) => v.isNotEmpty).join(' – '); - tags.add( - PersonalizationSearchFilter( - label: '${widget.priceTitle} $label', - onRemove: () => _apply( - applied.copyWith(priceMin: () => null, priceMax: () => null), - ), - ), - ); - } - for (final color in applied.colors.toList()..sort()) { - tags.add( - PersonalizationSearchFilter( - label: color, - onRemove: () => _apply( - applied.copyWith(colors: applied.colors.difference({color})), - ), - ), - ); - } - for (final size in applied.sizes.toList()..sort()) { - tags.add( - PersonalizationSearchFilter( - label: size, - onRemove: () => - _apply(applied.copyWith(sizes: applied.sizes.difference({size}))), - ), - ); - } - for (final name in applied.facets.keys.toList()..sort()) { - for (final value in applied.facets[name]!.toList()..sort()) { - tags.add( - PersonalizationSearchFilter( - label: value, - onRemove: () => _apply( - applied.copyWith( - facets: >{ - ...applied.facets, - name: applied.facets[name]!.difference({value}), - }, - ), - ), - ), - ); - } - } - return tags; + super.productTapped(product); } @override - Widget build(BuildContext context) { - final colors = PersonalizationTheme.of(context).colors; - final hasMore = _products.isNotEmpty && _products.length < _total; - - final header = PersonalizationSearchResultsTitle( - title: widget.titleText ?? widget.query, - selectedViewIndex: _layout == PersonalizationProductsLayout.grid ? 0 : 1, - onViewChanged: (index) => setState(() { - _layout = index == 0 - ? PersonalizationProductsLayout.grid - : PersonalizationProductsLayout.list; - }), - onBack: widget.onBack, - onFilters: () => setState(() => _filterSections = _buildSections()), - onSort: widget.onSortTap, - showFiltersButton: widget.showFilters, - showSortButton: widget.showSort, - results: PersonalizationSearchResults( - prefix: widget.foundPrefix, - count: _total, - suffix: widget.foundSuffix, - ), - filters: _appliedTags(), - iconBuilder: widget.iconBuilder, - ); + PersonalizationProduct card(SearchProduct product) => + productFromSearch(product, actionText: widget.productActionText); - final catalog = PersonalizationCatalog( - controller: _scroll, - // Поля экрана — поля ленты: карточки прокручиваются под ними. - padding: const EdgeInsets.all(16), - header: header, - layout: _layout, - products: [ - for (final product in _products) - toCardProduct(product, widget.productActionText), - ], - imageAspect: widget.imageAspect, - emptyText: _answered ? widget.emptyText : null, - loading: _loading, - count: _products.isEmpty - ? null - : PersonalizationCatalogCount( - prefix: widget.countPrefix, - shown: _products.length, - separator: widget.countSeparator, - total: _total, - ), - loadMoreText: hasMore && !widget.infiniteScroll - ? widget.loadMoreText - : null, - onLoadMore: _loadMore, - onProductTap: (card) { - final product = _find(card.id); - if (product != null) _productTapped(product); - }, - onProductAction: (card) { - final product = _find(card.id); - if (product != null) widget.onProductAction?.call(product); - }, - iconBuilder: widget.iconBuilder, - ); - - final filterSections = _filterSections; - return ColoredBox( - color: colors.backgroundGeneric, - child: Stack( - fit: StackFit.expand, - children: [ - // Каталог прокручивается сам, а не во внешнем скролле: там его лента - // раскладывалась бы целиком, и каждая догруженная страница оставалась бы - // построенной всеми карточками. - catalog, - if (filterSections != null) - ColoredBox( - color: colors.backgroundGeneric, - child: SingleChildScrollView( - padding: const EdgeInsets.all(16), - child: PersonalizationFilters( - title: widget.filtersTitle, - sections: filterSections, - resetText: widget.resetText, - applyText: widget.applyText, - onClose: () => setState(() => _filterSections = null), - onReset: () => _apply(const PersonalizationSearchApplied()), - onApply: (sections) => _apply(_fromSections(sections)), - iconBuilder: widget.iconBuilder, - ), - ), - ), - ], - ), - ); - } + @override + String idOf(SearchProduct product) => product.id; } diff --git a/lib/src/ui/widgets/personalization_stories.dart b/lib/src/ui/widgets/personalization_stories.dart index b853e1f..286ec20 100644 --- a/lib/src/ui/widgets/personalization_stories.dart +++ b/lib/src/ui/widgets/personalization_stories.dart @@ -8,9 +8,16 @@ import '../../personalization_sdk.dart'; import '../../stories/stories_response.dart'; import '../components/personalization_stories_bar.dart'; import 'personalization_story_viewer.dart'; +import 'stories_api_v3.dart'; import 'stories_playback.dart'; +import 'stories_poll.dart'; +import 'stories_polls_api.dart'; import 'stories_seen_store.dart'; +import 'stories_share.dart'; import 'stories_support.dart'; +import 'stories_v3_scope.dart'; + +part 'personalization_stories_v3.dart'; /// Программное управление блоком сторис: открыть сторис, пауза, продолжение, перезагрузка. /// @@ -280,11 +287,13 @@ class PersonalizationStories extends StatefulWidget { imageProvider: imageProvider, iconBuilder: iconBuilder, ); + // Режим v3 — как у блока: от PersonalizationStoriesV3 над контекстом. + final v3 = StoriesV3Scope.peek(context); final PersonalizationSdk resolved; final List stories; try { resolved = await _resolve(sdk, shopId); - stories = await _fetch(resolved, code); + stories = await _fetch(resolved, code, apiV3Domain: v3?.apiV3Domain); if (stories.isEmpty) { throw StateError('stories block "$code" has no stories'); } @@ -298,6 +307,7 @@ class PersonalizationStories extends StatefulWidget { await _present( context, config: config, + v3: v3, sdk: resolved, stories: stories, index: index < 0 ? 0 : index, @@ -309,22 +319,126 @@ class PersonalizationStories extends StatefulWidget { State createState() => _PersonalizationStoriesState(); } -/// Открыть просмотр [stories] со сторис [index] поверх корневого навигатора; тексты и -/// колбэки — из [config]. Пока просмотр открыт, [controller] ставит его на паузу и -/// листает. Завершается, когда просмотр закроют. +/// Ссылки [PersonalizationStoriesV3.handleLink], которые грузятся (`null`) или открыты +/// (маршрут просмотра): повтор той же ссылки в это время ничего не делает. +final Map?> _openLinks = ?>{}; + +/// Ссылка [key] грузится или её просмотр открыт. Маршрут, который ушёл без закрытия +/// (навигатор убран вместе с ним), ссылку не держит. +bool _linkBusy(String key) { + if (!_openLinks.containsKey(key)) return false; + final route = _openLinks[key]; + return route == null || route.isActive; +} + +/// Открытый просмотр V2 — виджета, `show` или ссылки; `null` — нет. +Route? _openViewer; + +/// Закрыть открытый просмотр V2, если он есть: сверху — обычным закрытием, под другим +/// экраном — сразу. +void _closeOpenViewer() { + final route = _openViewer; + _openViewer = null; + final navigator = route?.navigator; + if (route == null || navigator == null || !route.isActive) return; + if (route.isCurrent) { + navigator.pop(); + } else { + navigator.removeRoute(route); + } +} + +// Загрузить кампанию ссылки [link] с хоста API v3 режима [v3] и открыть её вместо +// открытого просмотра V2. Завершается, когда просмотр закроют или загрузка не удалась. +Future _openLink( + BuildContext context, + StoriesShareLink link, { + required PersonalizationStories config, + required StoriesV3Options v3, + PersonalizationSdk? sdk, + String? shopId, + PersonalizationStoriesController? controller, + ValueChanged? onError, +}) async { + final PersonalizationSdk resolved; + final List stories; + try { + resolved = await _resolve(sdk, shopId); + stories = await _fetch( + resolved, + link.code, + link: link, + apiV3Domain: v3.apiV3Domain, + ); + if (stories.isEmpty) { + throw StateError('stories link ${link.key} has no stories'); + } + } catch (error) { + debugPrint('PersonalizationStoriesV3.handleLink: ${link.key} — $error'); + onError?.call(error); + return; + } + if (!context.mounted) return; + final story = stories.first; + // Слайд ссылки, если он есть в ответе: `start_position` сервер ставит только по своим + // слайдам, виртуальные слайды товарных кампаний (`39_2`) он не знает. + final linked = link.slideId == null + ? -1 + : story.slides.indexWhere((slide) => slide.id == link.slideId); + final start = linked >= 0 + ? linked + : story.startPosition.clamp(0, story.slides.length - 1); + var opened = false; + _closeOpenViewer(); + await _present( + context, + config: config, + v3: v3, + sdk: resolved, + stories: stories, + index: 0, + initialSlide: start, + controller: controller, + onRoute: (route) => _openLinks[link.key] = route, + onSlideShown: (_, _) { + // `shared_open` — один раз, после показа: кампания и слайд, с которого начали. + if (opened) return; + opened = true; + unawaited( + StoriesApiV3.track( + resolved, + v3.apiV3Domain!, + code: link.code, + event: StoriesV3Event.sharedOpen, + storyId: story.id, + slideId: story.slides[start].id, + ), + ); + }, + ); +} + +// Открыть просмотр [stories] со сторис [index] поверх корневого навигатора; тексты и +// колбэки — из [config], режим API v3 — из [v3] (`null` — его нет). Пока просмотр +// открыт, [controller] ставит его на паузу и листает. Завершается, когда просмотр +// закроют. Future _present( BuildContext context, { required PersonalizationStories config, + required StoriesV3Options? v3, required PersonalizationSdk? sdk, required List stories, required int index, + int? initialSlide, PersonalizationStoriesController? controller, void Function(Story story, int slideIndex)? onSlideShown, + ValueChanged>? onRoute, }) async { final session = controller?._begin(stories); - final viewer = PersonalizationStoryViewer( + Widget viewer = PersonalizationStoryViewer( stories: stories, initialStory: index, + initialSlide: initialSlide, seen: sdk == null ? const >{} : StoriesSeenStore.instance.seen(sdk), @@ -348,18 +462,27 @@ Future _present( imageProvider: config.imageProvider, iconBuilder: config.iconBuilder, ); + if (v3 != null) { + // Режим v3 едет с просмотром: тот открывается вне поддерева хоста. Опросы только с + // API v3: в старой ленте их нет, свой транспорт их не включает. + viewer = StoriesV3Scope( + options: StoriesApiV3.host(v3.apiV3Domain) == null + ? v3.withoutPollsTransport() + : v3, + child: viewer, + ); + } final navigator = Navigator.of(context, rootNavigator: true); + // Тема едет с просмотром: хост мог задать её поддереву, а не приложению. + final route = PersonalizationStoryViewer.route( + InheritedTheme.capture(from: context, to: navigator.context).wrap(viewer), + ); + _openViewer = route; + onRoute?.call(route); try { - // Тема едет с просмотром: хост мог задать её поддереву, а не приложению. - await navigator.push( - PersonalizationStoryViewer.route( - InheritedTheme.capture( - from: context, - to: navigator.context, - ).wrap(viewer), - ), - ); + await navigator.push(route); } finally { + if (_openViewer == route) _openViewer = null; if (session != null) controller?._end(session); } } @@ -388,15 +511,32 @@ Future _resolve( } } -/// Блок [code] со сторис, у которых есть слайды, и просмотренное магазина — не дольше -/// [PersonalizationStories.loadTimeout]. -Future> _fetch(PersonalizationSdk sdk, String code) async { +// Блок [code] со сторис, у которых есть слайды, и просмотренное магазина — не дольше +// [PersonalizationStories.loadTimeout]. С хостом API v3 ([apiV3Domain], без него — +// глобальный) — лента v3, а с [link] — кампания ссылки; без хоста — лента через мост. +Future> _fetch( + PersonalizationSdk sdk, + String code, { + StoriesShareLink? link, + String? apiV3Domain, +}) async { if (code.isEmpty) { throw ArgumentError.value(code, 'code', 'must be non-empty'); } + final host = StoriesApiV3.host(apiV3Domain); + final Future request; + if (host != null && link != null) { + request = StoriesApiV3.story(sdk, host, link); + } else if (link != null) { + throw StateError('stories links need API v3'); + } else if (host != null) { + request = StoriesApiV3.feed(sdk, host, code); + } else { + request = sdk.getStories(code); + } // Просмотренное читается вместе с блоком; ошибка блока приходит как есть. final results = await Future.wait(>[ - sdk.getStories(code), + request, StoriesSeenStore.instance.load(sdk), ]).timeout(PersonalizationStories.loadTimeout); final block = results.first as StoriesBlock; @@ -410,11 +550,26 @@ class _PersonalizationStoriesState extends State { int _seq = 0; bool _presenting = false; + // Режим API v3 от PersonalizationStoriesV3 над блоком; `null` — его нет. + StoriesV3Options? _v3; + bool _loaded = false; + @override void initState() { super.initState(); widget.controller?._bar = this; - _load(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // Первая загрузка — здесь, а не в initState: ей нужен режим над блоком. Сменился его + // хост — блок грузится заново; прочее (тексты, транспорт) берёт следующий просмотр. + final v3 = StoriesV3Scope.of(context); + final reload = !_loaded || v3?.apiV3Domain != _v3?.apiV3Domain; + _v3 = v3; + _loaded = true; + if (reload) _load(); } @override @@ -457,7 +612,11 @@ class _PersonalizationStoriesState extends State { widget.shopId, alive: () => mounted && seq == _seq, ); - final stories = await _fetch(sdk, widget.code); + final stories = await _fetch( + sdk, + widget.code, + apiV3Domain: _v3?.apiV3Domain, + ); if (!mounted || seq != _seq) return; setState(() { _sdk = sdk; @@ -496,6 +655,7 @@ class _PersonalizationStoriesState extends State { await _present( context, config: widget, + v3: _v3, sdk: sdk, stories: _stories, index: index, diff --git a/lib/src/ui/widgets/personalization_stories_v3.dart b/lib/src/ui/widgets/personalization_stories_v3.dart new file mode 100644 index 0000000..f57b9ae --- /dev/null +++ b/lib/src/ui/widgets/personalization_stories_v3.dart @@ -0,0 +1,194 @@ +part of 'personalization_stories.dart'; + +/// Сторис V2 поверх API v3 для поддерева: блоки [PersonalizationStories] под ним, +/// [PersonalizationStories.show] с контекстом под ним и просмотры +/// [PersonalizationStoryViewer] под ним. +/// +/// Не публичный API: только шлюз v3 (`src/v3/personalization_v3.dart`). +/// +/// API v3 — свой хост ([ownApiV3Domain], параметр `apiV3Domain`), без него глобальный +/// [apiV3Domain]: лента, кампания по ссылке и события — на v3, у слайдов со ссылкой кнопка +/// «Поделиться», ссылки открывает [handleLink]. Пустой свой хост — старый API и при +/// заданном глобальном. Действует ближайший над блоком [PersonalizationStoriesV3]; два +/// блока на одном экране независимы: один может идти в старый API, другой — в v3. +/// Сменился хост — блок грузится заново. Открыт один просмотр V2 из блока, `show` или +/// [handleLink]: ссылка закрывает прежний перед показом своего. +/// +/// Опросы слайдов — тоже только с API v3: ответы уходят на хост блока, а +/// [pollsTransport] их подменяет (тесты, офлайн-демо). Просмотр под +/// [PersonalizationStoriesV3] со своим [pollsTransport] рисует опросы и без API v3. Ответы +/// сессии помнят все блоки, `show` и [handleLink] — до конца процесса. +/// +/// ```dart +/// PersonalizationStoriesV3( +/// apiV3Domain: 'app.rees46.ru', +/// shareUrlTransform: (url) => url.replaceFirst('https://', 'myapp://'), +/// child: PersonalizationStories(code: code), +/// ) +/// ``` +class PersonalizationStoriesV3 extends StatelessWidget { + const PersonalizationStoriesV3({ + super.key, + String? apiV3Domain, + this.shareLabel = 'Share', + this.shareUrlTransform, + this.pollsTransport, + this.pollReanswerText = 'Answer again', + this.pollSubmitText = 'Send', + this.pollErrorText = 'Failed to send the answer. Please try again', + required this.child, + }) : ownApiV3Domain = apiV3Domain; + + /// Свой хост API v3 без схемы (параметр `apiV3Domain`, например `app.rees46.ru`): лента, + /// события и кнопка «Поделиться» поддерева. `null` — глобальный [apiV3Domain]; пустая + /// строка — старый API и при заданном глобальном. + final String? ownApiV3Domain; + + /// Подпись «Поделиться» для скринридера. + final String shareLabel; + + /// Что сделать со ссылкой слайда перед системным окном «Поделиться», например сменить + /// `https://` на схему приложения; `null` — ссылка как есть. Событие `share` не меняется. + final String Function(String url)? shareUrlTransform; + + /// Куда отправлять ответы опросов слайдов; `null` — HTTP API v3 хоста. Блоку без API v3 + /// опросов нет и с ним. + final StoryPollsTransport? pollsTransport; + + /// Тексты карточки опроса: ссылка «Ответить заново», кнопка отправки без своей подписи + /// опроса и ошибка отправки. Непустые `labels` опроса от сервера важнее. + final String pollReanswerText; + final String pollSubmitText; + final String pollErrorText; + + /// Поддерево в режиме v3. + final Widget child; + + /// Глобальный хост API v3 сторис V2 без схемы, как `REES46Config.apiDomain`, например + /// `app.rees46.ru`, — для блоков, `show` и [handleLink] без своего хоста. `null` (по + /// умолчанию) — у них всё по-старому: лента `stories/{code}` и трекинг `track/stories` + /// через нативный SDK. Задан — их запросы V2 идут на `https://{apiV3Domain}`: лента и + /// события из Dart, у слайдов со ссылкой — кнопка «Поделиться», [handleLink] открывает + /// ссылки. + static String? get apiV3Domain => StoriesApiV3.domain; + static set apiV3Domain(String? value) => StoriesApiV3.domain = value; + + @override + Widget build(BuildContext context) => StoriesV3Scope( + options: StoriesV3Options( + apiV3Domain: ownApiV3Domain, + shareLabel: shareLabel, + shareUrlTransform: shareUrlTransform, + pollsTransport: pollsTransport, + pollTexts: StoryPollTexts( + reanswer: pollReanswerText, + error: pollErrorText, + submit: pollSubmitText, + ), + ), + child: child, + ); + + /// Открыть сторис по ссылке «Поделиться» [url]: + /// `https://<сайт>/<путь>?r46_stories=&r46_story=[&r46_slide=]`. + /// + /// `false` — не ссылка сторис или API v3 выключен (нет ни `apiV3Domain`, ни + /// глобального [apiV3Domain]): ничего не делает. `true` — дальше асинхронно: дождаться + /// SDK (как [PersonalizationStories.show]), загрузить кампанию ссылки (`/story/{id}` + /// API v3), закрыть открытый просмотр V2 и открыть свой — с первой сторис ответа, со + /// слайда ссылки (`r46_slide`), если он есть в ответе, иначе со слайда + /// `start_position`; в обход правила «первый непросмотренный». После показа один раз — + /// событие `shared_open` со слайдом, с которого начали. Ошибка, 404, пустой ответ или + /// дольше 15 с — [onError], ничего не показывается, событий нет. Та же ссылка, пока + /// прежняя грузится или её просмотр открыт, — ничего, но `true`. Тексты, колбэки и + /// [controller] — как у [PersonalizationStories.show], остальное — как у + /// [PersonalizationStoriesV3]. + static bool handleLink( + BuildContext context, + String url, { + PersonalizationSdk? sdk, + String? shopId, + PersonalizationStoriesController? controller, + ValueChanged? onLinkClick, + ValueChanged? onProductClick, + ValueChanged? onPromoCopied, + ValueChanged? onError, + String promoCopiedText = 'Copied', + String promoCaption = 'Promo code', + String productButtonText = 'More info', + String showProductsText = 'Used products', + String hideProductsText = 'Hide products', + String retryText = 'Retry', + String closeLabel = 'Close', + String shareLabel = 'Share', + String soundOnLabel = 'Sound on', + String soundOffLabel = 'Sound off', + PersonalizationStoryImageProvider? imageProvider, + Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder, + String Function(String url)? shareUrlTransform, + StoryPollsTransport? pollsTransport, + String pollReanswerText = 'Answer again', + String pollSubmitText = 'Send', + String pollErrorText = 'Failed to send the answer. Please try again', + String? apiV3Domain, + }) { + final link = parseStoriesShareLink(url); + if (link == null) return false; + // Хост — сейчас: дальше ссылка идёт на него, даже если глобальный поменяют. + final host = StoriesApiV3.host(apiV3Domain); + if (host == null) { + debugPrint('PersonalizationStoriesV3.handleLink: links need apiV3Domain'); + return false; + } + if (_linkBusy(link.key)) return true; + _openLinks[link.key] = null; + // Носитель текстов и колбэков для просмотра, как у show; в дерево не вставляется. + final config = PersonalizationStories( + code: link.code, + onLinkClick: onLinkClick, + onProductClick: onProductClick, + onPromoCopied: onPromoCopied, + promoCopiedText: promoCopiedText, + promoCaption: promoCaption, + productButtonText: productButtonText, + showProductsText: showProductsText, + hideProductsText: hideProductsText, + retryText: retryText, + closeLabel: closeLabel, + soundOnLabel: soundOnLabel, + soundOffLabel: soundOffLabel, + imageProvider: imageProvider, + iconBuilder: iconBuilder, + ); + final v3 = StoriesV3Options( + apiV3Domain: host, + shareLabel: shareLabel, + shareUrlTransform: shareUrlTransform, + pollsTransport: pollsTransport, + pollTexts: StoryPollTexts( + reanswer: pollReanswerText, + error: pollErrorText, + submit: pollSubmitText, + ), + ); + unawaited( + _openLink( + context, + link, + config: config, + v3: v3, + sdk: sdk, + shopId: shopId, + controller: controller, + onError: onError, + ).whenComplete(() => _openLinks.remove(link.key)), + ); + return true; + } +} diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart index 7e8483f..0b23f33 100644 --- a/lib/src/ui/widgets/personalization_story_viewer.dart +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -8,15 +8,19 @@ import 'package:video_player/video_player.dart'; import '../../personalization_sdk.dart'; import '../../stories/stories_response.dart'; +import 'stories_api_v3.dart'; import 'stories_gif.dart'; import 'stories_gif_player.dart'; import 'stories_image.dart'; import 'stories_media_cache.dart'; import 'stories_playback.dart'; +import 'stories_poll.dart'; +import 'stories_polls_api.dart'; import 'stories_seen_store.dart'; import 'stories_slide_view.dart'; import 'stories_sound.dart'; import 'stories_support.dart'; +import 'stories_v3_scope.dart'; /// Полноэкранный просмотр сторис: слайды по таймеру, листание, товары, ссылки. /// @@ -67,6 +71,7 @@ class PersonalizationStoryViewer extends StatefulWidget { super.key, required this.stories, this.initialStory = 0, + this.initialSlide, this.seen = const >{}, this.code, this.sdk, @@ -96,6 +101,10 @@ class PersonalizationStoryViewer extends StatefulWidget { /// С какой сторис начать — индекс в [stories]. final int initialStory; + /// Слайд начальной сторис в обход правила «первый непросмотренный»; `null` — по + /// правилам. Так ссылка «Поделиться» открывает свой слайд. + final int? initialSlide; + /// Уже просмотренные слайды: id слайдов по id сторис. По ним выбирается стартовый слайд /// сторис (первый непросмотренный). С [sdk] к ним добавляется сохранённое на устройстве. final Map> seen; @@ -186,11 +195,23 @@ class PersonalizationStoryViewer extends StatefulWidget { _PersonalizationStoryViewerState(); } +// Режим API v3 — [StoriesV3Scope] над просмотром (его ставит шлюз v3), без него — +// глобальный хост [StoriesApiV3.domain]: +// - события уходят из Dart на v3 — и у слайдов с id не числом тоже ([StoriesApiV3]); +// - «Поделиться» — с `sdk` и `code`: у слайда со ссылкой ([storySlideShareUrl]) в шапке +// кнопка. Нажатие — пауза, событие `share` и системное окно с ссылкой; закрыли окно — +// пауза снята, слайд идёт дальше, если шёл; +// - опросы слайдов (мини-опросы, NPS, CSAT, CES): ответы уходят через транспорт режима, +// без него — на хост API v3 просмотра ([StoriesPollsApi], нужен `sdk`); нет ни того ни +// другого — опросы не рисуются. Свой транспорт рисует их и без API v3. Пока карточку +// держат пальцем, в фокусе её поле или идёт отправка — пауза; касания карточки слайд не +// листают. Ответы помнятся до конца процесса ([StoryPollStore]). class _PersonalizationStoryViewerState extends State with SingleTickerProviderStateMixin, WidgetsBindingObserver { late final StoriesPlayback _playback = StoriesPlayback( stories: widget.stories, initialStory: widget.initialStory, + initialSlide: widget.initialSlide, seen: _initialSeen(), ); late final PageController _pages = PageController( @@ -218,6 +239,12 @@ class _PersonalizationStoryViewerState extends State StoriesTimer? _autoRetry; bool _closing = false; + /// Открыто окно «Поделиться»: второе не открывается. + bool _sharing = false; + + // Режим API v3 над просмотром; `null` — его нет. + StoriesV3Options? _v3; + static const Duration _turn = Duration(milliseconds: 300); static const Duration _readyTimeout = Duration(seconds: 10); static const Duration _videoRetry = Duration(seconds: 15); @@ -269,6 +296,8 @@ class _PersonalizationStoryViewerState extends State @override void didChangeDependencies() { super.didChangeDependencies(); + // До первого захода: initState его откладывает на после кадра. + _v3 = StoriesV3Scope.of(context); // Просмотр закрыт непрозрачным экраном — навигатор глушит тикеры его поддерева. _setPaused( StoriesPauseReason.covered, @@ -448,7 +477,9 @@ class _PersonalizationStoryViewerState extends State final sdk = widget.sdk; if (sdk != null) { StoriesSeenStore.instance.mark(sdk, story.id, slide.id); - if (storyTrackableId(story.id) && storyTrackableId(slide.id)) { + if (_v3Code != null) { + _trackV3(StoriesV3Event.view, story, slide); + } else if (storyTrackableId(story.id) && storyTrackableId(slide.id)) { sdk.tracking .storyView(storyId: story.id, slideId: slide.id, code: widget.code) .catchError((Object error) { @@ -469,6 +500,9 @@ class _PersonalizationStoryViewerState extends State final sdk = widget.sdk; final story = _playback.story; final slide = _playback.slide; + if (sdk != null && _v3Code != null) { + return _trackV3(StoriesV3Event.click, story, slide); + } if (sdk == null || !storyTrackableId(story.id) || !storyTrackableId(slide.id)) { @@ -481,6 +515,82 @@ class _PersonalizationStoryViewerState extends State }); } + // Хост API v3 просмотра: режима над ним, без него — глобальный; `null` — старый API. + String? get _v3Host => StoriesApiV3.host(_v3?.apiV3Domain); + + // Код блока для событий v3: у просмотра есть хост API v3, SDK и код; иначе `null` — + // старый трекинг через мост. + String? get _v3Code { + final code = widget.code; + if (_v3Host == null || widget.sdk == null) return null; + return code == null || code.isEmpty ? null : code; + } + + void _trackV3(StoriesV3Event event, Story story, StorySlide slide) { + final sdk = widget.sdk; + final code = _v3Code; + final host = _v3Host; + if (sdk == null || code == null || host == null) return; + unawaited( + StoriesApiV3.track( + sdk, + host, + code: code, + event: event, + storyId: story.id, + slideId: slide.id, + ), + ); + } + + StoriesPollsApi? _pollsApi; + + // Куда отправлять ответы опросов: транспорт режима v3, иначе HTTP API v3 хоста + // просмотра; без транспорта, API v3 или [PersonalizationStoryViewer.sdk] — `null`, + // опросы не рисуются. + StoryPollsTransport? get _polls { + final own = _v3?.pollsTransport; + if (own != null) return own; + final host = _v3Host; + final sdk = widget.sdk; + if (host == null || sdk == null) return null; + final api = _pollsApi; + if (api != null && api.sdk == sdk && api.host == host) return api; + return _pollsApi = StoriesPollsApi(sdk, host); + } + + /// «Поделиться»: своя пауза, `share` сразу, до результата, системное окно; закрыли — + /// пауза снята (остальные причины паузы держат слайд, как держали). + void _share(String url, Rect anchor) { + final sdk = widget.sdk; + if (sdk == null || _sharing || _closing) return; + _sharing = true; + _setPaused(StoriesPauseReason.share, true); + _trackV3(StoriesV3Event.share, _playback.story, _playback.slide); + sdk + .shareUrl(_shareLink(url), anchor) + .catchError((Object error) { + debugPrint('PersonalizationStoryViewer: share $url — $error'); + }) + .whenComplete(() { + _sharing = false; + if (mounted) _setPaused(StoriesPauseReason.share, false); + }); + } + + // Ссылка для окна «Поделиться» после `shareUrlTransform` режима v3; он упал — ссылка + // как есть. + String _shareLink(String url) { + final transform = _v3?.shareUrlTransform; + if (transform == null) return url; + try { + return transform(url); + } catch (error) { + debugPrint('PersonalizationStoryViewer: shareUrlTransform — $error'); + return url; + } + } + // --- Медиа -------------------------------------------------------------------------- /// Загрузка медиа захода [generation]. Готово — часы пошли; ошибка или 10 с без @@ -834,12 +944,22 @@ class _PersonalizationStoryViewerState extends State onTap: _tap, onHold: (held) => _setPaused(StoriesPauseReason.hold, held), onClose: _close, + onShare: _v3Code == null ? null : _share, + shareLabel: _v3?.shareLabel ?? 'Share', onToggleMute: StoriesSound.instance.toggle, onSheet: _sheet, onButton: _button, onProduct: _product, onPromoCopied: _promo, onRetry: _retry, + pollsTransport: _polls, + pollTexts: _v3?.pollTexts ?? const StoryPollTexts(), + pollShopId: widget.sdk == null + ? '' + : StoriesSeenStore.shopOf(widget.sdk!), + onPollHold: (held) { + if (mounted) _setPaused(StoriesPauseReason.poll, held); + }, ); } } diff --git a/lib/src/ui/widgets/product_mapping.dart b/lib/src/ui/widgets/product_mapping.dart new file mode 100644 index 0000000..397686b --- /dev/null +++ b/lib/src/ui/widgets/product_mapping.dart @@ -0,0 +1,152 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +import '../../products/products_list_response.dart'; +import '../../recommendation/recommendation_response.dart'; +import '../../search/search_response.dart'; +import '../components/personalization_product.dart'; + +/// Товар ответа API → данные карточки кита. Один маппер на все виджеты с данными: +/// поиск, рекомендации, каталог. Форма товара в API везде одна, разные только модели +/// SDK, поэтому у каждой своя точка входа, а правила — общие, в [_card]. +/// +/// Не экспортируется: это внутренность виджетов с данными. +PersonalizationProduct productFromSearch( + SearchProduct product, { + String? actionText, +}) => _card( + id: product.id, + name: product.name, + brand: product.brand, + price: product.price, + priceFormatted: product.priceFormatted, + currency: product.currency, + oldPrice: product.oldPrice, + oldPriceFormatted: product.oldPriceFormatted, + discount: product.discount, + discountFormatted: product.discountFormatted, + discountPercent: product.discountPercent, + picture: product.picture, + imageUrl: product.imageUrl, + url: product.url, + deeplinkAndroid: product.deeplinkAndroid, + deeplinkIos: product.deeplinkIos, + actionText: actionText, +); + +/// Товар блока рекомендаций → карточка, см. [productFromSearch]. +PersonalizationProduct productFromRecommendation( + RecommendedProduct product, { + String? actionText, +}) => _card( + id: product.id, + name: product.name, + brand: product.brand, + price: product.price, + priceFormatted: product.priceFormatted, + currency: product.currency, + oldPrice: product.oldPrice, + oldPriceFormatted: product.oldPriceFormatted, + discount: product.discount, + discountFormatted: product.discountFormatted, + discountPercent: product.discountPercent, + picture: product.resizedImageUrl, + imageUrl: product.imageUrl, + url: product.url, + deeplinkAndroid: product.deeplinkAndroid, + deeplinkIos: product.deeplinkIos, + actionText: actionText, +); + +/// Товар каталога (категория, коллекция, список товаров, карточка товара) → +/// карточка, см. [productFromSearch]. +PersonalizationProduct productFromCatalog( + Product product, { + String? actionText, +}) => _card( + id: product.id, + name: product.name, + brand: product.brand, + price: product.price, + priceFormatted: product.priceFormatted, + currency: product.currency, + oldPrice: product.oldPrice, + oldPriceFormatted: product.oldPriceFormatted, + discount: product.discount, + discountFormatted: product.discountFormatted, + discountPercent: product.discountPercent, + picture: product.picture, + imageUrl: product.imageUrl, + url: product.url, + deeplinkAndroid: product.deeplinkAndroid, + deeplinkIos: product.deeplinkIos, + actionText: actionText, +); + +/// Общие правила. Строки берутся уже отформатированными сервером: +/// - цена — `price_formatted`, иначе «цена валюта»; +/// - старая цена — `oldprice_formatted`, и только когда `oldprice` больше цены; +/// - скидка — только при показанной старой цене и положительном числе скидки +/// (`discount`, иначе `discount_percent`), ровно с одним «-» впереди. Текст — +/// `discount_formatted`, только когда число из `discount` (строка сделана из него), +/// иначе «число%»; +/// - картинка — `picture` (уменьшенная копия), иначе `image_url`; +/// - диплинк — для платформы запуска; рейтинга в API нет. +PersonalizationProduct _card({ + required String id, + required String name, + required String brand, + required double price, + required String? priceFormatted, + required String currency, + required double? oldPrice, + required String? oldPriceFormatted, + required int? discount, + required String? discountFormatted, + required int? discountPercent, + required String? picture, + required String imageUrl, + required String url, + required String? deeplinkAndroid, + required String? deeplinkIos, + required String? actionText, +}) { + final hasOldPrice = + (oldPrice ?? 0) > price && (oldPriceFormatted ?? '').isNotEmpty; + // Число скидки решает, есть ли бейдж: «0%» или `true` из ответа — не скидка. + final fromDiscount = (discount ?? 0) > 0; + final number = fromDiscount + ? discount + : ((discountPercent ?? 0) > 0 ? discountPercent : null); + String? discountText; + if (hasOldPrice && number != null) { + // `discount_formatted` сделан из `discount`: к числу из `discount_percent` не подходит. + final formatted = fromDiscount ? (discountFormatted ?? '').trim() : ''; + final text = formatted.isNotEmpty ? formatted : '$number%'; + discountText = '-${text.replaceFirst(RegExp(r'^-+'), '')}'; + } + final priceText = priceFormatted ?? ''; + final image = (picture ?? '').isNotEmpty ? picture! : imageUrl; + return PersonalizationProduct( + id: id, + name: name, + price: priceText.isNotEmpty ? priceText : '$price $currency'.trim(), + image: image.isEmpty ? null : NetworkImage(image), + brand: brand.isEmpty ? null : brand, + oldPrice: hasOldPrice ? oldPriceFormatted : null, + discount: discountText, + actionText: actionText, + url: url.isEmpty ? null : url, + deeplink: _deeplink(android: deeplinkAndroid, ios: deeplinkIos), + ); +} + +/// Диплинк своей платформы: на остальных платформах приложения нет — `null`. +String? _deeplink({required String? android, required String? ios}) { + final link = switch (defaultTargetPlatform) { + TargetPlatform.android => android, + TargetPlatform.iOS => ios, + _ => null, + }; + return (link ?? '').isEmpty ? null : link; +} diff --git a/lib/src/ui/widgets/search_support.dart b/lib/src/ui/widgets/search_support.dart index 32be5d9..1f7297b 100644 --- a/lib/src/ui/widgets/search_support.dart +++ b/lib/src/ui/widgets/search_support.dart @@ -2,7 +2,6 @@ import 'package:flutter/widgets.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../search/search_response.dart'; -import '../components/personalization_product.dart'; /// Категория, на которую можно перейти из поиска: из подсказок instant-поиска (есть id) /// или из популярных категорий пустого запроса (только имя и ссылка). @@ -60,50 +59,6 @@ class RecentSearches { } } -/// Товар ответа поиска → данные карточки кита. Строки берутся уже отформатированными -/// сервером (`price_formatted`, `oldprice_formatted`, `discount_formatted`); картинка — -/// `picture` (уменьшенная копия), иначе оригинал. -PersonalizationProduct toCardProduct( - SearchProduct product, - String? actionText, -) { - final hasOldPrice = - product.oldPrice > product.price && - (product.oldPriceFormatted ?? '').isNotEmpty; - String? discount; - if (hasOldPrice) { - final formatted = product.discountFormatted; - if (formatted != null && formatted.isNotEmpty) { - discount = formatted; - } else if (product.discount > 0) { - discount = '${product.discount}%'; - } - } - final priceText = product.priceFormatted ?? ''; - return PersonalizationProduct( - id: product.id, - name: product.name, - price: priceText.isNotEmpty - ? priceText - : '${product.price} ${product.currency}'.trim(), - image: imageFor(product), - brand: product.brand.isEmpty ? null : product.brand, - oldPrice: hasOldPrice ? product.oldPriceFormatted : null, - discount: discount == null - ? null - : (discount.startsWith('-') ? discount : '-$discount'), - actionText: actionText, - ); -} - -/// Картинка товара для карточки: уменьшенная копия, иначе оригинал, иначе ничего. -ImageProvider? imageFor(SearchProduct product) { - final url = (product.picture ?? '').isNotEmpty - ? product.picture! - : product.imageUrl; - return url.isEmpty ? null : NetworkImage(url); -} - /// Имя родительской категории: в ответе родитель — это id, имя ищем среди пришедших. String? parentName(SearchCategory category, List all) { final parentId = category.parentId; diff --git a/lib/src/ui/widgets/stories_api_v3.dart b/lib/src/ui/widgets/stories_api_v3.dart new file mode 100644 index 0000000..fb3da45 --- /dev/null +++ b/lib/src/ui/widgets/stories_api_v3.dart @@ -0,0 +1,320 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; + +import '../../personalization_sdk.dart'; +import '../../stories/stories_response.dart'; +import '../../tracking/tracking_models.dart'; +import 'stories_seen_store.dart'; +import 'stories_share.dart'; + +/// Событие сторис API v3. +enum StoriesV3Event { + view('view'), + click('click'), + share('share'), + sharedOpen('shared_open'); + + const StoriesV3Event(this.wire); + + /// Значение поля `event`. + final String wire; +} + +/// Ответ HTTP: код и тело. +typedef StoriesV3Response = ({int status, String body}); + +/// Отправить запрос [method] на [uri] с телом JSON [body] (`null` — без тела). +typedef StoriesV3Send = + Future Function(String method, Uri uri, String? body); + +/// Ошибка API v3: HTTP не 2xx, не JSON или `status` не `success`. +class StoriesV3Exception implements Exception { + StoriesV3Exception(this.message, {this.status}); + + final String message; + + /// Код HTTP ответа; `null` — ошибка не в коде (не JSON, `status: fail`). + final int? status; + + @override + String toString() => 'StoriesV3Exception: $message'; +} + +/// Сторис V2 на API v3 — из Dart, без нативного SDK: `dart:io` и `did` через мост. +/// +/// Включается хостом: своим у `PersonalizationStoriesV3` над блоком, `show` или +/// просмотром или у `PersonalizationStoriesV3.handleLink` (их `apiV3Domain`), без него — +/// глобальным [domain] (`PersonalizationStoriesV3.apiV3Domain`); см. [host]. Нет +/// хоста — лента и события идут по-старому, через мост (`stories/{code}`, +/// `track/stories`). Есть — все запросы V2 этого блока идут на `https://{host}`: +/// - лента — `GET /api/v3/storefront/stories/{code}`; +/// - кампания по ссылке — `GET /api/v3/storefront/stories/{code}/story/{id}[?slide_id=]`; +/// - события — `POST /api/v3/storefront/stories/{code}/events`; +/// - ответы опросов слайдов — [post] (`/api/v3/polls/...`, `StoriesPollsApi`). +/// +/// Запросу нужны `shop_id` и `did`, `sid` не нужен. Без `did` сервер отвечает 400, а SDK +/// получает его при init: запрос ждёт его ([identity]). +abstract final class StoriesApiV3 { + /// Глобальный хост API v3 без схемы (`app.rees46.ru`) — для блоков без своего; + /// `null` или пусто — старый API. + static String? domain; + + /// Как ходить в сеть. Тесты подменяют. + static StoriesV3Send send = _send; + + /// Как часто спрашивать `did`, пока SDK его не получил. + static const Duration didPoll = Duration(milliseconds: 200); + + /// Сколько ждать `did` по умолчанию. + static const Duration didTimeout = Duration(seconds: 15); + + /// Сколько ждать ответа на [post]. + static const Duration requestTimeout = Duration(seconds: 15); + + /// Хост API v3 блока: свой [own], без него (`null`) — глобальный [domain]. Схема и + /// `/` на конце отбрасываются. `null` — API v3 выключен: хоста нет или он пустой (так + /// блок уходит на старый API и при заданном глобальном). + static String? host(String? own) { + var host = (own ?? domain)?.trim() ?? ''; + host = host.replaceFirst(RegExp(r'^https?://', caseSensitive: false), ''); + while (host.endsWith('/')) { + host = host.substring(0, host.length - 1); + } + return host.isEmpty ? null : host; + } + + /// Адрес `https://{host}/api/v3/storefront/stories/{segments...}?{query}`. + static Uri uri( + String host, + List segments, + Map query, + ) => apiUri(host, ['storefront', 'stories', ...segments], query); + + /// Адрес `https://{host}/api/v3/{segments...}?{query}`; сегменты кодируются. + static Uri apiUri( + String host, + List segments, [ + Map query = const {}, + ]) { + return Uri.parse('https://$host').replace( + pathSegments: ['api', 'v3', ...segments], + // Пустой запрос — без «?» на конце. + queryParameters: query.isEmpty ? null : query, + ); + } + + /// `POST https://{host}/api/v3/{segments...}` с телом JSON [body] — ответ + /// `{status, payload}` целиком. Ошибка — нет сети, нет ответа за [requestTimeout], + /// HTTP не 2xx ([StoriesV3Exception.status] — код, в сообщении `message` сервера), не + /// JSON или `status` `fail` / `error`. + static Future> post( + String host, + List segments, + Map body, + ) async { + final response = await send( + 'POST', + apiUri(host, segments), + jsonEncode(body), + ).timeout(requestTimeout); + final json = _decode(response); + final status = json['status']; + if (status == 'fail' || status == 'error') { + throw StoriesV3Exception( + '$status: ${json['message'] ?? _short(response)}', + ); + } + return json; + } + + /// Тело ответа объектом JSON. HTTP не 2xx — ошибка с кодом и `message` сервера, если + /// он есть; не JSON или не объект — ошибка. + static Map _decode(StoriesV3Response response) { + Object? json; + try { + json = jsonDecode(response.body); + } on FormatException { + json = null; + } + final ok = response.status >= 200 && response.status < 300; + if (!ok) { + final message = json is Map ? json['message'] : null; + throw StoriesV3Exception( + 'HTTP ${response.status}: ${message ?? _short(response)}', + status: response.status, + ); + } + if (json is! Map) { + throw StoriesV3Exception('not JSON: ${_short(response)}'); + } + return Map.from(json); + } + + /// `shop_id` и `did` магазина [sdk]. `did` спрашивается раз в [didPoll], пока SDK его + /// не получит; не дождались за [timeout] — [TimeoutException]. + static Future<({String shopId, String did})> identity( + PersonalizationSdk sdk, { + Duration timeout = didTimeout, + }) async { + final shop = StoriesSeenStore.shopOf(sdk); + if (shop.isEmpty) throw StateError('stories API v3: unknown shop_id'); + for (var waited = Duration.zero; ; waited += didPoll) { + String? did; + try { + did = await sdk.getDid(); + } catch (_) { + // Инстанс ещё не готов — спросим снова. + } + if (did != null && did.isNotEmpty) return (shopId: shop, did: did); + if (waited >= timeout) { + throw TimeoutException('stories API v3: no did', timeout); + } + await Future.delayed(didPoll); + } + } + + /// Лента блока [code] с хоста [host]. + static Future feed( + PersonalizationSdk sdk, + String host, + String code, + ) async { + final id = await identity(sdk); + final response = await send( + 'GET', + uri( + host, + [code], + {'shop_id': id.shopId, 'did': id.did}, + ), + null, + ); + return parseResponse(response); + } + + /// Кампания ссылки [link] в формате ленты (обычно одна); `start_position` — слайд + /// ссылки. Нет кампании, она выключена или ей нельзя делиться — 404, ошибка. + static Future story( + PersonalizationSdk sdk, + String host, + StoriesShareLink link, + ) async { + final id = await identity(sdk); + final response = await send( + 'GET', + uri( + host, + [link.code, 'story', link.storyId], + { + 'shop_id': id.shopId, + 'did': id.did, + if (link.slideId != null) 'slide_id': link.slideId!, + }, + ), + null, + ); + return parseResponse(response); + } + + /// Событие [event] слайда [slideId] кампании [storyId] блока [code]. Ошибки — в лог: + /// просмотр от трекинга не зависит. `view` и `click` ещё и ставят источник следующих + /// событий — блок сторис, как это делает натив при старом трекинге. + static Future track( + PersonalizationSdk sdk, + String host, { + required String code, + required StoriesV3Event event, + required String storyId, + required String slideId, + }) async { + if (code.isEmpty || storyId.isEmpty || slideId.isEmpty) return; + try { + if (event == StoriesV3Event.view || event == StoriesV3Event.click) { + await sdk.tracking.setSource( + TrackingSource(type: TrackingSourceType.stories, code: code), + ); + } + } catch (error) { + debugPrint('PersonalizationStories: tracking source — $error'); + } + try { + final id = await identity(sdk); + final response = await send( + 'POST', + uri(host, [code, 'events'], const {}), + jsonEncode( + eventBody( + shopId: id.shopId, + did: id.did, + event: event, + storyId: storyId, + slideId: slideId, + ), + ), + ); + if (response.status < 200 || response.status >= 300) { + throw StoriesV3Exception('HTTP ${response.status}: ${response.body}'); + } + } catch (error) { + debugPrint('PersonalizationStories: v3 ${event.wire} — $error'); + } + } + + /// Тело события: id кампании — числом, как в ленте; id слайда — всегда строкой. + static Map eventBody({ + required String shopId, + required String did, + required StoriesV3Event event, + required String storyId, + required String slideId, + }) { + final number = int.tryParse(storyId); + return { + 'shop_id': shopId, + 'did': did, + 'event': event.wire, + 'story_id': number != null && '$number' == storyId ? number : storyId, + 'slide_id': slideId, + }; + } + + /// Ответ GET: `{"status":"success","payload":{id, settings, stories}}` — `payload` тем + /// же разбором, что и старая лента. HTTP не 2xx, не JSON, `status` не `success` или + /// нет `payload` — [StoriesV3Exception]. + static StoriesBlock parseResponse(StoriesV3Response response) { + final json = _decode(response); + if (json['status'] != 'success' || json['payload'] is! Map) { + throw StoriesV3Exception('unexpected response: ${_short(response)}'); + } + return StoriesBlock.fromJson( + Map.from(json['payload'] as Map), + ); + } + + static String _short(StoriesV3Response response) { + final body = response.body; + return body.length > 200 ? '${body.substring(0, 200)}…' : body; + } + + static final HttpClient _client = HttpClient() + ..connectionTimeout = const Duration(seconds: 15); + + static Future _send( + String method, + Uri uri, + String? body, + ) async { + final request = await _client.openUrl(method, uri); + request.headers.set(HttpHeaders.acceptHeader, 'application/json'); + if (body != null) { + request.headers.contentType = ContentType.json; + request.write(body); + } + final response = await request.close(); + final text = await response.transform(utf8.decoder).join(); + return (status: response.statusCode, body: text); + } +} diff --git a/lib/src/ui/widgets/stories_playback.dart b/lib/src/ui/widgets/stories_playback.dart index cef47b9..96eccca 100644 --- a/lib/src/ui/widgets/stories_playback.dart +++ b/lib/src/ui/widgets/stories_playback.dart @@ -22,6 +22,13 @@ enum StoriesPauseReason { /// Пауза от хоста (`PersonalizationStoriesController.pause`). host, + /// Открыто системное окно «Поделиться». + share, + + /// Опрос слайда: карточку держат пальцем, в фокусе её поле или идёт отправка ответа. + /// Снимается и при заходе на другой слайд — не залипает. + poll, + /// Медиа слайда ещё грузится. loading, @@ -69,9 +76,12 @@ enum StoriesStep { /// /// Сторис без слайдов отбрасываются при создании. class StoriesPlayback { + /// [initialSlide] — слайд начальной сторис в обход правил стартового слайда (ссылка + /// «Поделиться» открывает слайд ссылки); действует до первого захода на неё. StoriesPlayback({ required List stories, int initialStory = 0, + int? initialSlide, Map> seen = const >{}, }) : stories = List.unmodifiable( stories.where((story) => story.slides.isNotEmpty), @@ -85,6 +95,7 @@ class StoriesPlayback { if (stories[i].slides.isNotEmpty) kept++; } _story = this.stories.isEmpty ? 0 : kept.clamp(0, this.stories.length - 1); + _initialSlide = this.stories.isEmpty ? null : initialSlide; } /// Сторис со слайдами в порядке ленты. @@ -98,6 +109,9 @@ class StoriesPlayback { bool _entered = false; bool _sheet = false; int? _turnTarget; + + /// Слайд начальной сторис в обход правил, пока на неё не зашли. + int? _initialSlide; Duration _elapsed = Duration.zero; Duration _duration = Duration.zero; bool _byVideo = false; @@ -166,9 +180,14 @@ class StoriesPlayback { return story.startPosition.clamp(0, slides.length - 1); } - /// Стартовый слайд сторис [index] по текущему состоянию просмотренного. + /// Стартовый слайд сторис [index] по текущему состоянию просмотренного; у начальной + /// сторис до первого захода — заданный при создании, если он был. int startSlideFor(int index) { final story = stories[index]; + final initial = _initialSlide; + if (initial != null && index == _story && !_entered) { + return initial.clamp(0, story.slides.length - 1); + } return startSlideOf(story, _seen[story.id] ?? const {}); } @@ -183,6 +202,7 @@ class StoriesPlayback { if (_entered && target == _story) return false; _story = target; _slide = startSlideFor(target); + _initialSlide = null; _enter(); return true; } @@ -334,6 +354,7 @@ class StoriesPlayback { _reasons ..remove(StoriesPauseReason.sheet) ..remove(StoriesPauseReason.error) + ..remove(StoriesPauseReason.poll) ..add(StoriesPauseReason.loading); (_seen[story.id] ??= {}).add(slide.id); } diff --git a/lib/src/ui/widgets/stories_poll.dart b/lib/src/ui/widgets/stories_poll.dart new file mode 100644 index 0000000..823f382 --- /dev/null +++ b/lib/src/ui/widgets/stories_poll.dart @@ -0,0 +1,473 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; + +import '../../stories/stories_response.dart'; +import 'stories_polls_api.dart'; + +/// Тексты карточки опроса: умолчания < тексты хоста < `labels` элемента. +@immutable +class StoryPollTexts { + const StoryPollTexts({ + this.reanswer = defaultReanswer, + this.error = defaultError, + this.submit = defaultSubmit, + }); + + static const String defaultReanswer = 'Answer again'; + static const String defaultError = + 'Failed to send the answer. Please try again'; + static const String defaultSubmit = 'Send'; + + /// Ссылка «Ответить заново» у отвеченного опроса с `allow_reanswer`. + final String reanswer; + + /// Отправка не удалась. + final String error; + + /// Кнопка отправки, когда у опроса нет `submit_label`. + final String submit; + + /// Тексты для [poll]: непустые `labels` сервера, иначе непустые тексты хоста, иначе + /// умолчания. + StoryPollTexts forPoll(StoryPollElement poll) { + String pick(String? label, String host, String fallback) => + label ?? (host.isNotEmpty ? host : fallback); + return StoryPollTexts( + reanswer: pick(poll.labels.reanswer, reanswer, defaultReanswer), + error: pick(poll.labels.error, error, defaultError), + submit: pick(poll.labels.submit, submit, defaultSubmit), + ); + } +} + +/// Тексты итогов опроса с выбором: шапка «Результаты», «Спасибо! Голос учтён» и число +/// голосов. Язык — устройства, как у текстов попапов v3: русский для `ru`, остальные — +/// английский. +@immutable +class StoryPollResultTexts { + const StoryPollResultTexts._({ + required this.results, + required this.thanks, + required this.counted, + required bool russian, + }) : _russian = russian; + + static const StoryPollResultTexts ru = StoryPollResultTexts._( + results: 'Результаты', + thanks: 'Спасибо!', + counted: 'Голос учтён', + russian: true, + ); + + static const StoryPollResultTexts en = StoryPollResultTexts._( + results: 'Results', + thanks: 'Thank you!', + counted: 'Vote counted', + russian: false, + ); + + /// По коду языка [language]: `ru` — русский, остальные — английский. + static StoryPollResultTexts of(String language) => language == 'ru' ? ru : en; + + /// Шапка итогов; на карточке — прописными. + final String results; + + /// Благодарность, когда у опроса нет своего `thanks_text`. + final String thanks; + + /// Продолжение благодарности. + final String counted; + final bool _russian; + + /// Число голосов [count] с разрядами (у русского — неразрывный пробел) и склонением: + /// «1 голос», «1 248 голосов», «1 vote», «1,248 votes». + String votes(int count) { + final number = _grouped(count, _russian ? '\u00A0' : ','); + if (!_russian) return '$number ${count == 1 ? 'vote' : 'votes'}'; + final tens = count.abs() % 100; + final ones = count.abs() % 10; + final noun = ones == 1 && tens != 11 + ? 'голос' + : ones >= 2 && ones <= 4 && (tens < 12 || tens > 14) + ? 'голоса' + : 'голосов'; + return '$number $noun'; + } + + static String _grouped(int value, String separator) { + final digits = value.abs().toString(); + final out = StringBuffer(value < 0 ? '-' : ''); + for (var i = 0; i < digits.length; i++) { + if (i > 0 && (digits.length - i) % 3 == 0) out.write(separator); + out.write(digits[i]); + } + return out.toString(); + } +} + +/// Оценки шкалы: `rate_min..rate_max`, по умолчанию NPS 0..10, CSAT 1..5, CES 1..7; не +/// больше 21 значения. +List storyPollScaleRange(StoryPollElement poll) { + final (min, max) = switch (poll.pollType) { + StoryPollType.nps => (0, 10), + StoryPollType.csat => (1, 5), + _ => (1, 7), + }; + final from = poll.rateMin ?? min; + final to = poll.rateMax ?? max; + return [ + for (var value = from; value <= to && value - from <= 20; value++) value, + ]; +} + +const List _npsColors = [ + Color(0xFFFCA5A5), + Color(0xFFFCA5A5), + Color(0xFFFCA5A5), + Color(0xFFFDBA74), + Color(0xFFFDBA74), + Color(0xFFFDBA74), + Color(0xFFFCD34D), +]; + +/// Цвет ячейки [value] шкалы [min]..[max]: NPS 0..10 — 0–6 красные и оранжевые, 7–8 +/// жёлтые, 9–10 зелёные; остальные — по третям диапазона. +Color storyPollScaleColor(StoryPollType kind, int value, int min, int max) { + if (kind == StoryPollType.nps && min == 0 && max == 10) { + if (value <= 6) return _npsColors[math.max(0, value)]; + return value <= 8 ? const Color(0xFFFDE68A) : const Color(0xFF86EFAC); + } + final position = max > min ? (value - min) / (max - min) : 1; + if (position < 0.34) return const Color(0xFFFCA5A5); + return position < 0.68 ? const Color(0xFFFDE68A) : const Color(0xFF86EFAC); +} + +/// Текст `success` полосы шкалы, где `from ≤ rate ≤ to`; нет такой — `null`. +String? storyPollBandText(StoryPollElement poll, num? rate) { + if (rate == null) return null; + for (final band in poll.bands) { + if (rate >= band.from && rate <= band.to) return band.success; + } + return null; +} + +/// Ответ опроса и итоги, как их показать. +typedef StoryPollState = ({StoryPollAnswer? answer, StoryPollResults? results}); + +/// Ответы опросов за сессию: в памяти процесса, одно на все виджеты, `show` и +/// ссылки. Ключ — магазин, вид опроса и код. Важнее ответа из ленты: лента +/// сторис не перезагружается после ответа. На диск не пишется. +class StoryPollStore { + /// Хранилище процесса. Тесты подменяют его. + static StoryPollStore instance = StoryPollStore(); + + final Map _states = {}; + + static String _key(String shopId, StoryPollElement poll) => + '$shopId\n${poll.pollType.wire}\n${poll.code}'; + + /// Сохранённый ответ опроса [poll] магазина [shopId]; нет — `null`. + StoryPollState? read(String shopId, StoryPollElement poll) => + _states[_key(shopId, poll)]; + + void write(String shopId, StoryPollElement poll, StoryPollState state) => + _states[_key(shopId, poll)] = state; +} + +/// Касания, начатые на карточке опроса или на подложке под открытой клавиатурой: слайд +/// их не берёт — ни касание по третям, ни удержание. Карточка отмечает касание раньше, +/// чем его увидит слайд: глубокие получатели касаний идут первыми. +abstract final class StoryPollPointers { + static final Set _claimed = {}; + + static void claim(int pointer) => _claimed.add(pointer); + + static void release(int pointer) => _claimed.remove(pointer); + + static bool claimed(int pointer) => _claimed.contains(pointer); +} + +/// Логика карточки опроса — как `createPoll` веб-SDK, без UI. +/// +/// - Состояния: форма и отвеченное ([answered]). Отвеченное — когда есть запись хранилища +/// сессии ([StoryPollStore]) или у ответа ленты есть варианты, текст или оценка. +/// - Выбор одного и шкала отправляются нажатием ([choose], [rate]); выбор сразу +/// подсвечен, при ошибке откатывается к прежнему. Выбор нескольких и текст — кнопкой +/// ([submitChoices], [submitText]); варианты уходят в порядке опроса, текст — без +/// пробелов по краям. +/// - Пока идёт отправка ([sending]), всё выключено, повторы игнорируются. Ошибка — +/// [failed], всё снова доступно, автоповтора нет; в лог её пишет транспорт. +/// - [reanswer] при `allow_reanswer` возвращает форму с прежним ответом (у текста — +/// пустое поле). +/// - Слайд держит [onHold]: пока карточку держат пальцем ([pressed]), в фокусе поле +/// ([focused]) или идёт отправка — и только пока карточка [active] (живой слайд). +/// +/// Ответ пишется в хранилище и после [dispose] — карточку уже убрали (сменили слайд, +/// закрыли просмотр); тогда ни состояние, ни [onHold] не трогаются. +class StoryPollController extends ChangeNotifier { + StoryPollController({ + required this.poll, + required this.storyId, + required this.slideId, + required this.transport, + this.shopId = '', + StoryPollTexts texts = const StoryPollTexts(), + this.onHold, + bool active = true, + StoryPollStore? store, + }) : texts = texts.forPoll(poll), + _active = active, + _store = store ?? StoryPollStore.instance { + final saved = _store.read(shopId, poll); + _answer = saved != null ? saved.answer : poll.answer; + _results = saved != null ? saved.results : poll.results; + // Запись хранилища — это успешная отправка: отвечено, даже если ответ ничего не + // выделяет. + _answered = saved != null || (_answer?.isAnswered ?? false); + _resetForm(); + } + + final StoryPollElement poll; + final String storyId; + final String slideId; + final StoryPollsTransport transport; + + /// Магазин — часть ключа хранилища. + final String shopId; + + /// Тексты с учётом `labels` опроса. + final StoryPollTexts texts; + + /// Держать слайд (`true`) или отпустить. + final ValueChanged? onHold; + final StoryPollStore _store; + + StoryPollAnswer? _answer; + StoryPollResults? _results; + bool _answered = false; + bool _sending = false; + bool _failed = false; + Set _selected = const {}; + num? _rate; + String _text = ''; + bool _pressed = false; + bool _focused = false; + bool _active; + bool _held = false; + bool _disposed = false; + + StoryPollAnswer? get answer => _answer; + StoryPollResults? get results => _results; + bool get answered => _answered; + bool get sending => _sending; + + /// Последняя отправка не удалась. + bool get failed => _failed; + + /// Подсвеченные варианты: выбор одного — нажатый, выбор нескольких — отмеченные. + Set get selected => Set.unmodifiable(_selected); + + /// Подсвеченная оценка шкалы: нажатая в форме или отвеченная. + num? get rateValue => _answered ? _answer?.rate : _rate; + String get text => _text; + + /// На карточке поле ввода (форма текстового опроса). + bool get showsField => !_answered && poll.kind == StoryMiniPollKind.text; + + /// Кнопка отправки доступна. + bool get canSubmit => + !_sending && + switch (poll.kind) { + StoryMiniPollKind.multipleChoice => _selected.isNotEmpty, + StoryMiniPollKind.text => _text.trim().isNotEmpty, + _ => false, + }; + + /// Слайд держится. + bool get holding => _held; + + Set get _previousIds => {...?_answer?.optionIds}; + + void _resetForm() { + final previous = _previousIds; + _selected = { + for (final option in poll.options) + if (previous.contains(option.id)) option.id, + }; + _rate = _answer?.rate; + _text = ''; + } + + set pressed(bool value) { + if (_pressed == value) return; + _pressed = value; + _syncHold(); + } + + set focused(bool value) { + if (_focused == value) return; + _focused = value; + _syncHold(); + } + + /// Карточка на живом слайде: только тогда она держит слайд. + set active(bool value) { + if (_active == value) return; + _active = value; + _syncHold(); + } + + /// Выбор одного: вариант [id] сразу подсвечен и отправлен. + void choose(int id) { + if (_answered || _sending || _disposed) return; + final previous = _selected; + _selected = {id}; + _send( + () => transport.answerMiniPoll( + poll.code, + storyPollAnswerBody( + optionIds: [id], + storyId: storyId, + slideId: slideId, + ), + ), + sent: StoryPollAnswer(optionIds: [id]), + rollback: () => _selected = previous, + ); + } + + /// Выбор нескольких: отметить или снять вариант [id]. + void toggle(int id) { + if (_answered || _sending || _disposed) return; + _selected = {..._selected}; + if (!_selected.remove(id)) _selected.add(id); + notifyListeners(); + } + + /// Выбор нескольких: отправить отмеченное в порядке вариантов опроса. + void submitChoices() { + if (!canSubmit || + _answered || + poll.kind != StoryMiniPollKind.multipleChoice) { + return; + } + final ids = [ + for (final option in poll.options) + if (_selected.contains(option.id)) option.id, + ]; + _send( + () => transport.answerMiniPoll( + poll.code, + storyPollAnswerBody(optionIds: ids, storyId: storyId, slideId: slideId), + ), + sent: StoryPollAnswer(optionIds: ids), + ); + } + + /// Текст поля поменялся. + set text(String value) { + if (_text == value || _disposed) return; + _text = value; + notifyListeners(); + } + + /// Текстовый опрос: отправить текст без пробелов по краям. + void submitText() { + final value = _text.trim(); + if (!canSubmit || _answered || value.isEmpty) return; + _send( + () => transport.answerMiniPoll( + poll.code, + storyPollAnswerBody(text: value, storyId: storyId, slideId: slideId), + ), + sent: StoryPollAnswer(text: value), + ); + } + + /// Шкала: оценка [value] сразу подсвечена и отправлена. + void rate(int value) { + if (_answered || _sending || _disposed || !poll.pollType.isScale) return; + final previous = _rate; + _rate = value; + _send( + () => transport.review(poll.pollType, storyPollReviewBody(poll, value)), + sent: StoryPollAnswer(rate: value), + scale: true, + rollback: () => _rate = previous, + ); + } + + /// «Ответить заново»: снова форма с прежним ответом. + void reanswer() { + if (!_answered || !poll.allowReanswer || _sending || _disposed) return; + _answered = false; + _failed = false; + _resetForm(); + _changed(); + } + + Future _send( + Future Function() request, { + required StoryPollAnswer sent, + bool scale = false, + VoidCallback? rollback, + }) async { + _sending = true; + _failed = false; + _changed(); + try { + final reply = await request(); + // У шкалы ответ — сама оценка, итогов нет. + final StoryPollState state = scale + ? (answer: sent, results: null) + : (answer: reply.answer ?? sent, results: reply.results); + _store.write(shopId, poll, state); + if (_disposed) return; + _answer = state.answer; + _results = state.results; + _answered = true; + _sending = false; + _changed(); + } catch (_) { + // Лог ошибки — забота транспорта. + if (_disposed) return; + _sending = false; + _failed = true; + rollback?.call(); + _changed(); + } + } + + void _changed() { + _syncHold(); + notifyListeners(); + } + + void _syncHold() { + final hold = + !_disposed && + _active && + (_pressed || (_focused && showsField) || _sending); + if (hold == _held) return; + _held = hold; + onHold?.call(hold); + } + + /// Держала слайд — отпускает. + @override + void dispose() { + _disposed = true; + _syncHold(); + super.dispose(); + } +} + +/// Опрос слайда — первый элемент `poll`; нет — `null`. +StoryPollElement? storyPollOf(StorySlide slide) { + for (final element in slide.elements) { + if (element is StoryPollElement) return element; + } + return null; +} diff --git a/lib/src/ui/widgets/stories_polls_api.dart b/lib/src/ui/widgets/stories_polls_api.dart new file mode 100644 index 0000000..ddfd2f4 --- /dev/null +++ b/lib/src/ui/widgets/stories_polls_api.dart @@ -0,0 +1,142 @@ +import 'package:flutter/foundation.dart'; + +import '../../personalization_sdk.dart'; +import '../../stories/stories_response.dart'; +import 'stories_api_v3.dart'; + +/// Успешная отправка ответа опроса: что вернул сервер. +class StoryPollReply { + const StoryPollReply({this.answer, this.results}); + + /// Ответ, как его запомнил сервер (`payload.answer`); `null` — не прислал. + final StoryPollAnswer? answer; + + /// Итоги мини-опроса (`payload.results`, только при `show_results`). + final StoryPollResults? results; +} + +/// Как отправлять ответы опросов слайдов. Ошибка отправки — Future с ошибкой; в лог её +/// пишет сам транспорт (карточка не пишет). +/// +/// По умолчанию — [StoriesPollsApi] (HTTP API v3). Тесты и офлайн-демо подменяют его у +/// `PersonalizationStoriesV3` и `PersonalizationStoriesV3.handleLink` (`pollsTransport`). +abstract interface class StoryPollsTransport { + /// Ответ мини-опроса [code]. [body] — `{option_ids | text, story_id, slide_id}` + /// ([storyPollAnswerBody]); `shop_id`, `did` и `sid` добавляет транспорт. + Future answerMiniPoll(String code, Map body); + + /// Оценка шкалы [kind] (NPS, CSAT, CES). [body] — `{channel, category | campaign, + /// rate}` ([storyPollReviewBody]); `shop_id`, `did` и `sid` добавляет транспорт. + Future review(StoryPollType kind, Map body); +} + +/// Тело ответа мини-опроса: варианты [optionIds] или текст [text]; id кампании — +/// числом, как в ленте; id слайда — всегда строкой (у товарных слайдов он `39_0`). +Map storyPollAnswerBody({ + List? optionIds, + String? text, + required String storyId, + required String slideId, +}) { + final number = int.tryParse(storyId); + return { + 'option_ids': ?optionIds, + 'text': ?text, + if (storyId.isNotEmpty) + 'story_id': number != null && '$number' == storyId ? number : storyId, + if (slideId.isNotEmpty) 'slide_id': slideId, + }; +} + +/// Тело оценки шкалы [poll]: канал опроса (пусто — `stories`), код — `category` у NPS +/// и `campaign` у CSAT и CES. +Map storyPollReviewBody(StoryPollElement poll, int rate) => + { + 'channel': poll.channel.isNotEmpty ? poll.channel : 'stories', + poll.pollType == StoryPollType.nps ? 'category' : 'campaign': poll.code, + 'rate': rate, + }; + +/// Опросы API v3 на хосте [host] просмотра, с которого пришла лента: +/// - мини-опрос — `POST /api/v3/polls/mini_polls/{code}/answers`; +/// - шкала — `POST /api/v3/polls/{nps|csat|ces}/reviews`. +/// +/// К телу добавляются `shop_id`, `did` (ждём его, как лента: [StoriesApiV3.identity]) и +/// `sid` сеанса SDK — всегда, без сеанса пустой строкой. Транспорт, таймаут и разбор +/// `{status, payload}` — [StoriesApiV3.post]; ошибки — его, в отладочный лог с кодом HTTP +/// и `message` сервера. +class StoriesPollsApi implements StoryPollsTransport { + StoriesPollsApi(this.sdk, this.host); + + final PersonalizationSdk sdk; + + /// Хост API v3 без схемы (`app.rees46.ru`). + final String host; + + @override + Future answerMiniPoll( + String code, + Map body, + ) async { + final json = await _logged( + 'mini poll "$code"', + () async => StoriesApiV3.post(host, [ + 'polls', + 'mini_polls', + code, + 'answers', + ], await _identified(body)), + ); + final payload = json['payload']; + if (payload is! Map) return const StoryPollReply(); + return StoryPollReply( + answer: StoryPollAnswer.tryParse(payload['answer']), + results: StoryPollResults.tryParse(payload['results']), + ); + } + + @override + Future review( + StoryPollType kind, + Map body, + ) async { + await _logged( + '${kind.wire} "${body['category'] ?? body['campaign'] ?? ''}"', + () async => StoriesApiV3.post(host, [ + 'polls', + kind.wire, + 'reviews', + ], await _identified(body)), + ); + return const StoryPollReply(); + } + + /// Запрос [request] опроса [what]; ошибка — в отладочный лог и дальше. + static Future> _logged( + String what, + Future> Function() request, + ) async { + try { + return await request(); + } catch (error) { + debugPrint('PersonalizationStories: poll $what not sent — $error'); + rethrow; + } + } + + Future> _identified(Map body) async { + final id = await StoriesApiV3.identity(sdk); + var sid = ''; + try { + sid = await sdk.getSid(); + } catch (_) { + // Нет сеанса — пустой `sid`. + } + return { + 'shop_id': id.shopId, + 'did': id.did, + 'sid': sid, + ...body, + }; + } +} diff --git a/lib/src/ui/widgets/stories_share.dart b/lib/src/ui/widgets/stories_share.dart new file mode 100644 index 0000000..aafa212 --- /dev/null +++ b/lib/src/ui/widgets/stories_share.dart @@ -0,0 +1,128 @@ +import '../../stories/stories_response.dart'; + +/// Параметры ссылки «Поделиться» сторис (API v3): код блока, кампания и слайд. +const String storiesShareParamBlock = 'r46_stories'; +const String storiesShareParamStory = 'r46_story'; +const String storiesShareParamSlide = 'r46_slide'; + +/// Ссылка «Поделиться» сторис: +/// `https://<сайт>/<путь>?r46_stories=&r46_story=[&r46_slide=]`, другие +/// параметры допустимы. +class StoriesShareLink { + const StoriesShareLink({ + required this.code, + required this.storyId, + this.slideId, + }); + + /// Код блока сторис. + final String code; + + /// Id кампании — число до 10 цифр. + final String storyId; + + /// Id слайда: число или виртуальный слайд товарной кампании (`39_0`); нет или неверный — + /// `null`, кампания открывается со своего `start_position`. + final String? slideId; + + /// Ключ дублей: та же ссылка — тот же блок, кампания и слайд. + String get key => '$code/$storyId/${slideId ?? ''}'; + + @override + bool operator ==(Object other) => + other is StoriesShareLink && other.key == key; + + @override + int get hashCode => key.hashCode; + + @override + String toString() => 'StoriesShareLink($key)'; +} + +final RegExp _storyIdFormat = RegExp(r'^\d{1,10}$'); + +// Слайд: число или виртуальный слайд товарной кампании «{story_id}_{index}». +final RegExp _slideIdFormat = RegExp(r'^\d{1,10}(_\d{1,4})?$'); + +final RegExp _httpLink = RegExp(r'^https?://', caseSensitive: false); + +/// Ссылка сторис из адреса [url], как `parseShareLink` JS SDK: `r46_stories` не пустой, +/// `r46_story` — 1–10 цифр, `r46_slide` — число или `число_индекс` (неверный — `null`, +/// кампания всё равно открывается). Иначе — не ссылка сторис, `null`. Из повторов +/// параметра берётся первый. +StoriesShareLink? parseStoriesShareLink(String url) { + final Map> params; + try { + final uri = Uri.tryParse(url.trim()); + if (uri == null) return null; + params = uri.queryParametersAll; + } on FormatException { + // Битое %-кодирование в запросе. + return null; + } + String? first(String key) { + final values = params[key]; + return values == null || values.isEmpty ? null : values.first; + } + + final code = first(storiesShareParamBlock); + final storyId = first(storiesShareParamStory); + if (code == null || + code.isEmpty || + storyId == null || + !_storyIdFormat.hasMatch(storyId)) { + return null; + } + final slideId = first(storiesShareParamSlide); + return StoriesShareLink( + code: code, + storyId: storyId, + slideId: slideId != null && _slideIdFormat.hasMatch(slideId) + ? slideId + : null, + ); +} + +/// Ссылка «Поделиться» слайда [slide] кампании [story]: кампания запрещает делиться +/// (`shareable: false`) — нет; иначе своя ссылка слайда, без неё — ссылка кампании с id +/// слайда в `r46_slide` ([storyCampaignSlideUrl]). У слайдов товарных кампаний (`39_2`) +/// своих ссылок нет, и без id слайда ссылка открыла бы кампанию не с того слайда, +/// которым поделились. Только `http://` и `https://`; иначе нет. Нет ссылки — нет и +/// кнопки на слайде. +String? storySlideShareUrl(Story story, StorySlide slide) { + if (!story.shareable) return null; + final url = slide.shareUrl.isNotEmpty + ? slide.shareUrl + : storyCampaignSlideUrl(story.shareUrl, slide.id); + return _httpLink.hasMatch(url) ? url : null; +} + +/// Ссылка кампании [campaign] с `r46_slide=` в конце запроса, перед `#`. Пустая +/// ссылка, id слайда, который ссылка не несёт (не число и не `число_индекс`), или +/// `r46_slide` уже есть — как есть. Остальной адрес не перекодируется. +String storyCampaignSlideUrl(String campaign, String slideId) { + if (campaign.isEmpty || !_slideIdFormat.hasMatch(slideId)) return campaign; + final hash = campaign.indexOf('#'); + final base = hash < 0 ? campaign : campaign.substring(0, hash); + final fragment = hash < 0 ? '' : campaign.substring(hash); + final mark = base.indexOf('?'); + final query = mark < 0 ? '' : base.substring(mark + 1); + String name(String pair) { + final raw = pair.split('=').first; + try { + return Uri.decodeQueryComponent(raw); + } on FormatException { + return raw; + } + } + + if (query.split('&').map(name).contains(storiesShareParamSlide)) { + return campaign; + } + final separator = mark < 0 + ? '?' + : query.isEmpty || query.endsWith('&') + ? '' + : '&'; + return '$base$separator$storiesShareParamSlide=$slideId$fragment'; +} diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart index 8f11ef4..30528bb 100644 --- a/lib/src/ui/widgets/stories_slide_view.dart +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; @@ -8,6 +10,7 @@ import '../../stories/stories_response.dart'; import '../components/personalization_button.dart'; import '../components/personalization_product.dart'; import '../components/personalization_story_navigation.dart'; +import '../components/personalization_story_poll.dart'; import '../components/personalization_story_price.dart'; import '../components/personalization_story_sound_button.dart'; import '../components/personalization_story_used_products.dart'; @@ -15,6 +18,9 @@ import '../components/personalization_toast.dart'; import '../personalization_theme.dart'; import 'personalization_story_viewer.dart'; import 'stories_gif_player.dart'; +import 'stories_poll.dart'; +import 'stories_polls_api.dart'; +import 'stories_share.dart'; import 'stories_support.dart'; /// Один слайд просмотра сторис: фон, затемнение, содержимое, касания. @@ -27,11 +33,20 @@ import 'stories_support.dart'; /// - Товарный слайд — карточка товара кита, все кнопки слайда (Primary LG друг под /// другом), «Используемые товары» и звук у видео; текстовые блоки на нём не рисуются, /// но промокод текстового блока, если у товара своего нет, показывает блок цены. -/// - Медиа-слайд — непустые текстовые блоки на `y_offset`% высоты, кнопки внизу, -/// «Используемые товары», звук у видео. +/// - Медиа-слайд — непустые текстовые блоки, кнопки внизу, «Используемые товары», звук +/// у видео. Текстовый блок стоит, как карточка опроса: верх на `y_offset`% высоты +/// всего слайда, но целиком между шапкой и нижними кнопками; выше этого места — от +/// его верха. /// - GIF фона живого слайда рисует [StoryGifPlayer]; у соседних страниц и до готовности /// — первый кадр. /// - Медиа не загрузилось — по центру кнопка кита [PersonalizationStoryViewer.retryText]. +/// - У слайда есть ссылка «Поделиться» ([storySlideShareUrl]) и задан [onShare] — в шапке +/// кнопка слева от крестика. +/// - Опрос слайда ([storyPollOf]) при заданном [pollsTransport] — карточка +/// [PersonalizationStoryPoll] на `y_offset`% высоты всего слайда, и на товарном слайде +/// тоже, но целиком между шапкой и нижними кнопками; не влезает — прокрутка в ней. +/// Открыта клавиатура — карточка над ней (+16), слайд не сжимается, тап мимо +/// карточки только прячет клавиатуру. /// /// Живой ([live]) — только текущий слайд осевшей страницы: у него часы, видео, касания и /// шторка. Соседние страницы показывают свой стартовый слайд неподвижно. @@ -52,12 +67,18 @@ class StorySlideView extends StatelessWidget { this.onTap, this.onHold, this.onClose, + this.onShare, + this.shareLabel = 'Share', this.onToggleMute, this.onSheet, this.onButton, this.onProduct, this.onPromoCopied, this.onRetry, + this.pollsTransport, + this.pollTexts = const StoryPollTexts(), + this.pollShopId = '', + this.onPollHold, }); final Story story; @@ -85,6 +106,12 @@ class StorySlideView extends StatelessWidget { final void Function(double dx, double width)? onTap; final ValueChanged? onHold; final VoidCallback? onClose; + + /// «Поделиться» ссылкой [url]; [anchor] — кнопка в глобальных координатах. + final void Function(String url, Rect anchor)? onShare; + + /// Подпись «Поделиться» для скринридера. + final String shareLabel; final VoidCallback? onToggleMute; final ValueChanged? onSheet; final ValueChanged? onButton; @@ -92,6 +119,18 @@ class StorySlideView extends StatelessWidget { final ValueChanged? onPromoCopied; final VoidCallback? onRetry; + /// Куда отправлять ответы опросов; `null` — опросы не рисуются. + final StoryPollsTransport? pollsTransport; + + /// Тексты карточки опроса от хоста. + final StoryPollTexts pollTexts; + + /// Магазин — ключ хранилища ответов опросов сессии. + final String pollShopId; + + /// Опрос держит слайд (`true`) или отпускает. + final ValueChanged? onPollHold; + /// Удержание дольше этого — пауза, а не касание. static const Duration holdDelay = Duration(milliseconds: 200); @@ -112,7 +151,9 @@ class StorySlideView extends StatelessWidget { final colors = PersonalizationTheme.of(context).colors; final light = colors.textPrimary.computeLuminance() > 0.5; final product = storyProductElement(slide); + // Нижний отступ — системный и при открытой клавиатуре: слайд под ней не сжимается. final content = SafeArea( + maintainBottomViewPadding: true, child: product != null ? _productContent(context, slide, product) : _mediaContent(context, slide), @@ -145,23 +186,21 @@ class StorySlideView extends StatelessWidget { return RawGestureDetector( behavior: HitTestBehavior.opaque, gestures: { - TapGestureRecognizer: - GestureRecognizerFactoryWithHandlers( - TapGestureRecognizer.new, - (recognizer) => - recognizer.onTapUp = (details) => - onTap?.call(details.localPosition.dx, width), - ), - LongPressGestureRecognizer: - GestureRecognizerFactoryWithHandlers( - () => LongPressGestureRecognizer(duration: holdDelay), - (recognizer) { - recognizer - ..onLongPressStart = ((_) => onHold?.call(true)) - ..onLongPressEnd = ((_) => onHold?.call(false)) - ..onLongPressCancel = (() => onHold?.call(false)); - }, - ), + _SlideTap: GestureRecognizerFactoryWithHandlers<_SlideTap>( + _SlideTap.new, + (recognizer) => + recognizer.onTapUp = (details) => + onTap?.call(details.localPosition.dx, width), + ), + _SlideHold: GestureRecognizerFactoryWithHandlers<_SlideHold>( + () => _SlideHold(duration: holdDelay), + (recognizer) { + recognizer + ..onLongPressStart = ((_) => onHold?.call(true)) + ..onLongPressEnd = ((_) => onHold?.call(false)) + ..onLongPressCancel = (() => onHold?.call(false)); + }, + ), }, child: child, ); @@ -231,12 +270,21 @@ class StorySlideView extends StatelessWidget { ); Widget _navigation() { + final share = onShare; + final url = share == null ? null : storySlideShareUrl(story, slide); Widget header(double value) => PersonalizationStoryNavigation( count: story.slides.length, current: slideIndex, progress: value, onClose: onClose, closeLabel: config.closeLabel, + // Кнопка видна и у соседних страниц, нажимается только у живой. + onShare: share == null || url == null + ? null + : (anchor) { + if (live) share(url, anchor); + }, + shareLabel: shareLabel, iconBuilder: config.iconBuilder, ); final progress = this.progress; @@ -249,8 +297,12 @@ class StorySlideView extends StatelessWidget { /// Шапка поверх всего слайда, и подложки шторки тоже: крестик закрывает просмотр и /// при раскрытой шторке; мимо крестика касание доходит до подложки. - Widget _header() => - Positioned(left: 16, top: 16, right: 16, child: _navigation()); + Widget _header() => Positioned( + left: 16, + top: 16, + right: 16, + child: _keyboardShield(_navigation()), + ); /// Кнопка звука — только у видео. Widget? _sound(StorySlide slide) { @@ -337,7 +389,7 @@ class StorySlideView extends StatelessWidget { onHorizontalDragStart: (_) {}, ), ), - Positioned(left: 0, right: 0, bottom: 0, child: row), + Positioned(left: 0, right: 0, bottom: 0, child: _keyboardShield(row)), ]; } @@ -347,27 +399,28 @@ class StorySlideView extends StatelessWidget { Widget _mediaContent(BuildContext context, StorySlide slide) { final texts = storyTextBlocks(slide); final buttons = storyButtons(slide); - return LayoutBuilder( - builder: (context, constraints) => Stack( - fit: StackFit.expand, - children: [ - for (final text in texts) - Positioned( - left: 16, - right: 16, - top: constraints.maxHeight * text.yOffset.clamp(0, 100) / 100, + final bottom = + (_hasRow(slide) ? 64 : 16) + buttons.length * _buttonSpace(context); + return Stack( + fit: StackFit.expand, + children: [ + for (final text in texts) + Positioned.fill( + child: CustomSingleChildLayout( + delegate: _blockLayout(context, text.yOffset, bottom: bottom), child: _textBlock(context, text), ), - Positioned( - left: 16, - right: 16, - bottom: _hasRow(slide) ? 64 : 16, - child: _primaryButtons(buttons), ), - ..._bottomRow(slide), - _header(), - ], - ), + Positioned( + left: 16, + right: 16, + bottom: _hasRow(slide) ? 64 : 16, + child: _primaryButtons(buttons), + ), + ..._poll(context, slide, bottom: bottom), + ..._bottomRow(slide), + _header(), + ], ); } @@ -491,9 +544,238 @@ class StorySlideView extends StatelessWidget { ], ), ); + final polls = _poll( + context, + slide, + bottom: + (_hasRow(slide) ? 64 : 16) + + math.max(1, buttons.length) * _buttonSpace(context), + ); return Stack( fit: StackFit.expand, - children: [column, ..._bottomRow(slide), _header()], + children: [column, ...polls, ..._bottomRow(slide), _header()], + ); + } + + // --- Опрос и место блоков ------------------------------------------------------------ + + /// Верх места блоков слайда (опрос, текстовые блоки): под шапкой, с зазором 8. + static const double _blockTop = + 16 + PersonalizationStoryNavigation.height + 8; + + /// Место под кнопкой Primary LG слайда: зазор 16 и кнопка — строка 32 и поля по 8. + double _buttonSpace(BuildContext context) => + 16 + MediaQuery.textScalerOf(context).scale(32) + 16; + + /// Раскладка блока слайда — карточки опроса ([poll]) или текстового блока — на + /// [yOffset]% высоты всего слайда, между шапкой и местом нижних кнопок [bottom]. + /// [outer] — контекст над SafeArea, с системными отступами. + _SlideBlockLayout _blockLayout( + BuildContext outer, + double yOffset, { + required double bottom, + double keyboard = 0, + bool poll = false, + }) => _SlideBlockLayout( + yOffset: yOffset, + // Отступы SafeArea слайда (снизу — системный и при клавиатуре). + above: MediaQuery.paddingOf(outer).top, + below: MediaQuery.viewPaddingOf(outer).bottom, + top: _blockTop, + bottom: bottom, + keyboard: keyboard, + poll: poll, + ); + + /// Опрос, который рисуется: есть элемент и транспорт. + StoryPollElement? _pollOf(StorySlide slide) => + pollsTransport == null ? null : storyPollOf(slide); + + /// Открыта клавиатура (поле опроса живого слайда). + bool _keyboardOpen(BuildContext context) => + live && MediaQuery.viewInsetsOf(context).bottom > 0; + + /// Подложка под открытой клавиатурой и карточка опроса. [bottom] — место нижних + /// кнопок и строки «товары»; [outer] — контекст над SafeArea, с системными отступами: + /// `y_offset` считается от всего слайда, а клавиатура перекрывает слайд на свою высоту + /// без нижнего. + List _poll( + BuildContext outer, + StorySlide slide, { + required double bottom, + }) { + final poll = _pollOf(slide); + final transport = pollsTransport; + if (poll == null || transport == null) return const []; + final safeBottom = MediaQuery.viewPaddingOf(outer).bottom; + return [ + Positioned.fill( + child: Builder( + builder: (context) => IgnorePointer( + ignoring: !_keyboardOpen(context), + child: _keyboardBarrier(), + ), + ), + ), + Positioned.fill( + child: Builder( + builder: (context) { + final keyboard = live + ? math.max( + 0.0, + MediaQuery.viewInsetsOf(context).bottom - safeBottom, + ) + : 0.0; + return CustomSingleChildLayout( + delegate: _blockLayout( + outer, + poll.yOffset ?? 0, + bottom: bottom, + keyboard: keyboard, + poll: true, + ), + child: IgnorePointer( + ignoring: !live, + child: PersonalizationStoryPoll( + key: ValueKey('poll-${slide.id}'), + poll: poll, + storyId: story.id, + slideId: slide.id, + transport: transport, + shopId: pollShopId, + texts: pollTexts, + live: live, + onHold: onPollHold, + ), + ), + ); + }, + ), + ), + ]; + } + + /// Тап мимо карточки при открытой клавиатуре только прячет её: ни касания по третям, + /// ни удержания, ни свайпов. + Widget _keyboardBarrier() => Listener( + onPointerDown: (event) => StoryPollPointers.claim(event.pointer), + onPointerUp: (event) => StoryPollPointers.release(event.pointer), + onPointerCancel: (event) => StoryPollPointers.release(event.pointer), + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => FocusManager.instance.primaryFocus?.unfocus(), + onVerticalDragStart: (_) {}, + onHorizontalDragStart: (_) {}, + ), + ); + + /// Шапка и нижняя строка слайда с опросом при открытой клавиатуре не нажимаются: тап + /// по ним достаётся подложке и только прячет клавиатуру. + Widget _keyboardShield(Widget child) { + if (_pollOf(slide) == null) return child; + return Builder( + builder: (context) => + IgnorePointer(ignoring: _keyboardOpen(context), child: child), ); } } + +/// Блок на слайде — карточка опроса или текстовый блок: верх — [yOffset]% высоты всего +/// слайда (зажато 0…100, не число — 0), потом сдвиг, чтобы блок целиком был между [top] +/// и местом нижних кнопок [bottom]; выше этого места — от его верха. +/// +/// Карточка опроса ([poll]) — по центру, шириной [PersonalizationStoryPoll.widthFor]; +/// не влезает — ниже высотой, прокрутка внутри. Клавиатура перекрывает слайд снизу на +/// [keyboard] — карточка поднимается над ней на 16. Текстовый блок — во всю ширину с +/// полями 16, своей высоты. +/// +/// Раскладка — в области SafeArea: [above] и [below] — отступы её от краёв слайда. +class _SlideBlockLayout extends SingleChildLayoutDelegate { + const _SlideBlockLayout({ + required this.yOffset, + required this.above, + required this.below, + required this.top, + required this.bottom, + this.keyboard = 0, + this.poll = false, + }); + + final double yOffset; + final double above; + final double below; + final double top; + final double bottom; + final double keyboard; + final bool poll; + + static const double _aboveKeyboard = 16; + + /// Поля текстового блока слева и справа. + static const double _textEdge = 16; + + /// Ниже этого низ блока не опускается. + double _limit(Size size) { + var limit = size.height - bottom; + if (keyboard > 0) { + limit = math.min(limit, size.height - keyboard - _aboveKeyboard); + } + return math.max(top, limit); + } + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + final size = constraints.biggest; + if (!poll) { + return BoxConstraints.tightFor( + width: math.max(0, size.width - 2 * _textEdge), + ); + } + final width = PersonalizationStoryPoll.widthFor(size.width); + return BoxConstraints( + minWidth: width, + maxWidth: width, + maxHeight: math.max(0, _limit(size) - top), + ); + } + + @override + Offset getPositionForChild(Size size, Size childSize) { + final slide = above + size.height + below; + final percent = yOffset.isFinite ? yOffset.clamp(0, 100) : 0; + final wanted = slide * percent / 100 - above; + final y = math.max(top, math.min(wanted, _limit(size) - childSize.height)); + return Offset((size.width - childSize.width) / 2, y); + } + + @override + bool shouldRelayout(_SlideBlockLayout oldDelegate) => + oldDelegate.yOffset != yOffset || + oldDelegate.above != above || + oldDelegate.below != below || + oldDelegate.top != top || + oldDelegate.bottom != bottom || + oldDelegate.keyboard != keyboard || + oldDelegate.poll != poll; +} + +/// Касание слайда по третям; касания карточки опроса и подложки клавиатуры +/// ([StoryPollPointers]) — не его. +class _SlideTap extends TapGestureRecognizer { + _SlideTap(); + + @override + bool isPointerAllowed(PointerDownEvent event) => + !StoryPollPointers.claimed(event.pointer) && + super.isPointerAllowed(event); +} + +/// Удержание слайда; касания карточки опроса — не его. +class _SlideHold extends LongPressGestureRecognizer { + _SlideHold({super.duration}); + + @override + bool isPointerAllowed(PointerDownEvent event) => + !StoryPollPointers.claimed(event.pointer) && + super.isPointerAllowed(event); +} diff --git a/lib/src/ui/widgets/stories_v3_scope.dart b/lib/src/ui/widgets/stories_v3_scope.dart new file mode 100644 index 0000000..436fee4 --- /dev/null +++ b/lib/src/ui/widgets/stories_v3_scope.dart @@ -0,0 +1,89 @@ +import 'package:flutter/widgets.dart'; + +import 'stories_poll.dart'; +import 'stories_polls_api.dart'; + +/// Режим API v3 сторис V2: хост, «Поделиться» и опросы слайдов. Внутренность кита: хост +/// задаёт режим через `PersonalizationStoriesV3` шлюза v3 (`src/v3/personalization_v3.dart`), +/// блок, `show`, ссылка и просмотр читают его отсюда. +@immutable +class StoriesV3Options { + const StoriesV3Options({ + this.apiV3Domain, + this.shareLabel = 'Share', + this.shareUrlTransform, + this.pollsTransport, + this.pollTexts = const StoryPollTexts(), + }); + + /// Хост API v3 без схемы; `null` — глобальный (`StoriesApiV3.domain`), пустая строка — + /// старый API и при заданном глобальном. + final String? apiV3Domain; + + /// Подпись «Поделиться» для скринридера. + final String shareLabel; + + /// Что сделать со ссылкой слайда перед окном «Поделиться»; `null` — ссылка как есть. + final String Function(String url)? shareUrlTransform; + + /// Куда отправлять ответы опросов; `null` — HTTP API v3 хоста. + final StoryPollsTransport? pollsTransport; + + /// Тексты карточки опроса от хоста. + final StoryPollTexts pollTexts; + + /// Те же настройки без своего транспорта опросов. + StoriesV3Options withoutPollsTransport() => StoriesV3Options( + apiV3Domain: apiV3Domain, + shareLabel: shareLabel, + shareUrlTransform: shareUrlTransform, + pollTexts: pollTexts, + ); + + @override + bool operator ==(Object other) => + other is StoriesV3Options && + other.apiV3Domain == apiV3Domain && + other.shareLabel == shareLabel && + other.shareUrlTransform == shareUrlTransform && + other.pollsTransport == pollsTransport && + other.pollTexts.reanswer == pollTexts.reanswer && + other.pollTexts.error == pollTexts.error && + other.pollTexts.submit == pollTexts.submit; + + @override + int get hashCode => Object.hash( + apiV3Domain, + shareLabel, + shareUrlTransform, + pollsTransport, + pollTexts.reanswer, + pollTexts.error, + pollTexts.submit, + ); +} + +/// Режим API v3 поддерева ([StoriesV3Options]). Ставит его `PersonalizationStoriesV3`, а +/// `show` и ссылки — вокруг своего просмотра: тот открывается на корневом навигаторе, +/// вне поддерева хоста. +class StoriesV3Scope extends InheritedWidget { + const StoriesV3Scope({ + super.key, + required this.options, + required super.child, + }); + + final StoriesV3Options options; + + /// Режим над [context] с подпиской на смену; `null` — его нет. + static StoriesV3Options? of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.options; + + /// Режим над [context] без подписки — вне сборки (`show`). + static StoriesV3Options? peek(BuildContext context) => + context.getInheritedWidgetOfExactType()?.options; + + @override + bool updateShouldNotify(StoriesV3Scope oldWidget) => + options != oldWidget.options; +} diff --git a/lib/src/v3/personalization_v3.dart b/lib/src/v3/personalization_v3.dart new file mode 100644 index 0000000..eeddc93 --- /dev/null +++ b/lib/src/v3/personalization_v3.dart @@ -0,0 +1,43 @@ +/// Шлюз v3: попапы нового конструктора и сторис на API v3. +/// +/// v3 — не публичный API. Код живёт в пакете и работает в наших демо, но интеграторам +/// он недоступен: `package:rees46_sdk/rees46_sdk.dart` и кит в нём его не экспортируют. +/// Шлюз снимается, только когда v3 станет публичным. +/// +/// Демо берёт v3 прямым импортом; анализатор помечает его как implementation import, и +/// это ожидаемо: +/// +/// ```dart +/// // ignore: implementation_imports +/// import 'package:rees46_sdk/src/v3/personalization_v3.dart'; +/// ``` +/// +/// v3 спит, пока хост не прошёл через этот шлюз: движок попапов выключен, пока его не +/// включат через `sdk.popups`, а сторис ходят в старый API, пока над ними нет +/// `PersonalizationStoriesV3` и не задан его глобальный `apiV3Domain`. +library; + +// Попапы нового конструктора (документ design): `sdk.popups` — включение, экраны, +// ручной показ, — и наблюдатель экранов навигатора. Движок и рендер — внутренности. +export '../popups_v3/popups_v3.dart'; +export '../ui/popups_v3/personalization_screen_observer.dart'; + +// Сторис V2 на API v3: хост (свой и глобальный), «Поделиться», ссылки и опросы. +export '../ui/widgets/personalization_stories.dart' + show PersonalizationStoriesV3; +export '../stories/stories_response.dart' + show + StoryShareV3, + StorySlideShareV3, + StoryPollType, + StoryMiniPollKind, + StoryPollOption, + StoryPollBand, + StoryPollAnswer, + StoryPollResults, + StoryPollLabels, + StoryPollElement; +// Опросы слайдов: шов транспорта ответов (тесты, офлайн-демо). Карточка и её логика — +// внутренности просмотра. +export '../ui/widgets/stories_polls_api.dart' + show StoryPollsTransport, StoryPollReply; diff --git a/pigeons/personalization_api.dart b/pigeons/personalization_api.dart index ac51e20..4f0b373 100644 --- a/pigeons/personalization_api.dart +++ b/pigeons/personalization_api.dart @@ -307,9 +307,19 @@ abstract class PersonalizationHostApi { /// Returns a category product listing as a JSON string. /// [limit] and [page] paginate the result; both are optional. + /// [paramsJson] is a JSON object string with the optional filters: "brands" and + /// "locations" (comma-separated strings), "filters" (facet name → [values]), + /// "price_min" / "price_max" (numbers), "sort_by" / "sort_dir" (strings). A bridge + /// passes on only what its native SDK takes for a category. /// Dart layer parses the result into [CategoryResponse]. @async - String getCategory(String category, int? limit, int? page, String? shopId); + String getCategory( + String category, + int? limit, + int? page, + String? paramsJson, + String? shopId, + ); /// Returns a merchandised collection's products as a JSON string. /// Dart layer parses the result into [CollectionResponse]. @@ -328,6 +338,20 @@ abstract class PersonalizationHostApi { @async bool openUrl(String url); + /// Shows the system share sheet with one link [url] — the "Share" button of the stories + /// viewer. Completes when the sheet is gone: iOS — `completionWithItemsHandler` of + /// `UIActivityViewController`; Android — the window got its focus back after the + /// chooser (`Intent.createChooser` of `ACTION_SEND`). The anchor is the button in + /// logical pixels of the Flutter view: the popover of the sheet points at it on iPad. + @async + void shareUrl( + String url, + double anchorX, + double anchorY, + double anchorWidth, + double anchorHeight, + ); + /// The slide ids seen per story id for [shop] — the plugin's own store /// (SharedPreferences on Android, UserDefaults on iOS), not the native SDK's. It /// survives app restarts. The inner lists are untyped on purpose: the channel diff --git a/test/catalog_test.dart b/test/catalog_test.dart index eda4052..71aece9 100644 --- a/test/catalog_test.dart +++ b/test/catalog_test.dart @@ -151,6 +151,45 @@ void main() { expect(r.products, isEmpty); }); + test('sends the filters as params JSON, none when unset', () async { + final calls = >[]; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMessageHandler(_categoryChannel, (message) async { + calls.add(messageCodec.decodeMessage(message)! as List); + return reply(jsonEncode({'products_total': 0})); + }); + + await PersonalizationSdk().getCategory('shoes', limit: 5, page: 2); + await PersonalizationSdk().getCategory( + 'shoes', + brands: 'Bosch,Philips', + locations: '1,2', + filters: { + 'Материал': ['Металл'], + 'Цвет': [], + }, + priceMin: 10, + priceMax: 99.5, + sortBy: 'price', + sortDir: 'asc', + ); + + expect(calls[0], ['shoes', 5, 2, null, null]); + expect(calls[1].take(3), ['shoes', null, null]); + expect(jsonDecode(calls[1][3]! as String), { + 'brands': 'Bosch,Philips', + 'locations': '1,2', + // A facet with nothing checked is not a filter. + 'filters': { + 'Материал': ['Металл'], + }, + 'price_min': 10.0, + 'price_max': 99.5, + 'sort_by': 'price', + 'sort_dir': 'asc', + }); + }); + test('empty category throws ArgumentError (no native call)', () async { expect( () => PersonalizationSdk().getCategory(''), diff --git a/test/fixtures/category.json b/test/fixtures/category.json new file mode 100644 index 0000000..67287c3 --- /dev/null +++ b/test/fixtures/category.json @@ -0,0 +1,217 @@ +{ + "products_total": 2320, + "products": [ + { + "name": "Наушники накладные HONOR CHOICE Headphones Lite Gray (5504ADGF)", + "url": "https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252?recommended_by=listing", + "deeplink_android": "https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252", + "deeplink_ios": "https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252", + "category_ids": [ + "smartfony-i-gadzhety", + "naushniki", + "vse-naushniki" + ], + "barcode": "300252", + "vendor_code": "5504ADGF", + "brand": "Honor", + "model": "5504ADGF", + "sales_rate": 6755, + "relative_sales_rate": 100, + "picture": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/146384.jpg", + "categories": [ + { + "id": "smartfony-i-gadzhety", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety?recommended_by=listing", + "name": "Смартфоны и гаджеты", + "level": "1", + "url_handle": "/catalog/smartfony-i-gadzhety?recommended_by=listing" + }, + { + "id": "naushniki", + "parent_id": "smartfony-i-gadzhety", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki?recommended_by=listing", + "name": "Смартфоны и гаджеты - Наушники", + "level": "2", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki?recommended_by=listing" + }, + { + "id": "vse-naushniki", + "parent_id": "naushniki", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki?recommended_by=listing", + "name": "Наушники - Все наушники", + "level": "3", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki?recommended_by=listing" + } + ], + "price_formatted": "15 990 ₽", + "price_full_formatted": "15 990.00 ₽", + "price": 15990, + "price_full": 15990, + "image_url": "https://api.technodom.kz/f3/api/v1/images/300252_1.jpg", + "image_url_handle": "/f3/api/v1/images/300252_1.jpg", + "image_url_resized": { + "120": "https://pictures.rees46.ru/resize-images/120/c1140c8254976de297c3caf971701a/146384.jpg", + "140": "https://pictures.rees46.ru/resize-images/140/c1140c8254976de297c3caf971701a/146384.jpg", + "160": "https://pictures.rees46.ru/resize-images/160/c1140c8254976de297c3caf971701a/146384.jpg", + "180": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/146384.jpg", + "200": "https://pictures.rees46.ru/resize-images/200/c1140c8254976de297c3caf971701a/146384.jpg", + "220": "https://pictures.rees46.ru/resize-images/220/c1140c8254976de297c3caf971701a/146384.jpg", + "310": "https://pictures.rees46.ru/resize-images/310/c1140c8254976de297c3caf971701a/146384.jpg", + "520": "https://pictures.rees46.ru/resize-images/520/c1140c8254976de297c3caf971701a/146384.jpg", + "original": "https://api.technodom.kz/f3/api/v1/images/300252_1.jpg" + }, + "url_handle": "/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252?recommended_by=listing", + "currency": "₽", + "_id": "146384", + "id": "300252", + "stock_quantity": 999999, + "group_id": "_146384_" + }, + { + "name": "Гарнитура Накладная Logitech H150, White, 981-000350", + "url": "https://www.technodom.kz/p/garnitura-nakladnaa-logitech-h-white-868?recommended_by=listing", + "deeplink_android": "https://www.technodom.kz/p/garnitura-nakladnaa-logitech-h-white-868", + "deeplink_ios": "https://www.technodom.kz/p/garnitura-nakladnaa-logitech-h-white-868", + "category_ids": [ + "smartfony-i-gadzhety", + "naushniki", + "vse-naushniki" + ], + "barcode": "868", + "vendor_code": "981-000350", + "brand": "Logitech", + "model": "981-000350", + "picture": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/131887.jpg", + "categories": [ + { + "id": "smartfony-i-gadzhety", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety?recommended_by=listing", + "name": "Смартфоны и гаджеты", + "level": "1", + "url_handle": "/catalog/smartfony-i-gadzhety?recommended_by=listing" + }, + { + "id": "naushniki", + "parent_id": "smartfony-i-gadzhety", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki?recommended_by=listing", + "name": "Смартфоны и гаджеты - Наушники", + "level": "2", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki?recommended_by=listing" + }, + { + "id": "vse-naushniki", + "parent_id": "naushniki", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki?recommended_by=listing", + "name": "Наушники - Все наушники", + "level": "3", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki?recommended_by=listing" + } + ], + "price_formatted": "14 990 ₽", + "price_full_formatted": "14 990.00 ₽", + "price": 14990, + "price_full": 14990, + "image_url": "https://api.technodom.kz/f3/api/v1/images/garnitura_nakladnaa_logitech_h_white_868_1.jpg", + "image_url_handle": "/f3/api/v1/images/garnitura_nakladnaa_logitech_h_white_868_1.jpg", + "image_url_resized": { + "120": "https://pictures.rees46.ru/resize-images/120/c1140c8254976de297c3caf971701a/131887.jpg", + "140": "https://pictures.rees46.ru/resize-images/140/c1140c8254976de297c3caf971701a/131887.jpg", + "160": "https://pictures.rees46.ru/resize-images/160/c1140c8254976de297c3caf971701a/131887.jpg", + "180": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/131887.jpg", + "200": "https://pictures.rees46.ru/resize-images/200/c1140c8254976de297c3caf971701a/131887.jpg", + "220": "https://pictures.rees46.ru/resize-images/220/c1140c8254976de297c3caf971701a/131887.jpg", + "310": "https://pictures.rees46.ru/resize-images/310/c1140c8254976de297c3caf971701a/131887.jpg", + "520": "https://pictures.rees46.ru/resize-images/520/c1140c8254976de297c3caf971701a/131887.jpg", + "original": "https://api.technodom.kz/f3/api/v1/images/garnitura_nakladnaa_logitech_h_white_868_1.jpg" + }, + "url_handle": "/p/garnitura-nakladnaa-logitech-h-white-868?recommended_by=listing", + "currency": "₽", + "_id": "131887", + "id": "868", + "stock_quantity": 999999, + "group_id": "_131887_" + } + ], + "price_range": { + "min": 190, + "max": 1863890 + }, + "price_ranges": [ + { + "to": 10000, + "count": 501 + }, + { + "from": 10000, + "to": 25000, + "count": 378 + }, + { + "from": 25000, + "to": 50000, + "count": 415 + } + ], + "price_median": 35000, + "filters": { + "NFC": { + "count": 6, + "values": { + "Нет": 6 + } + }, + "has_gift": { + "count": 81, + "values": { + "1": 81 + }, + "ranges": { + "min": 1, + "max": 1 + } + }, + "is_preorder": { + "count": 2320, + "values": { + "False": 2320 + } + } + }, + "brands": [ + { + "name": "A-Case", + "count": 1 + }, + { + "name": "ACEFAST", + "count": 21 + }, + { + "name": "AULA", + "count": 3 + } + ], + "categories": [ + { + "id": "smartfony-i-gadzhety", + "name": "Смартфоны и гаджеты", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety?recommended_by=listing", + "url_handle": "/catalog/smartfony-i-gadzhety?recommended_by=listing", + "count": 2320 + }, + { + "id": "brendy", + "name": "Бренды", + "url": "https://www.technodom.kz/catalog/brendy?recommended_by=listing", + "url_handle": "/catalog/brendy?recommended_by=listing", + "count": 77 + }, + { + "id": "tv-audio-foto-video", + "name": "ТВ, аудио, фото, видео", + "url": "https://www.technodom.kz/catalog/tv-audio-foto-video?recommended_by=listing", + "url_handle": "/catalog/tv-audio-foto-video?recommended_by=listing", + "count": 21 + } + ] +} \ No newline at end of file diff --git a/test/fixtures/popups_v3/breakpoints.json b/test/fixtures/popups_v3/breakpoints.json new file mode 100644 index 0000000..a7b3669 --- /dev/null +++ b/test/fixtures/popups_v3/breakpoints.json @@ -0,0 +1,91 @@ +{ + "_fixture": { + "about": "Переопределения рамки для экранов уже mediaMaxWidth (логические px = dp/pt). Применяются все подходящие, от широкого к узкому (узкий побеждает) — так ведёт себя CSS при порядке 768 → 400. Порядок в массиве и сортировку у компилятора уточнить.", + "expect": { + "screen_390": { + "width": 390, + "maxWidth": null, + "padding": 12, + "borderRadius": 0, + "minHeight": 120 + }, + "screen_414": { + "width": 331.2, + "maxWidth": 480, + "padding": 20, + "borderRadius": 16 + }, + "screen_800": { + "width": 480, + "padding": 20, + "borderRadius": 16, + "note": "92% от 800 = 736 → maxWidth 480" + } + } + }, + "id": 9301, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20, + "breakpoints": [ + { + "mediaMaxWidth": 768, + "width": 80, + "widthMode": "%" + }, + { + "mediaMaxWidth": "400", + "width": 100, + "widthMode": "%", + "maxWidth": null, + "maxWidthMode": "none", + "padding": 12, + "borderRadius": 0, + "minHeight": 120 + } + ] + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Ширина зависит от экрана" + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/element-box.json b/test/fixtures/popups_v3/element-box.json new file mode 100644 index 0000000..54aa99a --- /dev/null +++ b/test/fixtures/popups_v3/element-box.json @@ -0,0 +1,87 @@ +{ + "_fixture": { + "about": "Элемент box: как text, но со своими DEFAULTS; пустой box — цветная плашка без текста.", + "expect": { + "el-box-defaults": { + "bgColor": "#f8fafcff", + "borderRadius": 12, + "paddingX": 16, + "paddingY": 16, + "fontSize": "как у text: messageFontSize → fontSize → 12 (у box нет fontSize в DEFAULTS)" + }, + "el-box-empty": { + "bgColor": "#eef2ffff", + "borderRadius": 20, + "paddingX": 24, + "paddingY": 24, + "text": null + } + } + }, + "id": 9102, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-box-defaults", + "type": "box", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Контейнер со стилями по умолчанию" + } + }, + { + "id": "el-box-empty", + "type": "box", + "rowId": "row-1", + "partIndex": 0, + "style": { + "bgColor": "#eef2ff", + "paddingX": 24, + "paddingY": 24, + "borderRadius": "20" + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/element-button.json b/test/fixtures/popups_v3/element-button.json new file mode 100644 index 0000000..acd4d75 --- /dev/null +++ b/test/fixtures/popups_v3/element-button.json @@ -0,0 +1,213 @@ +{ + "_fixture": { + "about": "Элемент button: действия link/close/copy, переменные в ссылке, платформенные ссылки, старый buttonHref, умолчания. Клик по link/copy — событие click, по close — close.", + "expect": { + "el-btn-link": { + "action": "link", + "spans": [ + { + "text": "Купить", + "bold": true + }, + { + "text": " со скидкой" + } + ], + "align": "left", + "bgColor": "#16a34aff", + "textColor": "#ffffffff", + "fontSize": 16, + "radius": 12, + "paddingX": 24, + "paddingY": 12, + "href": { + "ios": "rees46demo://sale?from=ios", + "android": "rees46demo://sale?from=android", + "rule": "ПРЕДЛОЖЕНИЕ, ждёт подтверждения бэка: для {{key}} сначала key_ios / key_android, потом key" + }, + "event": "click" + }, + "el-btn-ios-var": { + "href": "rees46demo://catalog?from=ios_var", + "note": "обычная переменная: на Android тоже откроется ios_link — так задумано в ТЗ?" + }, + "el-btn-close": { + "action": "close", + "event": "close" + }, + "el-btn-copy": { + "action": "copy", + "clipboard": "SALE10", + "event": "click" + }, + "el-btn-copy-fallback": { + "action": "copy", + "clipboard": "SALE20", + "note": "copyText пуст → текст кнопки как есть (вместе с разметкой, как в web)" + }, + "el-btn-legacy-href": { + "action": "link", + "href": "https://demo.rees46.ru" + }, + "el-btn-defaults": { + "action": "link", + "text": "Подробнее (локализованный текст по умолчанию)", + "align": "center", + "bgColor": "#2563ebff", + "textColor": "#ffffffff", + "fontSize": 14, + "paddingX": 20, + "paddingY": 10, + "radius": 10, + "href": null, + "note": "без ссылки нажатие ничего не открывает; событие click всё равно уходит" + }, + "el-btn-unknown-action": { + "action": "link", + "href": "https://demo.rees46.ru" + } + } + }, + "id": 9103, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-btn-link", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": { + "buttonText": "**Купить** со скидкой", + "buttonAction": "link", + "linkHref": "{{link}}", + "buttonAlign": "left", + "buttonBgColor": "#16a34a", + "buttonTextColor": "#ffffff", + "buttonFontSize": "16", + "buttonRadius": 12, + "buttonPaddingX": 24, + "buttonPaddingY": "12", + "fontFamily": "Inter" + } + }, + { + "id": "el-btn-ios-var", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": { + "buttonText": "Каталог", + "buttonAction": "link", + "linkHref": "{{ios_link}}" + } + }, + { + "id": "el-btn-close", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": { + "buttonText": "Не сейчас", + "buttonAction": "close", + "buttonBgColor": "transparent", + "buttonTextColor": "#71717a" + } + }, + { + "id": "el-btn-copy", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": { + "buttonText": "Скопировать код", + "buttonAction": "copy", + "copyText": "SALE10" + } + }, + { + "id": "el-btn-copy-fallback", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": { + "buttonText": "SALE20", + "buttonAction": "copy", + "copyText": "" + } + }, + { + "id": "el-btn-legacy-href", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": { + "buttonText": "Старый документ", + "buttonHref": "https://demo.rees46.ru" + } + }, + { + "id": "el-btn-defaults", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": {} + }, + { + "id": "el-btn-unknown-action", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": { + "buttonText": "?", + "buttonAction": "share", + "linkHref": "https://demo.rees46.ru" + } + } + ], + "variables": { + "link": "https://demo.rees46.ru/sale", + "link_ios": "rees46demo://sale?from=ios", + "link_android": "rees46demo://sale?from=android", + "ios_link": "rees46demo://catalog?from=ios_var" + } + } +} diff --git a/test/fixtures/popups_v3/element-close.json b/test/fixtures/popups_v3/element-close.json new file mode 100644 index 0000000..fdff981 --- /dev/null +++ b/test/fixtures/popups_v3/element-close.json @@ -0,0 +1,134 @@ +{ + "_fixture": { + "about": "Элемент close: text (по умолчанию ×), image, svg; размер иконки 8–128.", + "expect": { + "el-close-default": { + "mode": "text", + "text": "×", + "align": "right", + "bgColor": "#00000000", + "textColor": "#71717aff", + "fontSize": 22, + "paddingX": 8, + "paddingY": 2, + "radius": 999, + "event": "close" + }, + "el-close-text": { + "mode": "text", + "text": "Закрыть ×", + "align": "left", + "fontSize": 16 + }, + "el-close-image": { + "mode": "image", + "url": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "size": 128, + "note": "200 → 128" + }, + "el-close-svg": { + "mode": "svg", + "size": 8, + "note": "4 → 8. Скрипты и on*-атрибуты вырезать. Допустимо нарисовать стандартный крестик" + } + } + }, + "id": 9104, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "right", + "verticalAlign": "top" + } + ], + "gap": 4, + "minHeight": 0 + }, + { + "id": "row-2", + "columns": [ + 34, + 33, + 33 + ], + "gap": 4, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-close-default", + "type": "close", + "rowId": "row-1", + "partIndex": 0, + "style": {} + }, + { + "id": "el-close-text", + "type": "close", + "rowId": "row-2", + "partIndex": 0, + "style": { + "closeIconMode": "text", + "buttonText": "Закрыть ×", + "buttonAlign": "left", + "buttonTextColor": "#ef4444", + "buttonFontSize": "16" + } + }, + { + "id": "el-close-image", + "type": "close", + "rowId": "row-2", + "partIndex": 1, + "style": { + "closeIconMode": "image", + "imageUrl": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "imageAlt": "Закрыть", + "closeIconSize": "200" + } + }, + { + "id": "el-close-svg", + "type": "close", + "rowId": "row-2", + "partIndex": 2, + "style": { + "closeIconMode": "svg", + "closeSvg": "", + "closeIconSize": "4" + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/element-email-collector.json b/test/fixtures/popups_v3/element-email-collector.json new file mode 100644 index 0000000..47d83c9 --- /dev/null +++ b/test/fixtures/popups_v3/element-email-collector.json @@ -0,0 +1,170 @@ +{ + "_fixture": { + "about": "Форма подписки: inline/stacked, согласие обязательно, флаги согласий, старые поля, сегмент, экран успеха.", + "expect": { + "el-email-inline": { + "layout": "inline", + "consentFields": [ + "email_bulk", + "email_chain" + ], + "consentRequired": true, + "consentSpans": [ + { + "text": "Согласен получать " + }, + { + "text": "рассылку", + "italic": true + } + ], + "segmentId": "123", + "submit": { + "validation": "согласие отмечено и email по формату; иначе emailErrorMessage", + "calls": [ + "подписка email + флаги email_bulk, email_chain = true (транспорт — решение №8)", + "segments/add segment_id=123 после успешной подписки" + ], + "events": [ + { + "event": "subscribe", + "channel": "email" + }, + { + "event": "submit" + } + ] + }, + "success": { + "title": "Готово!", + "message": "Проверьте почту", + "bg": "#ecfdf5ff", + "align": "left" + } + }, + "el-email-stacked-legacy": { + "layout": "stacked", + "consentFields": [ + "email_transactional" + ], + "consentLabel": "Согласен на письма о заказах", + "note": "любое значение emailLayout, кроме inline, — колонкой (в доке — column, в ТЗ — stacked)" + }, + "el-email-bare": { + "layout": "stacked", + "consentFields": [ + "email_bulk", + "email_chain", + "email_transactional" + ], + "texts": "placeholder «Email», кнопка «Подписаться», согласие и ошибка — локализованные по умолчанию", + "note": "без emailLayout — колонкой; DEFAULTS редактора дали бы inline + email_bulk. Документы из редактора всегда несут DEFAULTS — уточнить у бэка" + } + } + }, + "id": 9106, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "gap": 12, + "minHeight": 0 + }, + { + "id": "row-2", + "columns": [ + 100 + ], + "gap": 12, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-email-inline", + "type": "emailCollector", + "rowId": "row-1", + "partIndex": 0, + "style": { + "emailLayout": "inline", + "emailPlaceholder": "Ваш email", + "emailSubmitText": "**Подписаться**", + "emailConsentLabel": "Согласен получать *рассылку*", + "emailConsentFields": [ + "email_bulk", + "email_chain", + "sms_bulk" + ], + "emailSegmentId": "123", + "emailErrorMessage": "Проверьте email", + "emailSuccessTitle": "Готово!", + "emailSuccessMessage": "Проверьте почту", + "emailSuccessBg": "#ecfdf5", + "emailSuccessColor": "#065f46", + "emailSuccessAlign": "left", + "emailSuccessRadius": 12, + "emailSuccessPaddingX": 14, + "emailSuccessPaddingY": 16, + "emailSuccessTitleColor": "#047857", + "emailSuccessTitleFontSize": 18, + "emailSuccessFontSize": 13, + "emailInputBg": "#ffffff", + "emailInputColor": "#0f172a", + "emailInputBorderColor": "#cbd5e1", + "emailInputRadius": 10, + "buttonBgColor": "#2563eb", + "buttonTextColor": "#ffffff" + } + }, + { + "id": "el-email-stacked-legacy", + "type": "emailCollector", + "rowId": "row-2", + "partIndex": 0, + "style": { + "emailLayout": "stacked", + "emailConsents": [ + { + "field": "email_transactional", + "label": "Согласен на письма о заказах" + } + ] + } + }, + { + "id": "el-email-bare", + "type": "emailCollector", + "rowId": "row-2", + "partIndex": 0, + "style": {} + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/element-form.json b/test/fixtures/popups_v3/element-form.json new file mode 100644 index 0000000..dd85e7e --- /dev/null +++ b/test/fixtures/popups_v3/element-form.json @@ -0,0 +1,243 @@ +{ + "_fixture": { + "about": "Форма профиля: нормализация полей как в компиляторе (Form#normalized_fields), до 8 полей, custom → свойство клиента, согласие, сегмент.", + "expect": { + "el-form": { + "fields": [ + { + "id": "f-email", + "kind": "email", + "required": true, + "propertyKey": "", + "input": "email" + }, + { + "id": "f-phone", + "kind": "phone", + "required": false, + "propertyKey": "", + "input": "phone" + }, + { + "id": "ffirst", + "kind": "first_name", + "required": false, + "propertyKey": "", + "input": "text", + "note": "required только при true (булевом); id очищен до [A-Za-z0-9_-]" + }, + { + "id": "field-3", + "kind": "last_name", + "required": false, + "propertyKey": "", + "input": "text" + }, + { + "id": "f-bday", + "kind": "birthday", + "required": false, + "propertyKey": "", + "input": "date", + "wire": "YYYY-MM-DD" + }, + { + "id": "f-gender", + "kind": "gender", + "required": false, + "propertyKey": "", + "input": "select m/f", + "options": [ + "Мужской → m", + "Женский → f" + ] + }, + { + "id": "f-color", + "kind": "custom", + "required": false, + "propertyKey": "fav_color", + "input": "text" + }, + { + "id": "f-level", + "kind": "custom", + "required": false, + "propertyKey": "loyaltylevel", + "input": "text" + } + ], + "dropped": [ + "f-address (неизвестный kind)", + "f-ninth (больше 8)", + "не объект" + ], + "consentFields": [ + "email_bulk" + ], + "consentRequired": false, + "segmentId": "456", + "submit": { + "profile_set_example": { + "email": "anna@example.com", + "phone": "+79990000000", + "first_name": "Анна", + "last_name": "Иванова", + "birthday": "1990-04-12", + "gender": "f", + "fav_color": "зелёный", + "loyaltylevel": "gold" + }, + "then": [ + "флаги formConsentFields = true, если согласие отмечено (транспорт — решение №8)", + "segments/add segment_id=456" + ], + "events": [ + { + "event": "submit" + } + ], + "note": "пустые необязательные поля не отправлять; id поля «field-3» — индекс после фильтра" + } + }, + "el-form-bare": { + "fields": [], + "note": "без formFields компилятор не рисует ни одного поля (DEFAULTS редактора дали бы одно поле email); formConsentFields пуст → флагов нет (в отличие от emailCollector, где пусто = все три)" + } + } + }, + "id": 9107, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-form", + "type": "form", + "rowId": "row-1", + "partIndex": 0, + "style": { + "formFields": [ + { + "id": "f-email", + "kind": "email", + "label": "Email", + "placeholder": "you@example.com", + "required": true + }, + { + "id": "f-phone", + "kind": "phone", + "label": "Телефон", + "placeholder": "+7…", + "required": false + }, + { + "id": "f first!", + "kind": "first_name", + "label": "Имя", + "required": "true" + }, + { + "id": "", + "kind": "last_name", + "label": "Фамилия" + }, + { + "id": "f-bday", + "kind": "birthday", + "label": "Дата рождения" + }, + { + "id": "f-gender", + "kind": "gender", + "label": "Пол" + }, + { + "id": "f-address", + "kind": "address", + "label": "Адрес" + }, + { + "id": "f-color", + "kind": "custom", + "label": "Любимый **цвет**", + "propertyKey": "Fav_Color!" + }, + { + "id": "f-level", + "kind": "custom", + "label": "Уровень", + "propertyKey": "loyalty-level" + }, + { + "id": "f-ninth", + "kind": "custom", + "label": "Девятое поле", + "propertyKey": "ninth" + }, + "not an object" + ], + "formConsentLabel": "Согласен на обработку данных", + "formConsentFields": [ + "email_bulk" + ], + "formSegmentId": " 456 ", + "formSubmitText": "Сохранить", + "formErrorMessage": "Заполните обязательные поля", + "formSuccessTitle": "Спасибо!", + "formSuccessMessage": "Данные сохранены", + "formInputBg": "#f8fafc", + "formInputColor": "#0f172a", + "formInputBorderColor": "#cbd5e1", + "formInputRadius": 10 + } + }, + { + "id": "el-form-bare", + "type": "form", + "rowId": "row-1", + "partIndex": 0, + "style": {} + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/element-image.json b/test/fixtures/popups_v3/element-image.json new file mode 100644 index 0000000..1f4421e --- /dev/null +++ b/test/fixtures/popups_v3/element-image.json @@ -0,0 +1,174 @@ +{ + "_fixture": { + "about": "Элемент image: переменные в URL, режимы высоты, object-fit, соотношение сторон, скрытие, ссылка.", + "expect": { + "el-img-auto": { + "url": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "height": "auto", + "fit": "cover", + "radius": 12, + "marginBottom": 8, + "width": "ширина ячейки", + "link": "https://demo.rees46.ru/product/141206" + }, + "el-img-px": { + "height": { + "px": 180 + }, + "fit": "contain" + }, + "el-img-percent": { + "height": { + "percent": 100 + }, + "note": "150 → 100 (clamp 1..100); % — от чего на mobile, уточнить (предложение: от высоты экрана)" + }, + "el-img-vh": { + "height": { + "vh": 40 + }, + "note": "null → 40" + }, + "el-img-ratio": { + "aspectRatio": 1.7778, + "fit": "cover" + }, + "el-img-bad-ratio": { + "aspectRatio": null, + "fit": "cover" + }, + "el-img-hidden": { + "rendered": false + } + } + }, + "id": 9105, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 50, + 50 + ], + "gap": 8, + "minHeight": 0 + }, + { + "id": "row-2", + "columns": [ + 100 + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-img-auto", + "type": "image", + "rowId": "row-1", + "partIndex": 0, + "style": { + "imageUrl": "{{banner}}", + "imageAlt": "Баннер", + "imageRadius": 12, + "imageMarginBottom": "8", + "linkHref": "https://demo.rees46.ru/product/141206" + } + }, + { + "id": "el-img-px", + "type": "image", + "rowId": "row-1", + "partIndex": 1, + "style": { + "imageUrl": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/434529932.jpg", + "imageHeightMode": "px", + "imageHeight": "180", + "imageObjectFit": "contain" + } + }, + { + "id": "el-img-percent", + "type": "image", + "rowId": "row-2", + "partIndex": 0, + "style": { + "imageUrl": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "imageHeightMode": "%", + "imageHeight": 150 + } + }, + { + "id": "el-img-vh", + "type": "image", + "rowId": "row-2", + "partIndex": 0, + "style": { + "imageUrl": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "imageHeightMode": "vh", + "imageHeight": null + } + }, + { + "id": "el-img-ratio", + "type": "image", + "rowId": "row-2", + "partIndex": 0, + "style": { + "imageUrl": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "imageAspectRatio": "16 / 9", + "imageObjectFit": "cover" + } + }, + { + "id": "el-img-bad-ratio", + "type": "image", + "rowId": "row-2", + "partIndex": 0, + "style": { + "imageUrl": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "imageAspectRatio": "wide", + "imageObjectFit": "stretch" + } + }, + { + "id": "el-img-hidden", + "type": "image", + "rowId": "row-2", + "partIndex": 0, + "style": { + "imageUrl": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "showImage": false + } + } + ], + "variables": { + "banner": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg" + } + } +} diff --git a/test/fixtures/popups_v3/element-promo-code.json b/test/fixtures/popups_v3/element-promo-code.json new file mode 100644 index 0000000..5fbf7ab --- /dev/null +++ b/test/fixtures/popups_v3/element-promo-code.json @@ -0,0 +1,126 @@ +{ + "_fixture": { + "about": "Промокод: personal (код до показа из promo_code_list_id) и static; копирование, ссылка применения.", + "expect": { + "before_show": { + "request": "GET https://api.rees46.ru/promo_codes/fetch?shop_id&did&sid&id=7", + "no_code": "попап не показывать, событие show не отправлять", + "needs_code": "promo_code_list_id задан И в design есть {{promo_code}} или promoCode с promoSource != static" + }, + "el-promo-personal": { + "code": "{{promo_code}} → код из ответа", + "align": "left", + "fontSize": 22, + "font": "моноширинный, жирный, letterSpacing 1", + "copy": { + "clipboard": "код", + "text_after": "Скопировано!", + "event": "click", + "then_open": "rees46demo://cart?promo=<код>" + } + }, + "el-promo-static": { + "code": "WELCOME5", + "copyButton": false + }, + "el-text-with-code": { + "spans_after_substitution_example": [ + { + "text": "Код " + }, + { + "text": "ABC123", + "bold": true + }, + { + "text": " действует 7 дней" + } + ] + } + } + }, + "id": 9108, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": 7, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-promo-personal", + "type": "promoCode", + "rowId": "row-1", + "partIndex": 0, + "style": { + "promoSource": "personal", + "promoLabel": "Ваш персональный промокод:", + "promoShowCopy": true, + "promoCopyText": "Копировать", + "promoCopiedText": "Скопировано!", + "promoApplyHref": "rees46demo://cart?promo={{promo_code}}", + "promoCodeBg": "#fef3c7", + "promoCodeColor": "#92400e", + "promoCodeFontSize": "22", + "promoCodeRadius": 10, + "messageAlign": "left" + } + }, + { + "id": "el-promo-static", + "type": "promoCode", + "rowId": "row-1", + "partIndex": 0, + "style": { + "promoSource": "static", + "promoStaticCode": " WELCOME5 ", + "promoShowCopy": false + } + }, + { + "id": "el-text-with-code", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Код **{{promo_code}}** действует 7 дней" + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/element-recommendation.json b/test/fixtures/popups_v3/element-recommendation.json new file mode 100644 index 0000000..ba9a714 --- /dev/null +++ b/test/fixtures/popups_v3/element-recommendation.json @@ -0,0 +1,82 @@ +{ + "_fixture": { + "about": "Блок рекомендаций: товары по коду блока, горизонтальная лента, placeholder до загрузки. Код — живой блок «Популярные» демо-магазина.", + "expect": { + "el-rec": { + "code": "e6249bb15043644bf25b135006149962", + "layout": "горизонтальная лента карточек кита", + "placeholder_minHeight": 40, + "box": "фон прозрачный, без рамки, отступов и тени — как Recommendation#box_declarations", + "click": "обычный клик по рекомендации (источник dynamic/код блока) + событие click попапа (уточнить у бэка)" + }, + "el-rec-empty": { + "rendered": false + } + } + }, + "id": 9110, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-rec", + "type": "recommendation", + "rowId": "row-1", + "partIndex": 0, + "style": { + "recommenderCode": "e6249bb15043644bf25b135006149962", + "bgColor": "#ffffff", + "paddingX": 16 + } + }, + { + "id": "el-rec-empty", + "type": "recommendation", + "rowId": "row-1", + "partIndex": 0, + "style": { + "recommenderCode": " " + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/element-survey.json b/test/fixtures/popups_v3/element-survey.json new file mode 100644 index 0000000..584a99d --- /dev/null +++ b/test/fixtures/popups_v3/element-survey.json @@ -0,0 +1,180 @@ +{ + "_fixture": { + "about": "Мини-опрос NPS/CSAT/CES: шкала, комментарий после оценки, отправка, «спасибо». Коды кампаний — живые у демо-магазина (nps/categories: test, csat/campaigns: MNTEST, ces/campaigns: «MN TEST»).", + "expect": { + "el-survey-nps": { + "scale": [ + 0, + 10 + ], + "flow": "оценка → поле комментария и кнопка → отправка → surveyThanksText", + "request": { + "url": "POST https://app.rees46.ru/api/v3/polls/nps/reviews", + "body": { + "shop_id": "c1140c8254976de297c3caf971701a", + "did": "", + "sid": "", + "channel": "popup", + "category": "test", + "rate": 0, + "comment": "<если введён>" + } + }, + "events": [ + { + "event": "submit" + } + ], + "note": "rate 0 допустим; старые review() на iOS и RN отклоняют 0 — нужен v3 или правка" + }, + "el-survey-csat": { + "scale": [ + 1, + 5 + ], + "request_body_key": { + "campaign": "MNTEST" + }, + "defaults": { + "submit": "Отправить", + "thanks": "Спасибо!", + "scaleBg": "#f3f4f6ff", + "activeBg": "#2563ebff" + } + }, + "el-survey-ces": { + "scale": [ + 1, + 7 + ], + "request_body_key": { + "campaign": "MN TEST" + } + }, + "el-survey-unknown": { + "type": "nps", + "scale": [ + 0, + 10 + ] + }, + "blocker": "канал popup должен существовать у магазина (Опросы → Настройки → Каналы), иначе 404 «Channel not found». У демо-магазина сейчас только канал test" + } + }, + "id": 9109, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "gap": 8, + "minHeight": 0 + }, + { + "id": "row-2", + "columns": [ + 100 + ], + "gap": 8, + "minHeight": 0 + }, + { + "id": "row-3", + "columns": [ + 100 + ], + "gap": 8, + "minHeight": 0 + }, + { + "id": "row-4", + "columns": [ + 100 + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-survey-nps", + "type": "survey", + "rowId": "row-1", + "partIndex": 0, + "style": { + "surveyType": "nps", + "surveyCampaignId": "1", + "surveyCampaignCode": "test", + "surveyQuestion": "Порекомендуете нас **друзьям**?", + "surveyMinLabel": "Точно нет", + "surveyMaxLabel": "Обязательно", + "surveyCommentPlaceholder": "Что можно улучшить?", + "surveySubmitText": "Отправить", + "surveyThanksText": "Спасибо за *оценку*!", + "surveyScaleBg": "#f3f4f6", + "surveyScaleColor": "#111827", + "surveyScaleActiveBg": "#2563eb", + "surveyScaleActiveColor": "#ffffff" + } + }, + { + "id": "el-survey-csat", + "type": "survey", + "rowId": "row-2", + "partIndex": 0, + "style": { + "surveyType": "csat", + "surveyCampaignCode": "MNTEST", + "surveyQuestion": "Как вам заказ?" + } + }, + { + "id": "el-survey-ces", + "type": "survey", + "rowId": "row-3", + "partIndex": 0, + "style": { + "surveyType": "ces", + "surveyCampaignCode": "MN TEST", + "surveyQuestion": "Легко ли было оформить заказ?" + } + }, + { + "id": "el-survey-unknown", + "type": "survey", + "rowId": "row-4", + "partIndex": 0, + "style": { + "surveyType": "star", + "surveyCampaignCode": "test" + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/element-text.json b/test/fixtures/popups_v3/element-text.json new file mode 100644 index 0000000..1146df2 --- /dev/null +++ b/test/fixtures/popups_v3/element-text.json @@ -0,0 +1,145 @@ +{ + "_fixture": { + "about": "Элемент text: разметка, выравнивание, числа строками и null, общие стили, ссылка на весь элемент, CSS-позиционирование.", + "expect": { + "el-text-full": { + "spans": [ + { + "text": "Скидка 10%", + "bold": true + }, + { + "text": " на всё\nдо конца недели" + } + ], + "align": "center", + "fontSize": 20, + "fontWeight": 700, + "lineHeight": 1.4, + "letterSpacing": 0.5, + "opacity": 0.9, + "paddingX": 8, + "paddingY": 0, + "textColor": "#111827ff", + "bgColor": "#00000000", + "borderColor": "#1118271a", + "shadow": { + "y": 2, + "blur": 8, + "color": "#00000055" + }, + "link": "https://demo.rees46.ru/sale", + "note": "shadowColor: к шестизначному hex компилятор дописывает альфу 55 (Context#shadow_color)" + }, + "el-text-bare": { + "defaults": "DEFAULTS типа text (fontSize 16, bgColor transparent, messageAlign left), затем запасные box_declarations: textColor #111827, fontWeight 500, lineHeight 1.35, padding 0, border 0", + "fontSize": 16, + "bgColor": "#00000000", + "align": "left", + "textColor": "#111827ff", + "fontWeight": 500, + "lineHeight": 1.35 + }, + "el-text-css-position": { + "rendered": true, + "note": "cssPosition/pos*/positionZIndex на mobile не поддерживаем, элемент остаётся в потоке ячейки" + } + } + }, + "id": 9101, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "el-text-full", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "**Скидка 10%** на всё\nдо конца недели", + "messageAlign": "center", + "messageFontSize": "20", + "messageFontWeight": 700, + "textColor": "#111827", + "bgColor": "transparent", + "paddingX": "8", + "paddingY": null, + "lineHeight": "1.4", + "letterSpacing": 0.5, + "opacity": "0.9", + "shadowY": 2, + "shadowBlur": 8, + "shadowColor": "#000000", + "borderWidth": 1, + "borderColor": "rgba(17, 24, 39, 0.1)", + "borderRadius": 8, + "linkHref": "https://demo.rees46.ru/sale", + "linkTarget": "_blank", + "cellAlign": "center" + } + }, + { + "id": "el-text-bare", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Текст без стилей" + } + }, + { + "id": "el-text-css-position", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "CSS-позиционирование игнорируется", + "cssPosition": "absolute", + "posTop": 10, + "posRight": 10, + "posUnit": "px", + "positionZIndex": 5 + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/empty-design.json b/test/fixtures/popups_v3/empty-design.json new file mode 100644 index 0000000..df8bf5f --- /dev/null +++ b/test/fixtures/popups_v3/empty-design.json @@ -0,0 +1,46 @@ +{ + "_fixture": { + "about": "Пустой дизайн нового попапа (EMPTY_DESIGN).", + "expect": { + "frame": { + "width": "92%", + "maxWidth": 480, + "heightMode": "auto", + "bgColor": "#ffffffff", + "border": "1 #e5e7eb", + "radius": 16, + "padding": 20 + }, + "show": "предложение: пустой попап не показывать и логировать (иначе пустая рамка)" + } + }, + "id": 9306, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [], + "elements": [], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/error-responses.json b/test/fixtures/popups_v3/error-responses.json new file mode 100644 index 0000000..265d7df --- /dev/null +++ b/test/fixtures/popups_v3/error-responses.json @@ -0,0 +1,56 @@ +{ + "_fixture": { + "about": "Ответы ошибок API попапов. Список: 4xx кешируем как пустой на ttl по умолчанию (300 с), сеть/5xx — не кешируем. События: 429 — пауза отправки, остальное не повторяем." + }, + "list_400": { + "status": "fail", + "message": "Invalid request parameters" + }, + "list_402": { + "status": "fail", + "message": "Payment required" + }, + "list_403": { + "status": "fail", + "message": "Access denied" + }, + "list_404": { + "status": "fail", + "message": "Resource not found" + }, + "one_404": { + "status": "fail", + "message": "Resource not found" + }, + "events_400_channel": { + "status": "fail", + "message": "Invalid request parameters", + "note": "channel = mobile/web → 400; channel только у subscribe" + }, + "events_429": { + "status": "fail", + "message": "Too many requests" + }, + "events_ok": { + "status": "success" + }, + "promo_404": { + "status": "error", + "message": "Promo codes list is not found" + }, + "promo_ok": { + "code": "ABC123" + }, + "review_404_channel": { + "status": "fail", + "message": "Channel not found" + }, + "review_ok": { + "status": "success", + "payload": { + "review": { + "id": 1 + } + } + } +} diff --git a/test/fixtures/popups_v3/grid.json b/test/fixtures/popups_v3/grid.json new file mode 100644 index 0000000..ac60890 --- /dev/null +++ b/test/fixtures/popups_v3/grid.json @@ -0,0 +1,297 @@ +{ + "_fixture": { + "about": "Сетка: доли колонок в процентах и старый parts, выравнивание ячейки → строки → left/top, порядок элементов, отступы, minHeight, фон строки, выпадающие элементы.", + "expect": { + "rows_gap": 8, + "rows": { + "row-a": { + "fractions": [ + 0.5, + 0.5 + ], + "gap": 12, + "minHeight": 80, + "cells": [ + { + "align": "left", + "verticalAlign": "top", + "elements": [ + "a0-1", + "a0-2", + "a0-3" + ] + }, + { + "align": "center", + "verticalAlign": "center", + "elements": [ + "a1" + ] + } + ] + }, + "row-b": { + "fractions": [ + 0.3333, + 0.3333, + 0.3333 + ], + "gap": 8, + "minHeight": 60, + "cells": [ + { + "align": "right", + "verticalAlign": "bottom", + "elements": [ + "b0" + ] + }, + { + "align": "right", + "verticalAlign": "bottom", + "elements": [] + }, + { + "align": "right", + "verticalAlign": "top", + "elements": [ + "b2" + ], + "note": "элемент с cellVerticalAlign: ячейка становится flex-start, элемент сам выбирает вертикаль (точная CSS-механика в Base не видна — уточнить)" + } + ] + }, + "row-c": { + "fractions": [ + 0.25, + 0.75 + ], + "gap": 8, + "minHeight": 110, + "background": { + "color": "#fef3c7ff", + "image": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "size": "contain", + "position": "top", + "repeat": "repeat-x" + }, + "cells": [ + { + "align": "left", + "verticalAlign": "top", + "elements": [] + }, + { + "align": "left", + "verticalAlign": "top", + "elements": [ + "c1" + ], + "note": "c1 сам прижат вправо (cellAlign)" + } + ] + }, + "row-d": { + "fractions": [ + 0.1, + 0.1, + 0.2, + 0.2, + 0.2, + 0.2 + ], + "gap": 4, + "minHeight": 0, + "cells": "6 ячеек, d5 в последней" + } + }, + "dropped": [ + "orphan", + "out-of-range" + ], + "note": "minHeight без значения = 110 (компилятор). Строки идут столбиком с промежутком 8. Строка обрезает содержимое (overflow hidden)." + } + }, + "id": 9111, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-a", + "columns": [ + 50, + 50 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + }, + { + "align": "center", + "verticalAlign": "center" + } + ], + "gap": 12, + "minHeight": "80" + }, + { + "id": "row-b", + "parts": 3, + "align": "right", + "verticalAlign": "bottom", + "gap": null, + "minHeight": 60 + }, + { + "id": "row-c", + "columns": [ + 25, + 75 + ], + "cells": [ + {}, + { + "align": "nonsense" + } + ], + "minHeight": null, + "bgColor": "#fef3c7", + "bgImageUrl": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "bgSize": "contain", + "bgPosition": "top", + "bgRepeat": "repeat-x" + }, + { + "id": "row-d", + "columns": [ + 10, + 10, + 20, + 20, + 20, + 20 + ], + "gap": 4, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "a0-1", + "type": "text", + "rowId": "row-a", + "partIndex": 0, + "style": { + "message": "A0 первый" + } + }, + { + "id": "a0-2", + "type": "text", + "rowId": "row-a", + "partIndex": 0, + "style": { + "message": "A0 второй" + } + }, + { + "id": "a1", + "type": "button", + "rowId": "row-a", + "partIndex": "1", + "style": { + "buttonText": "A1" + } + }, + { + "id": "b0", + "type": "text", + "rowId": "row-b", + "partIndex": 0, + "style": { + "message": "B0" + } + }, + { + "id": "b2", + "type": "text", + "rowId": "row-b", + "partIndex": 2, + "style": { + "message": "B2 внизу", + "cellVerticalAlign": "top" + } + }, + { + "id": "c1", + "type": "text", + "rowId": "row-c", + "partIndex": 1, + "style": { + "message": "C1 справа", + "cellAlign": "right" + } + }, + { + "id": "d5", + "type": "box", + "rowId": "row-d", + "partIndex": 5, + "style": { + "message": "D5" + } + }, + { + "id": "orphan", + "type": "text", + "rowId": "row-missing", + "partIndex": 0, + "style": { + "message": "Нет такой строки" + } + }, + { + "id": "out-of-range", + "type": "text", + "rowId": "row-a", + "partIndex": 5, + "style": { + "message": "Колонки 5 в строке A нет" + } + }, + { + "id": "a0-3", + "type": "text", + "rowId": "row-a", + "partIndex": 0, + "style": { + "message": "A0 третий (порядок по массиву)" + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/layouts.json b/test/fixtures/popups_v3/layouts.json new file mode 100644 index 0000000..9c30b23 --- /dev/null +++ b/test/fixtures/popups_v3/layouts.json @@ -0,0 +1,328 @@ +{ + "_fixture": { + "about": "Макеты и рамка: banner top/bottom, modal, fullscreen; затемнение, блокировка фона, отступы баннера.", + "expect": { + "9201": { + "layout": "banner", + "placement": "top", + "overlay": false, + "touchesOutside": "проходят в приложение", + "insets": { + "x": 12, + "top": "16 от верхней безопасной зоны" + }, + "width": "экран − 2×12" + }, + "9202": { + "layout": "banner", + "placement": "bottom", + "overlay": { + "color": "#000000", + "opacity": 0.3 + }, + "lockBackgroundScroll": true, + "touchesOutside": "блокируются; тап по затемнению закрывает", + "insets": { + "x": 0, + "bottom": "0 от нижней безопасной зоны" + } + }, + "9203": { + "layout": "modal", + "overlay": "включено по умолчанию; цвет и прозрачность по умолчанию уточнить (предложение #000000, 0.5)", + "frame": { + "width": "92% экрана, не больше 480", + "minHeight": 200, + "radius": 16, + "padding": 20, + "border": "1 #e5e7eb" + }, + "close": "тап по затемнению, системное «назад» → событие close" + }, + "9204": { + "layout": "fullscreen", + "frame": "весь экран с учётом безопасных зон; width/height рамки игнорируются, радиус 0 (предложение — уточнить у бэка)", + "overlay": false + } + } + }, + "popups": [ + { + "id": 9201, + "layout": "banner", + "placement": "top", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 100, + "widthMode": "%", + "maxWidth": null, + "maxWidthMode": "none", + "heightMode": "auto", + "bgColor": "#111827", + "borderWidth": 0, + "borderRadius": 12, + "padding": 12, + "offsetX": 12, + "offsetY": "16" + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 80, + 20 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "center" + }, + { + "align": "right", + "verticalAlign": "center" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Бесплатная доставка от 3000 ₽", + "textColor": "#ffffff", + "bgColor": "transparent" + } + }, + { + "id": "x", + "type": "close", + "rowId": "row-1", + "partIndex": 1, + "style": { + "buttonTextColor": "#ffffff" + } + } + ], + "variables": {} + } + }, + { + "id": 9202, + "layout": "banner", + "placement": "bottom", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 100, + "widthMode": "%", + "maxWidth": null, + "maxWidthMode": "none", + "heightMode": "auto", + "bgColor": "#111827", + "borderWidth": 0, + "borderRadius": 12, + "padding": 12, + "offsetX": 0, + "offsetY": 0, + "overlayEnabled": true, + "overlayColor": "#000000", + "overlayOpacity": "0.3", + "lockBackgroundScroll": true + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 80, + 20 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "center" + }, + { + "align": "right", + "verticalAlign": "center" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Бесплатная доставка от 3000 ₽", + "textColor": "#ffffff", + "bgColor": "transparent" + } + }, + { + "id": "x", + "type": "close", + "rowId": "row-1", + "partIndex": 1, + "style": { + "buttonTextColor": "#ffffff" + } + } + ], + "variables": {} + } + }, + { + "id": 9203, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20, + "overlayEnabled": null, + "overlayColor": null, + "overlayOpacity": null, + "lockBackgroundScroll": true, + "minHeight": 200, + "minHeightMode": "px" + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Модальное окно" + } + }, + { + "id": "x", + "type": "close", + "rowId": "row-1", + "partIndex": 0, + "style": {} + } + ], + "variables": {} + } + }, + { + "id": 9204, + "layout": "fullscreen", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "bgColor": "#0f172a", + "padding": 24, + "borderRadius": 16, + "overlayEnabled": false, + "width": 92, + "widthMode": "%", + "heightMode": "px", + "height": 300 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "center", + "verticalAlign": "center" + } + ], + "gap": 16, + "minHeight": 400 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Полноэкранный", + "textColor": "#ffffff", + "bgColor": "transparent", + "messageFontSize": 28 + } + }, + { + "id": "b", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": { + "buttonText": "Закрыть", + "buttonAction": "close" + } + } + ], + "variables": {} + } + } + ] +} diff --git a/test/fixtures/popups_v3/legacy-free-elements.json b/test/fixtures/popups_v3/legacy-free-elements.json new file mode 100644 index 0000000..bd0d8af --- /dev/null +++ b/test/fixtures/popups_v3/legacy-free-elements.json @@ -0,0 +1,69 @@ +{ + "_fixture": { + "about": "Старый дизайн без rows: компилятор ставит элементы абсолютно по x/y. Предложение для mobile: в потоке, сверху вниз по y, при равном y — по x.", + "expect": { + "order": [ + "first", + "third", + "second" + ] + } + }, + "id": 9305, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [], + "elements": [ + { + "id": "second", + "type": "text", + "x": 20, + "y": 120, + "style": { + "message": "Второй по y" + } + }, + { + "id": "first", + "type": "text", + "x": 200, + "y": 10, + "style": { + "message": "Первый по y" + } + }, + { + "id": "third", + "type": "button", + "x": 0, + "y": 120, + "style": { + "buttonText": "Тот же y, левее" + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/list-response.json b/test/fixtures/popups_v3/list-response.json new file mode 100644 index 0000000..bdb2264 --- /dev/null +++ b/test/fixtures/popups_v3/list-response.json @@ -0,0 +1,513 @@ +{ + "_fixture": { + "about": "Ответ GET /api/v3/storefront/popups?channel=mobile&debug=1. ttl строкой, null в частоте и паузе.", + "expect": { + "ttl_seconds": 300, + "armed": [ + 512, + 513, + 514, + 515, + 519 + ], + "manual_only": [ + 516 + ], + "skipped_logged": { + "517": "неизвестный для mobile trigger_type", + "518": "неизвестный для mobile layout" + }, + "defaults": { + "516": { + "frequency": "once_session", + "target_screens": [] + }, + "515": { + "cooldown_minutes": 0 + } + }, + "excluded_logged_in_debug": [ + { + "id": 520, + "reason": "segments" + }, + { + "id": 521, + "reason": "period" + } + ], + "promo": { + "519": "promo_code_list_id есть, а {{promo_code}} в дизайне нет → код не запрашиваем" + } + } + }, + "status": "success", + "payload": { + "ttl": "300", + "popups": [ + { + "id": 512, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "app_start", + "trigger_value": null, + "trigger_event": null, + "frequency": "once_session", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Старт приложения" + } + } + ], + "variables": {} + } + }, + { + "id": 513, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "screen_open", + "trigger_value": null, + "trigger_event": null, + "frequency": "once_day", + "cooldown_minutes": 60, + "promo_code_list_id": null, + "target_screens": [ + "product", + "cart" + ], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Карточка или корзина" + } + } + ], + "variables": {} + } + }, + { + "id": 514, + "layout": "banner", + "placement": "bottom", + "selector": null, + "trigger_type": "time_on_screen", + "trigger_value": "10", + "trigger_event": null, + "frequency": "once_week", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [ + "home" + ], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "10 секунд на главной" + } + } + ], + "variables": {} + } + }, + { + "id": 515, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "track_event", + "trigger_value": null, + "trigger_event": "promo_view", + "frequency": "once_life", + "cooldown_minutes": null, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "После события" + } + } + ], + "variables": {} + } + }, + { + "id": 516, + "layout": "fullscreen", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": null, + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": null, + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Только вручную" + } + } + ], + "variables": {} + } + }, + { + "id": 517, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "scroll_percent", + "trigger_value": 50, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Web-триггер в mobile" + } + } + ], + "variables": {} + } + }, + { + "id": 518, + "layout": "bar", + "placement": "top", + "selector": null, + "trigger_type": "app_start", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Web-макет в mobile" + } + } + ], + "variables": {} + } + }, + { + "id": 519, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "app_start", + "trigger_value": null, + "trigger_event": null, + "frequency": "once_session", + "cooldown_minutes": 0, + "promo_code_list_id": 7, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Промокод" + } + } + ], + "variables": {} + } + } + ], + "excluded": [ + { + "id": 520, + "reason": "segments" + }, + { + "id": 521, + "reason": "period" + } + ] + } +} diff --git a/test/fixtures/popups_v3/live-list-181-182.json b/test/fixtures/popups_v3/live-list-181-182.json new file mode 100644 index 0000000..d25a9f2 --- /dev/null +++ b/test/fixtures/popups_v3/live-list-181-182.json @@ -0,0 +1 @@ +{"status":"success","payload":{"ttl":300,"popups":[{"id":181,"cooldown_minutes":0,"design":{"rows":[{"id":"row-mw0jzwms-c","gap":8,"align":"left","cells":[{}],"columns":[100],"minHeight":60,"verticalAlign":"top"}],"elements":[{"id":"el-mw0k0egu-h","type":"close","rowId":"row-mw0jzwms-c","style":{"buttonText":"×","buttonAlign":"right","buttonRadius":999,"buttonBgColor":"transparent","closeIconMode":"text","buttonFontSize":22,"buttonPaddingX":8,"buttonPaddingY":2,"buttonTextColor":"#71717a"},"partIndex":0},{"id":"el-mw0jzwms-d","type":"text","rowId":"row-mw0jzwms-c","style":{"bgColor":"transparent","message":"Test !@#%$%^&*","fontSize":16,"messageAlign":"left"},"partIndex":0},{"id":"el-mw0k0bwb-g","type":"button","rowId":"row-mw0jzwms-c","style":{"linkHref":"https://demo.rees46.ru/","buttonText":"Подробнее","buttonAlign":"center","buttonAction":"link","buttonRadius":10,"buttonBgColor":"#2563eb","buttonFontSize":14,"buttonPaddingX":20,"buttonPaddingY":10,"buttonTextColor":"#ffffff"},"partIndex":0},{"id":"el-mw0k0ny2-i","type":"image","rowId":"row-mw0jzwms-c","style":{"bgColor":"transparent","imageUrl":"https://storage.yandexcloud.net/r46v8/1/gallery/d664c5a6-ecf5-4db2-9e9c-b5dd1394d8e9.jpg","imageRadius":8,"imageObjectFit":"cover","imageHeightMode":"auto"},"partIndex":0},{"id":"el-mw0k1sro-k","type":"emailCollector","rowId":"row-mw0jzwms-c","style":{"emailLayout":"inline","borderRadius":12,"buttonBgColor":"#2563eb","buttonTextColor":"#ffffff","emailSubmitText":"Подписаться","emailPlaceholder":"Email","emailConsentLabel":"Согласен получать рассылки","emailErrorMessage":"Подтвердите согласие и введите корректный email","emailSuccessTitle":"Спасибо!","emailConsentFields":["email_bulk"],"emailSuccessMessage":"Вы подписаны на рассылку"},"partIndex":0},{"id":"el-mw0k3jw7-o","type":"survey","rowId":"row-mw0jzwms-c","style":{"surveyType":"nps","buttonBgColor":"#2563eb","surveyScaleBg":"#f3f4f6","surveyMaxLabel":"Очень вероятно","surveyMinLabel":"Маловероятно","surveyQuestion":"Насколько вероятно, что вы порекомендуете нас друзьям?","buttonTextColor":"#ffffff","surveyScaleColor":"#111827","surveySubmitText":"Отправить","surveyThanksText":"Спасибо за оценку!","surveyScaleActiveBg":"#2563eb","surveyScaleActiveColor":"#ffffff","surveyCommentPlaceholder":"Расскажите подробнее"},"partIndex":0}],"variables":{},"frameStyle":{"width":92,"height":320,"bgColor":"#ffffff","padding":20,"maxWidth":480,"widthMode":"%","heightMode":"auto","borderColor":"#e5e7eb","borderWidth":1,"borderRadius":16,"maxWidthMode":"px"}},"frequency":"once_session","layout":"banner","placement":"top","promo_code_list_id":null,"selector":null,"target_screens":[],"trigger_event":null,"trigger_type":"app_start","trigger_value":null},{"id":182,"cooldown_minutes":0,"design":{"rows":[{"id":"row-mw0k6x8e-q","gap":8,"align":"left","cells":[{}],"columns":[100],"minHeight":60,"verticalAlign":"top"}],"elements":[{"id":"el-mw0k6x8f-r","type":"promoCode","rowId":"row-mw0k6x8e-q","style":{"bgColor":"transparent","promoLabel":"Ваш промокод","promoCodeBg":"#fef3c7","promoSource":"static","messageAlign":"center","promoCopyText":"Скопировать","promoShowCopy":true,"promoCodeColor":"#92400e","promoCodeRadius":10,"promoCopiedText":"Скопировано","promoStaticCode":"Fix Test","promoCodeFontSize":20},"partIndex":0},{"id":"el-mw0k7wre-s","type":"survey","rowId":"row-mw0k6x8e-q","style":{"surveyType":"csat","buttonBgColor":"#2563eb","surveyScaleBg":"#f3f4f6","surveyMaxLabel":"Очень вероятно","surveyMinLabel":"Маловероятно","surveyQuestion":"Насколько вероятно, что вы порекомендуете нас друзьям?","buttonTextColor":"#ffffff","surveyScaleColor":"#111827","surveySubmitText":"Отправить","surveyThanksText":"Спасибо за оценку!","surveyScaleActiveBg":"#2563eb","surveyScaleActiveColor":"#ffffff","surveyCommentPlaceholder":"Расскажите подробнее"},"partIndex":0},{"id":"el-mw0k855n-t","type":"recommendation","rowId":"row-mw0k6x8e-q","style":{"bgColor":"transparent","recommenderCode":"e4bceaa2a37cdc9f1d995b8862b4fe2a"},"partIndex":0}],"variables":{},"frameStyle":{"width":92,"height":320,"bgColor":"#ffffff","padding":20,"maxWidth":480,"widthMode":"%","heightMode":"auto","borderColor":"#e5e7eb","borderWidth":1,"borderRadius":16,"maxWidthMode":"px"}},"frequency":"once_session","layout":"modal","placement":"center","promo_code_list_id":null,"selector":null,"target_screens":[],"trigger_event":null,"trigger_type":"app_start","trigger_value":null}]}} \ No newline at end of file diff --git a/test/fixtures/popups_v3/markup.json b/test/fixtures/popups_v3/markup.json new file mode 100644 index 0000000..a7f2c1e --- /dev/null +++ b/test/fixtures/popups_v3/markup.json @@ -0,0 +1,265 @@ +{ + "_fixture": { + "about": "Облегчённая разметка текста. Сканирование слева направо одним регэкспом компилятора (Context::RICH_TEXT_RE), без вложенности; HTML — это текст; \\n — перенос строки.", + "regex": "\\*\\*\\*([^*]+)\\*\\*\\*|\\*\\*([^*]+)\\*\\*|~~([^~]+)~~|__([^_]+)__|\\^\\^([^^]+)\\^\\^|\\*([^*]+)\\*", + "expect": [ + { + "input": "***жирный курсив*** **жирный** *курсив* __подчёркнутый__ ~~зачёркнутый~~ ^^надчёркнутый^^", + "spans": [ + { + "text": "жирный курсив", + "bold": true, + "italic": true + }, + { + "text": " " + }, + { + "text": "жирный", + "bold": true + }, + { + "text": " " + }, + { + "text": "курсив", + "italic": true + }, + { + "text": " " + }, + { + "text": "подчёркнутый", + "underline": true + }, + { + "text": " " + }, + { + "text": "зачёркнутый", + "strike": true + }, + { + "text": " " + }, + { + "text": "надчёркнутый", + "overline": true + } + ] + }, + { + "input": "**незакрытый", + "spans": [ + { + "text": "**незакрытый" + } + ] + }, + { + "input": "теги — это текст & < >", + "spans": [ + { + "text": "теги — это текст & < >" + } + ] + }, + { + "input": "строка 1\nстрока 2", + "spans": [ + { + "text": "строка 1\nстрока 2" + } + ] + }, + { + "input": "a*b*c", + "spans": [ + { + "text": "a" + }, + { + "text": "b", + "italic": true + }, + { + "text": "c" + } + ] + }, + { + "input": "**жирный *вложенный* текст**", + "spans": [ + { + "text": "*" + }, + { + "text": "жирный ", + "italic": true + }, + { + "text": "вложенный" + }, + { + "text": " текст", + "italic": true + }, + { + "text": "*" + } + ] + }, + { + "input": "**многострочный\nжирный**", + "spans": [ + { + "text": "многострочный\nжирный", + "bold": true + } + ] + }, + { + "input": "__a__b__c__", + "spans": [ + { + "text": "a", + "underline": true + }, + { + "text": "b" + }, + { + "text": "c", + "underline": true + } + ] + }, + { + "input": "", + "spans": [] + } + ] + }, + "id": 9303, + "layout": "modal", + "placement": "center", + "trigger_type": "manual", + "frequency": "every_page", + "cooldown_minutes": 0, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "m0", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "***жирный курсив*** **жирный** *курсив* __подчёркнутый__ ~~зачёркнутый~~ ^^надчёркнутый^^" + } + }, + { + "id": "m1", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "**незакрытый" + } + }, + { + "id": "m2", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "теги — это текст & < >" + } + }, + { + "id": "m3", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "строка 1\nстрока 2" + } + }, + { + "id": "m4", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "a*b*c" + } + }, + { + "id": "m5", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "**жирный *вложенный* текст**" + } + }, + { + "id": "m6", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "**многострочный\nжирный**" + } + }, + { + "id": "m7", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "__a__b__c__" + } + }, + { + "id": "m8", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "" + } + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/parsing.json b/test/fixtures/popups_v3/parsing.json new file mode 100644 index 0000000..f705937 --- /dev/null +++ b/test/fixtures/popups_v3/parsing.json @@ -0,0 +1,158 @@ +{ + "_fixture": { + "about": "Векторы для разбора цветов и чисел. Цвет → #RRGGBBAA (в нижнем регистре) или null (нет цвета → запасное значение элемента). Число → значение или запасное. Значения со звёздочкой — наше предложение, у бэка не подтверждено." + }, + "colors": [ + { + "in": "#2563eb", + "out": "#2563ebff" + }, + { + "in": "#ABC", + "out": "#aabbccff" + }, + { + "in": "#2563eb80", + "out": "#2563eb80", + "note": "CSS-порядок RRGGBBAA, не Android AARRGGBB" + }, + { + "in": "#abcd", + "out": "#aabbccdd", + "note": "*" + }, + { + "in": "rgba(37, 99, 235, 0.5)", + "out": "#2563eb80" + }, + { + "in": "rgb(0,0,0)", + "out": "#000000ff" + }, + { + "in": "rgba(0 0 0 / 50%)", + "out": "#00000080", + "note": "*" + }, + { + "in": "red", + "out": "#ff0000ff" + }, + { + "in": "RebeccaPurple", + "out": "#663399ff" + }, + { + "in": "transparent", + "out": "#00000000" + }, + { + "in": " #fff ", + "out": "#ffffffff" + }, + { + "in": "#GGGGGG", + "out": null + }, + { + "in": "", + "out": null + }, + { + "in": null, + "out": null + }, + { + "in": 255, + "out": null + }, + { + "in": "url(javascript:alert(1))", + "out": null + } + ], + "numbers": [ + { + "in": 12, + "fallback": 0, + "out": 12 + }, + { + "in": "12", + "fallback": 0, + "out": 12 + }, + { + "in": "12.5", + "fallback": 0, + "out": 12.5 + }, + { + "in": " 7 ", + "fallback": 0, + "out": 7 + }, + { + "in": "12px", + "fallback": 0, + "out": 12, + "note": "* как parseFloat" + }, + { + "in": "", + "fallback": 8, + "out": 8 + }, + { + "in": null, + "fallback": 110, + "out": 110 + }, + { + "in": "abc", + "fallback": 16, + "out": 16 + }, + { + "in": true, + "fallback": 1, + "out": 1 + }, + { + "in": -4, + "fallback": 0, + "out": -4 + }, + { + "in": "0", + "fallback": 22, + "out": 0 + } + ], + "booleans": [ + { + "in": true, + "out": true + }, + { + "in": "true", + "out": true + }, + { + "in": 1, + "out": true + }, + { + "in": false, + "out": false + }, + { + "in": "false", + "out": false + }, + { + "in": null, + "out": null + } + ] +} diff --git a/test/fixtures/popups_v3/popup-response.json b/test/fixtures/popups_v3/popup-response.json new file mode 100644 index 0000000..cfc552a --- /dev/null +++ b/test/fixtures/popups_v3/popup-response.json @@ -0,0 +1,68 @@ +{ + "_fixture": { + "about": "Ответ GET /api/v3/storefront/popups/:id для ручного показа: аудитория, триггер, экраны и частота не проверяются, частота не записывается.", + "expect": { + "id": 516, + "show": true + } + }, + "status": "success", + "payload": { + "popup": { + "id": 516, + "layout": "fullscreen", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": null, + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": null, + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Только вручную" + } + } + ], + "variables": {} + } + } + } +} diff --git a/test/fixtures/popups_v3/requests.json b/test/fixtures/popups_v3/requests.json new file mode 100644 index 0000000..4204eff --- /dev/null +++ b/test/fixtures/popups_v3/requests.json @@ -0,0 +1,93 @@ +{ + "_fixture": { + "about": "Какие запросы делает SDK (контекст в context). Порядок параметров запроса не важен.", + "context": { + "shop_id": "c1140c8254976de297c3caf971701a", + "did": "DID123", + "sid": "SID123", + "app_host": "app.rees46.ru", + "api_host": "api.rees46.ru" + } + }, + "list": { + "method": "GET", + "url": "https://app.rees46.ru/api/v3/storefront/popups?shop_id=c1140c8254976de297c3caf971701a&did=DID123&sid=SID123&channel=mobile" + }, + "list_testmode_debug": { + "method": "GET", + "url": "https://app.rees46.ru/api/v3/storefront/popups?shop_id=c1140c8254976de297c3caf971701a&did=DID123&sid=SID123&channel=mobile&testmode=true&debug=1" + }, + "one": { + "method": "GET", + "url": "https://app.rees46.ru/api/v3/storefront/popups/516?shop_id=c1140c8254976de297c3caf971701a&did=DID123&sid=SID123" + }, + "one_testmode": { + "method": "GET", + "url": "https://app.rees46.ru/api/v3/storefront/popups/516?shop_id=c1140c8254976de297c3caf971701a&did=DID123&sid=SID123&testmode=true" + }, + "event_show": { + "method": "POST", + "url": "https://app.rees46.ru/api/v3/storefront/popups/512/events", + "json": { + "shop_id": "c1140c8254976de297c3caf971701a", + "did": "DID123", + "sid": "SID123", + "event": "show" + } + }, + "event_subscribe": { + "method": "POST", + "url": "https://app.rees46.ru/api/v3/storefront/popups/512/events", + "json": { + "shop_id": "c1140c8254976de297c3caf971701a", + "did": "DID123", + "sid": "SID123", + "event": "subscribe", + "channel": "email" + } + }, + "init_testmode": { + "method": "GET", + "url": "https://api.rees46.ru/init?shop_id=c1140c8254976de297c3caf971701a&stream=android&testmode=true", + "note": "в тестовом режиме /init тоже с testmode=true, иначе флаг не учтёт попапы в статусе «Тест»" + }, + "promo": { + "method": "GET", + "url": "https://api.rees46.ru/promo_codes/fetch?shop_id=c1140c8254976de297c3caf971701a&did=DID123&sid=SID123&id=7" + }, + "review_nps": { + "method": "POST", + "url": "https://app.rees46.ru/api/v3/polls/nps/reviews", + "json": { + "shop_id": "c1140c8254976de297c3caf971701a", + "did": "DID123", + "sid": "SID123", + "channel": "popup", + "category": "test", + "rate": 0, + "comment": "Долгая доставка" + } + }, + "review_csat_no_comment": { + "method": "POST", + "url": "https://app.rees46.ru/api/v3/polls/csat/reviews", + "json": { + "shop_id": "c1140c8254976de297c3caf971701a", + "did": "DID123", + "sid": "SID123", + "channel": "popup", + "campaign": "MNTEST", + "rate": 5 + } + }, + "segment_add": { + "method": "POST", + "url": "https://api.rees46.ru/segments/add", + "json_subset": { + "shop_id": "c1140c8254976de297c3caf971701a", + "did": "DID123", + "segment_id": 123 + }, + "note": "после записи профиля/подписки; только по did — обходит баг Android (phone пишется в email)" + } +} diff --git a/test/fixtures/popups_v3/scenarios.json b/test/fixtures/popups_v3/scenarios.json new file mode 100644 index 0000000..1fbd222 --- /dev/null +++ b/test/fixtures/popups_v3/scenarios.json @@ -0,0 +1,214 @@ +{ + "_fixture": { + "about": "Сценарии движка для общих юнит-тестов: триггеры, экраны, частота, конкуренция, промокод. Время в секундах от старта. screen(x) — вызов API «открыт экран x». Попапы — из list-response.json." + }, + "scenarios": [ + { + "name": "app_start без экранов", + "popup": 512, + "steps": [ + "init", + "list loaded" + ], + "expect": "show at list loaded" + }, + { + "name": "app_start ждёт подходящий экран", + "popup": { + "from": 512, + "target_screens": [ + "product" + ] + }, + "steps": [ + "list loaded", + "screen(home)", + "screen(product)" + ], + "expect": "show at screen(product)" + }, + { + "name": "screen_open по списку экранов", + "popup": 513, + "steps": [ + "screen(home)", + "screen(product)" + ], + "expect": "show at screen(product)" + }, + { + "name": "screen_open с пустым списком", + "popup": { + "from": 513, + "target_screens": [] + }, + "steps": [ + "screen(home)" + ], + "expect": "show at screen(home)" + }, + { + "name": "time_on_screen ушёл раньше", + "popup": 514, + "steps": [ + "t=0 screen(home)", + "t=9 screen(category)", + "t=20" + ], + "expect": "no show" + }, + { + "name": "time_on_screen досидел", + "popup": 514, + "steps": [ + "t=0 screen(home)", + "t=10" + ], + "expect": "show at t=10" + }, + { + "name": "time_on_screen и фон", + "popup": 514, + "steps": [ + "t=0 screen(home)", + "t=5 background", + "t=30 foreground", + "t=39", + "t=40" + ], + "expect": "show at t=40 (таймер сбрасывается в фоне и стартует заново) — предложение" + }, + { + "name": "track_event", + "popup": 515, + "steps": [ + "trackEvent(other)", + "trackEvent(promo_view)" + ], + "expect": "show at trackEvent(promo_view)" + }, + { + "name": "track_event не на том экране", + "popup": { + "from": 515, + "target_screens": [ + "cart" + ] + }, + "steps": [ + "screen(home)", + "trackEvent(promo_view)", + "screen(cart)" + ], + "expect": "no show (событийный триггер не ждёт экран)" + }, + { + "name": "manual", + "popup": 516, + "steps": [ + "list loaded", + "screen(home)", + "show(516)" + ], + "expect": "GET /popups/516 → show; частота не записана" + }, + { + "name": "once_session", + "popup": 512, + "steps": [ + "show", + "close", + "init (тот же sid)", + "init (новый sid)" + ], + "expect": "show, no show, show" + }, + { + "name": "once_day и пауза 60 минут", + "popup": 513, + "steps": [ + "t=0 screen(product) → show", + "t=30m screen(product)", + "t=23h screen(product)", + "t=24h screen(product)" + ], + "expect": "show, no, no, show" + }, + { + "name": "every_page — раз на экран", + "popup": { + "from": 512, + "frequency": "every_page" + }, + "steps": [ + "screen(home) → show", + "trigger again on home", + "screen(product)" + ], + "expect": "show, no show, show (app_start на каждом экране не стреляет повторно — уточнить)" + }, + { + "name": "testmode не пишет частоту", + "popup": { + "from": 512, + "frequency": "once_life" + }, + "steps": [ + "testmode on", + "show", + "init" + ], + "expect": "show, show" + }, + { + "name": "одна модалка", + "popups": [ + 513, + { + "from": 513, + "id": 613 + } + ], + "steps": [ + "screen(product)" + ], + "expect": "513 показан, 613 в очереди и показан после закрытия 513, если частота ещё позволяет" + }, + { + "name": "баннер не ждёт модалку", + "popups": [ + 512, + { + "from": 514, + "trigger_type": "app_start", + "target_screens": [] + } + ], + "steps": [ + "list loaded" + ], + "expect": "модалка 512 и баннер 514 видны вместе" + }, + { + "name": "нет промокода", + "popup": { + "from": 519, + "design": "element-promo-code.json" + }, + "steps": [ + "list loaded", + "promo_codes/fetch → 404" + ], + "expect": "no show, no show event" + }, + { + "name": "смена контекста", + "steps": [ + "list loaded", + "profile set", + "t+2s" + ], + "expect": "кеш списка сброшен, новый GET через ~2 с; одинаковый profile set в той же сессии повторно не сбрасывает" + } + ] +} diff --git a/test/fixtures/popups_v3/unknown-element.json b/test/fixtures/popups_v3/unknown-element.json new file mode 100644 index 0000000..f360d05 --- /dev/null +++ b/test/fixtures/popups_v3/unknown-element.json @@ -0,0 +1,99 @@ +{ + "_fixture": { + "about": "Неизвестные типы пропускаются с записью в лог, рендер не падает; style не объект → пустой стиль.", + "expect": { + "rendered": [ + "ok", + "bad-style" + ], + "skipped_logged": [ + "wheel", + "countdown", + "no-type" + ] + } + }, + "id": 9304, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "ok", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Остаюсь" + } + }, + { + "id": "wheel", + "type": "wheel", + "rowId": "row-1", + "partIndex": 0, + "style": { + "sectors": [] + } + }, + { + "id": "countdown", + "type": "countdown", + "rowId": "row-1", + "partIndex": 0, + "style": {} + }, + { + "id": "no-type", + "rowId": "row-1", + "partIndex": 0, + "style": {} + }, + { + "id": "bad-style", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": "oops" + } + ], + "variables": {} + } +} diff --git a/test/fixtures/popups_v3/variables.json b/test/fixtures/popups_v3/variables.json new file mode 100644 index 0000000..2ce791c --- /dev/null +++ b/test/fixtures/popups_v3/variables.json @@ -0,0 +1,130 @@ +{ + "_fixture": { + "about": "Переменные: статические из design.variables (объект или старый массив {key, value}) подставляются сразу, витринные (promo_code, coupon_code, campaign_end, remaining, progress, cart_total, wheel_prize) — SDK при показе; неизвестные остаются как есть.", + "expect": { + "static_variables": { + "name": "Аня", + "spaced": "ок", + "path": "sale", + "img": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "promo_code": "FAKE" + }, + "t_after_static": "Привет, Аня! Код: {{promo_code}}. {{unknown}} ок {{cart_total}}", + "t_at_show_with_code_ABC123": "Привет, Аня! Код: ABC123. {{unknown}} ок {{cart_total}}", + "notes": [ + "promo_code из variables игнорируется (витринная переменная)", + "cart_total неизвестен → токен остаётся (как в web, где applyVars не трогает отсутствующие)", + "переменные подставляются до разбора разметки (Context#rich_html), значения витринных — без разметки" + ], + "b_href": "https://demo.rees46.ru/sale", + "i_url": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg", + "e_placeholder": "Email для Аня" + } + }, + "id": 9302, + "layout": "modal", + "placement": "center", + "selector": null, + "trigger_type": "manual", + "trigger_value": null, + "trigger_event": null, + "frequency": "every_page", + "cooldown_minutes": 0, + "promo_code_list_id": null, + "target_screens": [], + "design": { + "frameStyle": { + "width": 92, + "height": 320, + "widthMode": "%", + "heightMode": "auto", + "maxWidth": 480, + "maxWidthMode": "px", + "bgColor": "#ffffff", + "borderColor": "#e5e7eb", + "borderWidth": 1, + "borderRadius": 16, + "padding": 20 + }, + "rows": [ + { + "id": "row-1", + "columns": [ + 100 + ], + "cells": [ + { + "align": "left", + "verticalAlign": "top" + } + ], + "gap": 8, + "minHeight": 0 + } + ], + "elements": [ + { + "id": "t", + "type": "text", + "rowId": "row-1", + "partIndex": 0, + "style": { + "message": "Привет, {{name}}! Код: {{promo_code}}. {{unknown}} {{ spaced }} {{cart_total}}" + } + }, + { + "id": "b", + "type": "button", + "rowId": "row-1", + "partIndex": 0, + "style": { + "buttonText": "Открыть {{name}}", + "linkHref": "https://demo.rees46.ru/{{path}}" + } + }, + { + "id": "i", + "type": "image", + "rowId": "row-1", + "partIndex": 0, + "style": { + "imageUrl": "{{img}}" + } + }, + { + "id": "e", + "type": "emailCollector", + "rowId": "row-1", + "partIndex": 0, + "style": { + "emailPlaceholder": "Email для {{name}}" + } + } + ], + "variables": [ + { + "key": "name", + "value": "Аня" + }, + { + "key": "spaced", + "value": "ок" + }, + { + "key": "path", + "value": "sale" + }, + { + "key": "img", + "value": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/141206.jpg" + }, + { + "key": "promo_code", + "value": "FAKE" + }, + { + "value": "без ключа" + } + ] + } +} diff --git a/test/fixtures/product_info.json b/test/fixtures/product_info.json new file mode 100644 index 0000000..dc7608d --- /dev/null +++ b/test/fixtures/product_info.json @@ -0,0 +1,126 @@ +{ + "name": "Гарнитура Накладная Logitech H150, White, 981-000350", + "is_available": true, + "description": "", + "price": "14990.0", + "price_full": 14990.0, + "currency": "₽", + "url": "https://www.technodom.kz/p/garnitura-nakladnaa-logitech-h-white-868", + "url_handle": "/p/garnitura-nakladnaa-logitech-h-white-868", + "picture": "https://api.technodom.kz/f3/api/v1/images/garnitura_nakladnaa_logitech_h_white_868_1.jpg", + "image_url": "https://api.technodom.kz/f3/api/v1/images/garnitura_nakladnaa_logitech_h_white_868_1.jpg", + "image_url_handle": "/f3/api/v1/images/garnitura_nakladnaa_logitech_h_white_868_1.jpg", + "image_url_resized": { + "120": "https://pictures.rees46.ru/resize-images/120/c1140c8254976de297c3caf971701a/131887.jpg", + "140": "https://pictures.rees46.ru/resize-images/140/c1140c8254976de297c3caf971701a/131887.jpg", + "160": "https://pictures.rees46.ru/resize-images/160/c1140c8254976de297c3caf971701a/131887.jpg", + "180": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/131887.jpg", + "200": "https://pictures.rees46.ru/resize-images/200/c1140c8254976de297c3caf971701a/131887.jpg", + "220": "https://pictures.rees46.ru/resize-images/220/c1140c8254976de297c3caf971701a/131887.jpg", + "310": "https://pictures.rees46.ru/resize-images/310/c1140c8254976de297c3caf971701a/131887.jpg", + "520": "https://pictures.rees46.ru/resize-images/520/c1140c8254976de297c3caf971701a/131887.jpg" + }, + "category_ids": [ + "smartfony-i-gadzhety", + "naushniki", + "vse-naushniki" + ], + "brand": "Logitech", + "sales_rate": null, + "relative_sales_rate": null, + "price_formatted": "14 990 ₽", + "price_full_formatted": "14 990.00 ₽", + "categories": [ + { + "id": "smartfony-i-gadzhety", + "name": "Смартфоны и гаджеты", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety", + "branch": 1, + "level": 1, + "name_with_parent": "Смартфоны и гаджеты", + "url_handle": "/catalog/smartfony-i-gadzhety" + }, + { + "parent_id": "smartfony-i-gadzhety", + "id": "naushniki", + "name": "Наушники", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki", + "branch": 1, + "level": 2, + "name_with_parent": "Смартфоны и гаджеты - Наушники", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki" + }, + { + "parent_id": "naushniki", + "id": "vse-naushniki", + "name": "Все наушники", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki", + "branch": 1, + "level": 3, + "name_with_parent": "Наушники - Все наушники", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki" + } + ], + "group_id": null, + "id": "868", + "uniqid": "868", + "widgetable": true, + "ignored": false, + "locations": { + "7": { + "price": 14990, + "stock_quantity": 9999 + }, + "10": { + "price": 14990, + "stock_quantity": 9999 + }, + "30": { + "price": 14990, + "stock_quantity": 1 + }, + "39": { + "price": 14990, + "stock_quantity": 9999 + }, + "47": { + "price": 14990, + "stock_quantity": 9999 + }, + "58": { + "price": 14990, + "stock_quantity": 9999 + }, + "None": { + "price": 14990, + "stock_quantity": 9999 + } + }, + "type_prefix": "все наушники барлық құлаққап ақ", + "vendor_code": "981-000350", + "model": "981-000350", + "barcode": "868", + "location_ids": [ + "39", + "47", + "None", + "7", + "30", + "58", + "10" + ], + "price_margin": 2, + "brand_downcase": "logitech", + "discount": false, + "tags": [ + "все", + "наушники", + "барлық", + "құлаққап", + "ақ" + ], + "image_download_start_at": "2026-10-18T15:28:29.000Z", + "stock_quantity": 999999, + "deeplink_android": "https://www.technodom.kz/p/garnitura-nakladnaa-logitech-h-white-868", + "deeplink_ios": "https://www.technodom.kz/p/garnitura-nakladnaa-logitech-h-white-868" +} \ No newline at end of file diff --git a/test/fixtures/products.json b/test/fixtures/products.json new file mode 100644 index 0000000..8dade24 --- /dev/null +++ b/test/fixtures/products.json @@ -0,0 +1,226 @@ +{ + "products_total": 10000, + "products": [ + { + "name": "Наушники накладные HONOR CHOICE Headphones Lite Gray (5504ADGF)", + "url": "https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252?recommended_by=listing", + "deeplink_android": "https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252", + "deeplink_ios": "https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252", + "category_ids": [ + "smartfony-i-gadzhety", + "naushniki", + "vse-naushniki" + ], + "barcode": "300252", + "vendor_code": "5504ADGF", + "brand": "Honor", + "model": "5504ADGF", + "sales_rate": 6755, + "relative_sales_rate": 100, + "picture": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/146384.jpg", + "categories": [ + { + "id": "smartfony-i-gadzhety", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety?recommended_by=listing", + "name": "Смартфоны и гаджеты", + "level": "1", + "url_handle": "/catalog/smartfony-i-gadzhety?recommended_by=listing" + }, + { + "id": "naushniki", + "parent_id": "smartfony-i-gadzhety", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki?recommended_by=listing", + "name": "Смартфоны и гаджеты - Наушники", + "level": "2", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki?recommended_by=listing" + }, + { + "id": "vse-naushniki", + "parent_id": "naushniki", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki?recommended_by=listing", + "name": "Наушники - Все наушники", + "level": "3", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki?recommended_by=listing" + } + ], + "price_formatted": "15 990 ₽", + "price_full_formatted": "15 990.00 ₽", + "price": 15990, + "price_full": 15990, + "image_url": "https://api.technodom.kz/f3/api/v1/images/300252_1.jpg", + "image_url_handle": "/f3/api/v1/images/300252_1.jpg", + "image_url_resized": { + "120": "https://pictures.rees46.ru/resize-images/120/c1140c8254976de297c3caf971701a/146384.jpg", + "140": "https://pictures.rees46.ru/resize-images/140/c1140c8254976de297c3caf971701a/146384.jpg", + "160": "https://pictures.rees46.ru/resize-images/160/c1140c8254976de297c3caf971701a/146384.jpg", + "180": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/146384.jpg", + "200": "https://pictures.rees46.ru/resize-images/200/c1140c8254976de297c3caf971701a/146384.jpg", + "220": "https://pictures.rees46.ru/resize-images/220/c1140c8254976de297c3caf971701a/146384.jpg", + "310": "https://pictures.rees46.ru/resize-images/310/c1140c8254976de297c3caf971701a/146384.jpg", + "520": "https://pictures.rees46.ru/resize-images/520/c1140c8254976de297c3caf971701a/146384.jpg", + "original": "https://api.technodom.kz/f3/api/v1/images/300252_1.jpg" + }, + "url_handle": "/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252?recommended_by=listing", + "currency": "₽", + "_id": "146384", + "id": "300252", + "stock_quantity": 999999, + "group_id": "_146384_" + }, + { + "name": "Двухкамерный холодильник Beko RDSK-240M00W", + "url": "https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173?recommended_by=listing", + "deeplink_android": "https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173", + "deeplink_ios": "https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173", + "category_ids": [ + "bytovaja-tehnika", + "holodil-niki", + "hranenie-produktov-i-napitkov" + ], + "barcode": "52173", + "vendor_code": "RDSK-240M00W", + "brand": "Beko", + "model": "RDSK-240M00W", + "sales_rate": 3969, + "relative_sales_rate": 58.76, + "picture": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/132229.jpg", + "categories": [ + { + "id": "bytovaja-tehnika", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika?recommended_by=listing", + "name": "Бытовая техника", + "level": "1", + "url_handle": "/catalog/bytovaja-tehnika?recommended_by=listing" + }, + { + "id": "hranenie-produktov-i-napitkov", + "parent_id": "bytovaja-tehnika", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika/hranenie-produktov-i-napitkov?recommended_by=listing", + "name": "Бытовая техника - Хранение продуктов и напитков", + "level": "2", + "url_handle": "/catalog/bytovaja-tehnika/hranenie-produktov-i-napitkov?recommended_by=listing" + }, + { + "id": "holodil-niki", + "parent_id": "hranenie-produktov-i-napitkov", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika/hranenie-produktov-i-napitkov/holodil-niki?recommended_by=listing", + "name": "Хранение продуктов и напитков - Холодильники", + "level": "3", + "url_handle": "/catalog/bytovaja-tehnika/hranenie-produktov-i-napitkov/holodil-niki?recommended_by=listing" + } + ], + "discount_percent": 5, + "price_formatted": "164 990 ₽", + "price_full_formatted": "164 990.00 ₽", + "price": 164990, + "price_full": 164990, + "oldprice_formatted": "174 990 ₽", + "oldprice_full_formatted": "174 990.00 ₽", + "oldprice": 174990, + "oldprice_full": 174990, + "image_url": "https://api.technodom.kz/f3/api/v1/images/holodilnik_beko_rdsk_mw_52173_1.jpg", + "image_url_handle": "/f3/api/v1/images/holodilnik_beko_rdsk_mw_52173_1.jpg", + "image_url_resized": { + "120": "https://pictures.rees46.ru/resize-images/120/c1140c8254976de297c3caf971701a/132229.jpg", + "140": "https://pictures.rees46.ru/resize-images/140/c1140c8254976de297c3caf971701a/132229.jpg", + "160": "https://pictures.rees46.ru/resize-images/160/c1140c8254976de297c3caf971701a/132229.jpg", + "180": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/132229.jpg", + "200": "https://pictures.rees46.ru/resize-images/200/c1140c8254976de297c3caf971701a/132229.jpg", + "220": "https://pictures.rees46.ru/resize-images/220/c1140c8254976de297c3caf971701a/132229.jpg", + "310": "https://pictures.rees46.ru/resize-images/310/c1140c8254976de297c3caf971701a/132229.jpg", + "520": "https://pictures.rees46.ru/resize-images/520/c1140c8254976de297c3caf971701a/132229.jpg", + "original": "https://api.technodom.kz/f3/api/v1/images/holodilnik_beko_rdsk_mw_52173_1.jpg" + }, + "url_handle": "/p/holodilnik-beko-rdsk-mw-52173?recommended_by=listing", + "discount": 6, + "discount_formatted": "6%", + "currency": "₽", + "_id": "132229", + "id": "52173", + "stock_quantity": 999999, + "group_id": "_132229_" + } + ], + "price_range": { + "min": 10, + "max": 8000000 + }, + "price_ranges": [ + { + "to": 10000, + "count": 3107 + }, + { + "from": 10000, + "to": 25000, + "count": 2497 + }, + { + "from": 25000, + "to": 50000, + "count": 2399 + } + ], + "price_median": 37000, + "filters": { + "\"Сухой\" ТЭН": { + "count": 2, + "values": { + "Да": 2 + } + }, + "AC выход": { + "count": 1, + "values": { + "3600 Вт (Скачки 7200 Вт)": 1 + } + }, + "AC гнезда": { + "count": 1, + "values": { + "4": 1 + }, + "ranges": { + "min": 4, + "max": 4 + } + } + }, + "brands": [ + { + "name": "1STPLAYER", + "count": 11 + }, + { + "name": "2E", + "count": 31 + }, + { + "name": "70mai", + "count": 1 + } + ], + "categories": [ + { + "id": "noutbuki-i-komp-jutery", + "name": "Ноутбуки и компьютеры", + "url": "https://www.technodom.kz/catalog/noutbuki-i-komp-jutery?recommended_by=listing", + "url_handle": "/catalog/noutbuki-i-komp-jutery?recommended_by=listing", + "count": 3240 + }, + { + "id": "bytovaja-tehnika", + "name": "Бытовая техника", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika?recommended_by=listing", + "url_handle": "/catalog/bytovaja-tehnika?recommended_by=listing", + "count": 2818 + }, + { + "id": "tehnika-dlja-kuhni", + "name": "Техника для кухни", + "url": "https://www.technodom.kz/catalog/tehnika-dlja-kuhni?recommended_by=listing", + "url_handle": "/catalog/tehnika-dlja-kuhni?recommended_by=listing", + "count": 2428 + } + ] +} \ No newline at end of file diff --git a/test/fixtures/recommend_extended.json b/test/fixtures/recommend_extended.json new file mode 100644 index 0000000..1e7b23b --- /dev/null +++ b/test/fixtures/recommend_extended.json @@ -0,0 +1,151 @@ +{ + "id": 877, + "title": "Популярные", + "recommends": [ + { + "name": "Двухкамерный холодильник Beko RDSK-240M00W", + "url": "https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "deeplink_android": "https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173", + "deeplink_ios": "https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173", + "category_ids": [ + "bytovaja-tehnika", + "holodil-niki", + "hranenie-produktov-i-napitkov" + ], + "barcode": "52173", + "vendor_code": "RDSK-240M00W", + "brand": "Beko", + "model": "RDSK-240M00W", + "sales_rate": 3969, + "relative_sales_rate": 58.76, + "picture": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/132229.jpg", + "categories": [ + { + "id": "bytovaja-tehnika", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "name": "Бытовая техника", + "level": "1", + "name_with_parent": "Бытовая техника", + "url_handle": "/catalog/bytovaja-tehnika?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962" + }, + { + "id": "hranenie-produktov-i-napitkov", + "parent_id": "bytovaja-tehnika", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika/hranenie-produktov-i-napitkov?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "name": "Хранение продуктов и напитков", + "level": "2", + "name_with_parent": "Бытовая техника - Хранение продуктов и напитков", + "url_handle": "/catalog/bytovaja-tehnika/hranenie-produktov-i-napitkov?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962" + }, + { + "id": "holodil-niki", + "parent_id": "hranenie-produktov-i-napitkov", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika/hranenie-produktov-i-napitkov/holodil-niki?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "name": "Холодильники", + "level": "3", + "name_with_parent": "Хранение продуктов и напитков - Холодильники", + "url_handle": "/catalog/bytovaja-tehnika/hranenie-produktov-i-napitkov/holodil-niki?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962" + } + ], + "discount_percent": 5, + "price_formatted": "164 990 ₽", + "price_full_formatted": "164 990.00 ₽", + "price": 164990, + "price_full": 164990, + "oldprice_formatted": "174 990 ₽", + "oldprice_full_formatted": "174 990.00 ₽", + "oldprice": 174990, + "oldprice_full": 174990, + "image_url": "https://api.technodom.kz/f3/api/v1/images/holodilnik_beko_rdsk_mw_52173_1.jpg", + "image_url_handle": "/f3/api/v1/images/holodilnik_beko_rdsk_mw_52173_1.jpg", + "image_url_resized": { + "120": "https://pictures.rees46.ru/resize-images/120/c1140c8254976de297c3caf971701a/132229.jpg", + "140": "https://pictures.rees46.ru/resize-images/140/c1140c8254976de297c3caf971701a/132229.jpg", + "160": "https://pictures.rees46.ru/resize-images/160/c1140c8254976de297c3caf971701a/132229.jpg", + "180": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/132229.jpg", + "200": "https://pictures.rees46.ru/resize-images/200/c1140c8254976de297c3caf971701a/132229.jpg", + "220": "https://pictures.rees46.ru/resize-images/220/c1140c8254976de297c3caf971701a/132229.jpg", + "310": "https://pictures.rees46.ru/resize-images/310/c1140c8254976de297c3caf971701a/132229.jpg", + "520": "https://pictures.rees46.ru/resize-images/520/c1140c8254976de297c3caf971701a/132229.jpg", + "original": "https://api.technodom.kz/f3/api/v1/images/holodilnik_beko_rdsk_mw_52173_1.jpg" + }, + "url_handle": "/p/holodilnik-beko-rdsk-mw-52173?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "discount": 6, + "discount_formatted": "6%", + "currency": "₽", + "_id": "132229", + "id": "52173", + "stock_quantity": 999999, + "group_id": "_132229_" + }, + { + "name": "Наушники накладные HONOR CHOICE Headphones Lite Gray (5504ADGF)", + "url": "https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "deeplink_android": "https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252", + "deeplink_ios": "https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252", + "category_ids": [ + "smartfony-i-gadzhety", + "naushniki", + "vse-naushniki" + ], + "barcode": "300252", + "vendor_code": "5504ADGF", + "brand": "Honor", + "model": "5504ADGF", + "sales_rate": 6755, + "relative_sales_rate": 100, + "picture": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/146384.jpg", + "categories": [ + { + "id": "smartfony-i-gadzhety", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "name": "Смартфоны и гаджеты", + "level": "1", + "name_with_parent": "Смартфоны и гаджеты", + "url_handle": "/catalog/smartfony-i-gadzhety?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962" + }, + { + "id": "naushniki", + "parent_id": "smartfony-i-gadzhety", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "name": "Наушники", + "level": "2", + "name_with_parent": "Смартфоны и гаджеты - Наушники", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962" + }, + { + "id": "vse-naushniki", + "parent_id": "naushniki", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "name": "Все наушники", + "level": "3", + "name_with_parent": "Наушники - Все наушники", + "url_handle": "/catalog/smartfony-i-gadzhety/naushniki/vse-naushniki?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962" + } + ], + "price_formatted": "15 990 ₽", + "price_full_formatted": "15 990.00 ₽", + "price": 15990, + "price_full": 15990, + "image_url": "https://api.technodom.kz/f3/api/v1/images/300252_1.jpg", + "image_url_handle": "/f3/api/v1/images/300252_1.jpg", + "image_url_resized": { + "120": "https://pictures.rees46.ru/resize-images/120/c1140c8254976de297c3caf971701a/146384.jpg", + "140": "https://pictures.rees46.ru/resize-images/140/c1140c8254976de297c3caf971701a/146384.jpg", + "160": "https://pictures.rees46.ru/resize-images/160/c1140c8254976de297c3caf971701a/146384.jpg", + "180": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/146384.jpg", + "200": "https://pictures.rees46.ru/resize-images/200/c1140c8254976de297c3caf971701a/146384.jpg", + "220": "https://pictures.rees46.ru/resize-images/220/c1140c8254976de297c3caf971701a/146384.jpg", + "310": "https://pictures.rees46.ru/resize-images/310/c1140c8254976de297c3caf971701a/146384.jpg", + "520": "https://pictures.rees46.ru/resize-images/520/c1140c8254976de297c3caf971701a/146384.jpg", + "original": "https://api.technodom.kz/f3/api/v1/images/300252_1.jpg" + }, + "url_handle": "/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252?recommended_by=dynamic&recommended_code=e6249bb15043644bf25b135006149962", + "currency": "₽", + "_id": "146384", + "id": "300252", + "stock_quantity": 999999, + "group_id": "_146384_" + } + ] +} \ No newline at end of file diff --git a/test/fixtures/search_full.json b/test/fixtures/search_full.json new file mode 100644 index 0000000..db8a2f8 --- /dev/null +++ b/test/fixtures/search_full.json @@ -0,0 +1,217 @@ +{ + "search_query": "samsung", + "search_query_original": "samsung", + "collections": [], + "products_total": 833, + "products": [ + { + "name": "Стиральная машина Samsung WW60AK4S00CELT", + "url": "https://www.technodom.kz/p/stiralnaya-mashina-samsung-ww60ak4s00celt-292523?recommended_by=full_search&recommended_code=samsung", + "deeplink_android": "https://www.technodom.kz/p/stiralnaya-mashina-samsung-ww60ak4s00celt-292523", + "deeplink_ios": "https://www.technodom.kz/p/stiralnaya-mashina-samsung-ww60ak4s00celt-292523", + "category_ids": [ + "bytovaja-tehnika", + "stiral-nye-mashiny", + "uhod-za-odezhdoj" + ], + "barcode": "292523", + "vendor_code": "WW60AK4S00CELT", + "brand": "Samsung", + "model": "WW60AK4S00CELT", + "picture": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/143748.jpg", + "categories": [ + { + "id": "bytovaja-tehnika", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika?recommended_by=full_search&recommended_code=samsung", + "name": "Бытовая техника", + "level": "1", + "url_handle": "/catalog/bytovaja-tehnika?recommended_by=full_search&recommended_code=samsung" + }, + { + "id": "uhod-za-odezhdoj", + "parent_id": "bytovaja-tehnika", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika/uhod-za-odezhdoj?recommended_by=full_search&recommended_code=samsung", + "name": "Бытовая техника - Уход за одеждой", + "level": "2", + "url_handle": "/catalog/bytovaja-tehnika/uhod-za-odezhdoj?recommended_by=full_search&recommended_code=samsung" + }, + { + "id": "stiral-nye-mashiny", + "parent_id": "uhod-za-odezhdoj", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika/uhod-za-odezhdoj/stiral-nye-mashiny?recommended_by=full_search&recommended_code=samsung", + "name": "Уход за одеждой - Стиральные машины", + "level": "3", + "url_handle": "/catalog/bytovaja-tehnika/uhod-za-odezhdoj/stiral-nye-mashiny?recommended_by=full_search&recommended_code=samsung" + } + ], + "price_formatted": "179 990 ₽", + "price_full_formatted": "179 990.00 ₽", + "price": 179990, + "price_full": 179990, + "image_url": "https://api.technodom.kz/f3/api/v1/images/292523_1.jpg", + "image_url_handle": "/f3/api/v1/images/292523_1.jpg", + "image_url_resized": { + "120": "https://pictures.rees46.ru/resize-images/120/c1140c8254976de297c3caf971701a/143748.jpg", + "140": "https://pictures.rees46.ru/resize-images/140/c1140c8254976de297c3caf971701a/143748.jpg", + "160": "https://pictures.rees46.ru/resize-images/160/c1140c8254976de297c3caf971701a/143748.jpg", + "180": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/143748.jpg", + "200": "https://pictures.rees46.ru/resize-images/200/c1140c8254976de297c3caf971701a/143748.jpg", + "220": "https://pictures.rees46.ru/resize-images/220/c1140c8254976de297c3caf971701a/143748.jpg", + "310": "https://pictures.rees46.ru/resize-images/310/c1140c8254976de297c3caf971701a/143748.jpg", + "520": "https://pictures.rees46.ru/resize-images/520/c1140c8254976de297c3caf971701a/143748.jpg", + "original": "https://api.technodom.kz/f3/api/v1/images/292523_1.jpg" + }, + "url_handle": "/p/stiralnaya-mashina-samsung-ww60ak4s00celt-292523?recommended_by=full_search&recommended_code=samsung", + "currency": "₽", + "_id": "143748", + "id": "292523", + "stock_quantity": 999999, + "group_id": "_143748_" + }, + { + "name": "Пылесос с контейнером Samsung VC-C4520S3R", + "url": "https://www.technodom.kz/p/pylesos-samsung-vc-c4520s3r-22510?recommended_by=full_search&recommended_code=samsung", + "deeplink_android": "https://www.technodom.kz/p/pylesos-samsung-vc-c4520s3r-22510", + "deeplink_ios": "https://www.technodom.kz/p/pylesos-samsung-vc-c4520s3r-22510", + "category_ids": [ + "bytovaja-tehnika", + "pylesosy", + "uhod-za-domom" + ], + "barcode": "22510", + "vendor_code": "VC-C4520S3R", + "brand": "Samsung", + "model": "VC-C4520S3R", + "picture": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/133215.jpg", + "categories": [ + { + "id": "bytovaja-tehnika", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika?recommended_by=full_search&recommended_code=samsung", + "name": "Бытовая техника", + "level": "1", + "url_handle": "/catalog/bytovaja-tehnika?recommended_by=full_search&recommended_code=samsung" + }, + { + "id": "uhod-za-domom", + "parent_id": "bytovaja-tehnika", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika/uhod-za-domom?recommended_by=full_search&recommended_code=samsung", + "name": "Бытовая техника - Уход за домом", + "level": "2", + "url_handle": "/catalog/bytovaja-tehnika/uhod-za-domom?recommended_by=full_search&recommended_code=samsung" + }, + { + "id": "pylesosy", + "parent_id": "uhod-za-domom", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika/uhod-za-domom/pylesosy?recommended_by=full_search&recommended_code=samsung", + "name": "Уход за домом - Пылесосы", + "level": "3", + "url_handle": "/catalog/bytovaja-tehnika/uhod-za-domom/pylesosy?recommended_by=full_search&recommended_code=samsung" + } + ], + "price_formatted": "41 990 ₽", + "price_full_formatted": "41 990.00 ₽", + "price": 41990, + "price_full": 41990, + "image_url": "https://api.technodom.kz/f3/api/v1/images/22510_2.jpg", + "image_url_handle": "/f3/api/v1/images/22510_2.jpg", + "image_url_resized": { + "120": "https://pictures.rees46.ru/resize-images/120/c1140c8254976de297c3caf971701a/133215.jpg", + "140": "https://pictures.rees46.ru/resize-images/140/c1140c8254976de297c3caf971701a/133215.jpg", + "160": "https://pictures.rees46.ru/resize-images/160/c1140c8254976de297c3caf971701a/133215.jpg", + "180": "https://pictures.rees46.ru/resize-images/180/c1140c8254976de297c3caf971701a/133215.jpg", + "200": "https://pictures.rees46.ru/resize-images/200/c1140c8254976de297c3caf971701a/133215.jpg", + "220": "https://pictures.rees46.ru/resize-images/220/c1140c8254976de297c3caf971701a/133215.jpg", + "310": "https://pictures.rees46.ru/resize-images/310/c1140c8254976de297c3caf971701a/133215.jpg", + "520": "https://pictures.rees46.ru/resize-images/520/c1140c8254976de297c3caf971701a/133215.jpg", + "original": "https://api.technodom.kz/f3/api/v1/images/22510_2.jpg" + }, + "url_handle": "/p/pylesos-samsung-vc-c4520s3r-22510?recommended_by=full_search&recommended_code=samsung", + "currency": "₽", + "_id": "133215", + "id": "22510", + "stock_quantity": 999999, + "group_id": "_133215_" + } + ], + "price_range": { + "min": 990, + "max": 6999990 + }, + "price_ranges": [ + { + "to": 100000, + "count": 346 + }, + { + "from": 100000, + "to": 250000, + "count": 150 + }, + { + "from": 250000, + "to": 500000, + "count": 151 + } + ], + "price_median": 161000, + "filters": { + "is_preorder": { + "count": 833, + "values": { + "False": 833 + } + }, + "merchant": { + "count": 833, + "values": { + "Technodom": 833 + } + }, + "product_type": { + "count": 833, + "values": { + "regular": 833 + } + } + }, + "brands": [ + { + "name": "Samsung", + "count": 801 + }, + { + "name": "Topperr", + "count": 9 + }, + { + "name": "Ozone", + "count": 1 + } + ], + "categories": [ + { + "id": "smartfony-i-gadzhety", + "name": "Смартфоны и гаджеты", + "url": "https://www.technodom.kz/catalog/smartfony-i-gadzhety?recommended_by=full_search&recommended_code=samsung", + "url_handle": "/catalog/smartfony-i-gadzhety?recommended_by=full_search&recommended_code=samsung", + "count": 422 + }, + { + "id": "bytovaja-tehnika", + "name": "Бытовая техника", + "url": "https://www.technodom.kz/catalog/bytovaja-tehnika?recommended_by=full_search&recommended_code=samsung", + "url_handle": "/catalog/bytovaja-tehnika?recommended_by=full_search&recommended_code=samsung", + "count": 209 + }, + { + "id": "tv-audio-foto-video", + "name": "ТВ, аудио, фото, видео", + "url": "https://www.technodom.kz/catalog/tv-audio-foto-video?recommended_by=full_search&recommended_code=samsung", + "url_handle": "/catalog/tv-audio-foto-video?recommended_by=full_search&recommended_code=samsung", + "count": 148 + } + ], + "clarification": false, + "requests_count": 1, + "html": "" +} \ No newline at end of file diff --git a/test/fixtures/stories_polls_feed.json b/test/fixtures/stories_polls_feed.json new file mode 100644 index 0000000..8619969 --- /dev/null +++ b/test/fixtures/stories_polls_feed.json @@ -0,0 +1,379 @@ +{ + "status": "success", + "payload": { + "id": 1, + "settings": { + "avatar_size": "54", + "avatar_shape": "circle", + "border_not_viewed": "#119400", + "border_viewed": "#a0fdbc", + "pin_background": "#00cc33", + "pin_size": "20", + "background": "#ffffff", + "background_transparency": "100", + "color": "#212529", + "font_family": "-apple-system, Inter, system-ui, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif", + "font_size": "10", + "viewed_transparency": "0", + "progress_background": "#ffffff", + "close_color": "#ffffff", + "button_background": "#3b82f6", + "product_slide_background": "#000000", + "product_title_color": "#ffffff", + "product_price_background": "#f0f0f0", + "product_price_transparency": "0", + "product_price_color": "#18181b", + "product_old_price_color": "#868688", + "product_discount_background": "#f97316", + "product_status_color": "#ffffff", + "product_promo_code_background": "#18181b", + "product_promo_code_title_color": "#ffffff", + "product_notification_background": "#ffffff", + "product_notification_color": "#000000", + "pin_symbol": "📌", + "css_url": "https://storage.yandexcloud.net/r46v8/1/stories/1.css?v=1793634325-19616ad6" + }, + "stories": [ + { + "id": 9001, + "avatar": "https://cdn.stories.rees46.ru/14fcae67-551d-4a7a-828a-afc13fd5146c.jpg", + "name": "Опросы", + "pinned": false, + "share_url": null, + "shareable": false, + "start_position": 0, + "viewed": false, + "slides": [ + { + "id": 900, + "background": "https://cdn.stories.rees46.ru/2e6305ca-06db-4cca-8a75-0f50a0a42a97.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "mini_poll", + "y_offset": 50, + "allow_reanswer": true, + "labels": { + "reanswer": "Ответить заново", + "error": "Не удалось отправить ответ. Попробуйте еще раз" + }, + "poll": { + "code": "demo_single", + "kind": "single_choice", + "question": "Что вам больше нравится?", + "placeholder": null, + "max_length": null, + "submit_label": null, + "thanks_text": "Спасибо за ответ!", + "show_results": true, + "options": [ + { + "id": 1, + "label": "Кроссовки" + }, + { + "id": 2, + "label": "Ботинки" + }, + { + "id": 3, + "label": "Сандалии" + } + ] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 901, + "background": "https://cdn.stories.rees46.ru/5458c2f8-816a-4f53-82bb-89ad7995d4e1.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "mini_poll", + "y_offset": "40", + "allow_reanswer": false, + "labels": null, + "poll": { + "code": "demo_multi", + "kind": "multiple_choice", + "question": "Какие категории вам интересны?", + "placeholder": null, + "max_length": null, + "submit_label": "Отправить ответ", + "thanks_text": "Спасибо!", + "show_results": true, + "options": [ + { + "id": 1, + "label": "Обувь" + }, + { + "id": 2, + "label": "Одежда" + }, + { + "id": 3, + "label": "Аксессуары" + }, + { + "id": 4, + "label": "Спорт" + }, + { + "id": 5, + "label": "Дом" + } + ] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 902, + "background": "https://cdn.stories.rees46.ru/2e6305ca-06db-4cca-8a75-0f50a0a42a97.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "mini_poll", + "y_offset": 30, + "allow_reanswer": true, + "labels": { + "reanswer": "Ответить заново", + "error": "Не удалось отправить ответ. Попробуйте еще раз" + }, + "poll": { + "code": "demo_text", + "kind": "text", + "question": "Что нам улучшить?", + "placeholder": "Ваш ответ", + "max_length": "120", + "submit_label": null, + "thanks_text": "Спасибо за отзыв!", + "show_results": false, + "options": [] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 903, + "background": "https://cdn.stories.rees46.ru/5458c2f8-816a-4f53-82bb-89ad7995d4e1.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "nps", + "y_offset": 60, + "allow_reanswer": true, + "labels": { + "reanswer": "Ответить заново", + "error": "Не удалось отправить ответ. Попробуйте еще раз" + }, + "poll": { + "code": "test", + "channel": "test", + "name": "NPS", + "rate_min": 0, + "rate_max": 10, + "question": "Насколько вероятно, что вы порекомендуете нас друзьям?", + "bands": [ + { + "from": 0, + "to": 6, + "success": "Спасибо, мы станем лучше" + }, + { + "from": 7, + "to": 8, + "success": "Спасибо за оценку" + }, + { + "from": 9, + "to": 10, + "success": "Спасибо, мы рады!" + } + ] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 904, + "background": "https://cdn.stories.rees46.ru/2e6305ca-06db-4cca-8a75-0f50a0a42a97.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "csat", + "y_offset": 90, + "allow_reanswer": false, + "labels": null, + "poll": { + "code": "demo_csat", + "channel": null, + "name": "CSAT", + "rate_min": null, + "rate_max": null, + "question": "Как вам наш магазин?", + "bands": [ + { + "from": 1, + "to": 3, + "success": "Жаль" + }, + { + "from": 4, + "to": 5, + "success": "Ура" + } + ] + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 905, + "background": "https://cdn.stories.rees46.ru/5458c2f8-816a-4f53-82bb-89ad7995d4e1.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "ces", + "y_offset": 5, + "allow_reanswer": true, + "labels": null, + "poll": { + "code": "demo_ces", + "channel": "stories", + "name": "CES", + "rate_min": "1", + "rate_max": "7", + "question": "Легко ли было оформить заказ?", + "bands": null + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 906, + "background": "https://cdn.stories.rees46.ru/2e6305ca-06db-4cca-8a75-0f50a0a42a97.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "mini_poll", + "y_offset": 50, + "allow_reanswer": true, + "labels": { + "reanswer": "Ответить заново", + "error": "Не удалось отправить ответ. Попробуйте еще раз" + }, + "poll": { + "code": "demo_answered", + "kind": "single_choice", + "question": "Уже отвечено: выбор с результатами", + "placeholder": null, + "max_length": null, + "submit_label": null, + "thanks_text": "Спасибо за ответ!", + "show_results": true, + "options": [ + { + "id": 1, + "label": "Да" + }, + { + "id": 2, + "label": "Нет" + } + ] + }, + "answer": { + "id": 77, + "option_ids": [ + 2 + ], + "text": null + }, + "results": { + "total": 120, + "options": [ + { + "id": 1, + "percent": 40 + }, + { + "id": 2, + "percent": 60 + } + ] + } + } + ], + "preview": "", + "type": "image", + "share_url": null + }, + { + "id": 907, + "background": "https://cdn.stories.rees46.ru/5458c2f8-816a-4f53-82bb-89ad7995d4e1.jpg", + "duration": 10, + "elements": [ + { + "type": "poll", + "poll_type": "quiz", + "y_offset": 50, + "allow_reanswer": true, + "labels": null, + "poll": { + "code": "demo_unknown", + "kind": "single_choice", + "question": "Неизвестный вид — не рисуется" + }, + "answer": null, + "results": null + } + ], + "preview": "", + "type": "image", + "share_url": null + } + ] + } + ] + } +} \ No newline at end of file diff --git a/test/popups/popup_presenter_test.dart b/test/popups/popup_presenter_test.dart index 337fb7f..e6283e6 100644 --- a/test/popups/popup_presenter_test.dart +++ b/test/popups/popup_presenter_test.dart @@ -4,8 +4,6 @@ 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([ diff --git a/test/popups_v3/fixtures.dart b/test/popups_v3/fixtures.dart new file mode 100644 index 0000000..18fc302 --- /dev/null +++ b/test/popups_v3/fixtures.dart @@ -0,0 +1,12 @@ +import 'dart:convert'; +import 'dart:io'; + +/// Общая фикстура попапов v3 (`test/fixtures/popups_v3/`). +Map popupsV3Fixture(String name) => + jsonDecode(File('test/fixtures/popups_v3/$name').readAsStringSync()) + as Map; + +/// Ожидания фикстуры (`_fixture.expect`). +Map popupsV3Expect(Map fixture) => + (fixture['_fixture'] as Map)['expect'] + as Map; diff --git a/test/popups_v3/harness.dart b/test/popups_v3/harness.dart new file mode 100644 index 0000000..59217b0 --- /dev/null +++ b/test/popups_v3/harness.dart @@ -0,0 +1,319 @@ +import 'dart:async'; +import 'dart:convert'; + +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_v3/popup_v3.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_api.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_engine.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_frequency.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; + +/// Мост без натива: `did`, `sid` и вызовы профиля, подписки, ссылок. +class FakeHostApi extends pigeon.PersonalizationHostApi { + String? did = 'DID123'; + String sid = 'SID123'; + final List profiles = []; + final List subscriptions = + []; + final List opened = []; + + @override + Future initialize(pigeon.InitConfig config) async {} + + @override + Future getDid(String? shopId) async => did; + + @override + Future getSid(String? shopId) async => sid; + + @override + Future setProfile( + pigeon.ProfileParamsWire params, + String? shopId, + ) async => profiles.add(params); + + @override + Future manageSubscription( + pigeon.ManageSubscriptionParamsWire params, + String? shopId, + ) async => subscriptions.add(params); + + @override + Future openUrl(String url) async { + opened.add(url); + return true; + } +} + +/// Часы, которые идут только по [advance]. +class FakeClock implements PopupsV3Clock { + FakeClock([DateTime? start]) : _now = start ?? DateTime(2026, 11, 3, 12); + + DateTime _now; + final List<_FakeTimer> _timers = <_FakeTimer>[]; + + @override + DateTime now() => _now; + + @override + Timer timer(Duration delay, void Function() callback) { + final timer = _FakeTimer(_now.add(delay), callback); + _timers.add(timer); + return timer; + } + + /// Сдвинуть время на [by], срабатывая таймеры по порядку. + void advance(Duration by) { + final target = _now.add(by); + while (true) { + final due = + _timers + .where((timer) => timer.isActive && !timer.at.isAfter(target)) + .toList() + ..sort((a, b) => a.at.compareTo(b.at)); + if (due.isEmpty) break; + final timer = due.first; + _now = timer.at; + timer.fire(); + } + _now = target; + _timers.removeWhere((timer) => !timer.isActive); + } +} + +class _FakeTimer implements Timer { + _FakeTimer(this.at, this._callback); + + final DateTime at; + final void Function() _callback; + bool _active = true; + + void fire() { + _active = false; + _callback(); + } + + @override + void cancel() => _active = false; + + @override + bool get isActive => _active; + + @override + int get tick => 0; +} + +/// Показ без экрана: какие попапы на экране и их действия. +class FakePresenter implements PopupsV3Presenter { + final List shown = []; + final Map open = {}; + final Map actions = {}; + final Map> variables = >{}; + + @override + Future present( + PopupV3 popup, + Map variables, + PopupV3Actions actions, + ) async { + shown.add(popup.id); + this.actions[popup.id] = actions; + this.variables[popup.id] = variables; + return open[popup.id] = FakeShown(() => open.remove(popup.id)); + } + + /// Закрыть попап [id] пользователем. + void close(int id) { + actions[id]?.event(PopupV3Event.close); + open[id]?.dismiss(); + } +} + +class FakeShown implements PopupsV3Shown { + FakeShown(this._onClosed); + + final void Function() _onClosed; + final Completer _closed = Completer(); + + @override + Future get closed => _closed.future; + + @override + void dismiss() { + if (_closed.isCompleted) return; + _onClosed(); + _closed.complete(); + } +} + +/// Платформа движка поверх [FakeHostApi]; отзывы — в [reviews]. +class FakePlatform implements PopupsV3Platform { + FakePlatform(this.sdk, this.host); + + final PersonalizationSdk sdk; + final FakeHostApi host; + final List<({String kind, Map body})> reviews = + <({String kind, Map body})>[]; + Object? reviewError; + + @override + Future identity() async => + (shopId: 'c1140c8254976de297c3caf971701a', did: host.did!, sid: host.sid); + + @override + Future openUrl(String url) => sdk.openUrl(url); + + @override + Future manageSubscription(ManageSubscriptionParams params) => + sdk.manageSubscription(params); + + @override + Future setProfile(ProfileParams params) => sdk.setProfile(params); + + @override + Future review(String kind, Map body) async { + final error = reviewError; + if (error != null) throw error; + reviews.add((kind: kind, body: body)); + } +} + +/// Один HTTP-запрос. +typedef FakeRequest = ({String method, Uri uri, Map? body}); + +/// Сервер попапов: список, один попап, события, промокоды, сегменты. +class FakeServer { + FakeServer({List>? popups}) + : popups = popups ?? >[]; + + List> popups; + final List requests = []; + + /// Ответ на список: код и тело; `null` — список [popups]. + StoriesV3Response? listReply; + + /// Код ответа на события. + int eventsStatus = 200; + + /// Промокод; `null` — 404. + String? promoCode; + + Future send(String method, Uri uri, String? body) async { + requests.add(( + method: method, + uri: uri, + body: body == null ? null : jsonDecode(body) as Map, + )); + final path = uri.path; + if (path == '/api/v3/storefront/popups') { + return listReply ?? + ( + status: 200, + body: jsonEncode({ + 'status': 'success', + 'payload': {'ttl': 300, 'popups': popups}, + }), + ); + } + if (path.endsWith('/events')) { + return (status: eventsStatus, body: '{"status":"success"}'); + } + final one = RegExp(r'^/api/v3/storefront/popups/(\d+)$').firstMatch(path); + if (one != null) { + final id = int.parse(one.group(1)!); + for (final popup in popups) { + if (popup['id'] == id) { + return ( + status: 200, + body: jsonEncode({ + 'status': 'success', + 'payload': {'popup': popup}, + }), + ); + } + } + return ( + status: 404, + body: '{"status":"fail","message":"Resource not found"}', + ); + } + if (path == '/promo_codes/fetch') { + final code = promoCode; + return code == null + ? ( + status: 404, + body: + '{"status":"error","message":"Promo codes list is not found"}', + ) + : (status: 200, body: jsonEncode({'code': code})); + } + if (path == '/segments/add') { + return (status: 200, body: '{"status":"success"}'); + } + return (status: 404, body: '{}'); + } + + List where(bool Function(FakeRequest request) test) => + requests.where(test).toList(); + + List get lists => + where((request) => request.uri.path == '/api/v3/storefront/popups'); + + /// События: `(id, event)`. + List get events => [ + for (final request in where( + (request) => request.uri.path.endsWith('/events'), + )) + '${request.uri.pathSegments[4]}:${request.body!['event']}', + ]; +} + +/// Движок на подставных часах, сервере, хранилище и показе. +class EngineHarness { + EngineHarness({ + FakeServer? server, + PopupsV3MemoryStorage? storage, + FakeClock? clock, + FakeHostApi? host, + }) : server = server ?? FakeServer(), + storage = storage ?? PopupsV3MemoryStorage(), + clock = clock ?? FakeClock(), + host = host ?? FakeHostApi() { + sdk = PersonalizationSdk( + api: this.host, + shopId: 'c1140c8254976de297c3caf971701a', + ); + platform = FakePlatform(sdk, this.host); + engine = PopupsV3Engine( + sdk: sdk, + platform: platform, + presenter: presenter, + api: PopupsV3Api(send: this.server.send, now: this.clock.now), + storage: this.storage, + clock: this.clock, + ); + } + + final FakeServer server; + final PopupsV3MemoryStorage storage; + final FakeClock clock; + final FakeHostApi host; + final FakePresenter presenter = FakePresenter(); + late final PersonalizationSdk sdk; + late final FakePlatform platform; + late final PopupsV3Engine engine; + + /// Тот же «телефон» после перезапуска приложения: хранилище, часы, сервер и сеанс + /// прежние, движок новый. + EngineHarness restart() => + EngineHarness(server: server, storage: storage, clock: clock, host: host); +} + +/// Товар для действий рекомендаций. +const PersonalizationProduct fakeProduct = PersonalizationProduct( + id: '868', + name: 'Товар', + price: '100 ₽', + url: 'https://demo.rees46.ru/product/868', +); diff --git a/test/popups_v3/popups_v3_actions_test.dart b/test/popups_v3/popups_v3_actions_test.dart new file mode 100644 index 0000000..21b057e --- /dev/null +++ b/test/popups_v3/popups_v3_actions_test.dart @@ -0,0 +1,269 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_engine.dart'; +import 'package:rees46_sdk/src/ui/components/personalization_product.dart'; + +import 'fixtures.dart'; +import 'harness.dart'; + +/// Движок с показанным вручную попапом [fixture] (`id` фикстуры). +Future<({EngineHarness harness, PopupV3Actions actions})> _shown( + String fixture, +) async { + final popup = popupsV3Fixture(fixture); + final harness = EngineHarness( + server: FakeServer(popups: >[popup]), + ); + await harness.engine.show(popup['id'] as int); + await pumpEventQueue(); + return ( + harness: harness, + actions: harness.presenter.actions[popup['id'] as int]!, + ); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(PopupsV3Slots.reset); + + test( + 'email: subscription with the flags, then the segment, then events', + () async { + final shown = await _shown('element-email-collector.json'); + await shown.actions.subscribeEmail( + email: 'demo+flutter@rees46.test', + consentFields: const ['email_bulk', 'email_chain'], + segmentId: '123', + ); + await pumpEventQueue(); + final subscription = shown.harness.host.subscriptions.single; + expect(subscription.email, 'demo+flutter@rees46.test'); + expect(subscription.emailBulk, isTrue); + expect(subscription.emailChain, isTrue); + expect(subscription.emailTransactional, isNull); + final segment = shown.harness.server.requests.firstWhere( + (request) => request.uri.path == '/segments/add', + ); + expect(segment.body!['segment_id'], 123); + expect(segment.body!['did'], 'DID123'); + expect(shown.harness.server.events, [ + '9106:show', + '9106:subscribe', + '9106:submit', + ]); + final subscribe = shown.harness.server.requests.firstWhere( + (request) => request.body?['event'] == 'subscribe', + ); + expect(subscribe.body!['channel'], 'email'); + }, + ); + + test( + 'form: the profile, consent flags with the contact, the segment', + () async { + final shown = await _shown('element-form.json'); + await shown.actions.submitProfile( + const PopupV3ProfileSubmission( + email: 'anna@example.com', + phone: '+79990000000', + firstName: 'Анна', + lastName: 'Иванова', + birthday: '1990-04-12', + gender: 'f', + custom: { + 'fav_color': 'зелёный', + 'loyaltylevel': 'gold', + }, + consentFields: ['email_bulk'], + segmentId: '456', + ), + ); + await pumpEventQueue(); + final profile = shown.harness.host.profiles.single; + expect(profile.email, 'anna@example.com'); + expect(profile.phone, '+79990000000'); + expect(profile.firstName, 'Анна'); + expect(profile.lastName, 'Иванова'); + expect(profile.birthday, '1990-04-12'); + expect(profile.gender, 'f'); + expect(profile.customPropertiesJson, contains('fav_color')); + final subscription = shown.harness.host.subscriptions.single; + expect(subscription.email, 'anna@example.com'); + expect(subscription.emailBulk, isTrue); + expect( + shown.harness.server.requests + .where((request) => request.uri.path == '/segments/add') + .single + .body!['segment_id'], + 456, + ); + expect(shown.harness.server.events.last, '9107:submit'); + }, + ); + + test('form without consent: no subscription', () async { + final shown = await _shown('element-form.json'); + await shown.actions.submitProfile( + const PopupV3ProfileSubmission(firstName: 'Анна'), + ); + expect(shown.harness.host.subscriptions, isEmpty); + expect(shown.harness.host.profiles.single.firstName, 'Анна'); + }); + + test( + 'survey: NPS by category, CSAT and CES by campaign, comment trimmed', + () async { + final requests = popupsV3Fixture('requests.json'); + final shown = await _shown('element-survey.json'); + await shown.actions.review( + kind: 'nps', + code: 'test', + rate: 0, + comment: 'Долгая доставка', + ); + await shown.actions.review( + kind: 'csat', + code: 'MNTEST', + rate: 5, + comment: ' ', + ); + await shown.actions.review(kind: 'ces', code: 'MN TEST', rate: 7); + Map body(String name) => { + for (final entry + in ((requests[name] as Map)['json'] + as Map) + .entries) + if (!['shop_id', 'did', 'sid'].contains(entry.key)) + entry.key: entry.value, + }; + final reviews = shown.harness.platform.reviews; + expect(reviews.map((review) => review.kind), [ + 'nps', + 'csat', + 'ces', + ]); + expect(reviews[0].body, body('review_nps')); + expect(reviews[1].body, body('review_csat_no_comment')); + expect(reviews[2].body, { + 'channel': 'popup', + 'campaign': 'MN TEST', + 'rate': 7, + }); + await pumpEventQueue(); + expect( + shown.harness.server.events.where((event) => event.endsWith('submit')), + hasLength(3), + ); + }, + ); + + test('a failed review throws and sends no submit', () async { + final shown = await _shown('element-survey.json'); + shown.harness.platform.reviewError = Exception('Channel not found'); + await expectLater( + shown.actions.review(kind: 'nps', code: '', rate: 9), + throwsException, + ); + await pumpEventQueue(); + expect(shown.harness.server.events, ['9109:show']); + }); + + test('links: the host handler first, unsafe schemes never', () async { + final shown = await _shown('element-button.json'); + expect(shown.actions.openLink('https://demo.rees46.ru/'), isFalse); + expect(shown.actions.openLink('javascript:alert(1)'), isFalse); + expect(shown.actions.openLink(' '), isFalse); + await pumpEventQueue(); + expect(shown.harness.host.opened, ['https://demo.rees46.ru/']); + final handled = []; + shown.harness.engine.onLink = (url) { + handled.add(url); + return true; + }; + expect(shown.actions.openLink('rees46demo://sale'), isTrue); + await pumpEventQueue(); + expect(handled, ['rees46demo://sale']); + expect(shown.harness.host.opened, hasLength(1)); + }); + + test('links: declined or failed by the host handler — the system', () async { + final shown = await _shown('element-button.json'); + shown.harness.engine.onLink = (url) => false; + expect(shown.actions.openLink('https://demo.rees46.ru/a'), isFalse); + shown.harness.engine.onLink = (url) => throw StateError('no screen'); + expect(shown.actions.openLink('https://demo.rees46.ru/b'), isFalse); + await pumpEventQueue(); + expect(shown.harness.host.opened, [ + 'https://demo.rees46.ru/a', + 'https://demo.rees46.ru/b', + ]); + expect(shown.harness.engine.openIds, [9103]); + }); + + test('products: the host opens them, otherwise the product link', () async { + final shown = await _shown('element-recommendation.json'); + expect(shown.actions.openProduct(fakeProduct), isFalse); + await pumpEventQueue(); + expect(shown.harness.host.opened, [fakeProduct.url!]); + + final taken = []; + shown.harness.engine.onProductClick = (product) { + taken.add(product.id); + return true; + }; + expect(shown.actions.openProduct(fakeProduct), isTrue); + await pumpEventQueue(); + expect(taken, ['868']); + expect(shown.harness.host.opened, hasLength(1)); + }); + + test('products: declined or failed by the host — the deeplink, else the url, ' + 'through the link handler, which may open them', () async { + final shown = await _shown('element-recommendation.json'); + final links = []; + shown.harness.engine.onLink = (url) { + links.add(url); + return true; + }; + shown.harness.engine.onProductClick = (product) => false; + expect( + shown.actions.openProduct( + const PersonalizationProduct( + id: '868', + name: 'Товар', + price: '100 ₽', + url: 'https://demo.rees46.ru/product/868', + deeplink: 'rees46demo://product/868', + ), + ), + isTrue, + ); + shown.harness.engine.onProductClick = (product) => + throw StateError('no shop'); + expect( + shown.actions.openProduct( + const PersonalizationProduct( + id: '868', + name: 'Товар', + price: '100 ₽', + url: 'https://demo.rees46.ru/product/868', + deeplink: ' ', + ), + ), + isTrue, + ); + await pumpEventQueue(); + expect(links, [ + 'rees46demo://product/868', + 'https://demo.rees46.ru/product/868', + ]); + expect(shown.harness.host.opened, isEmpty); + }); + + test('the close event comes from the presenter', () async { + final shown = await _shown('element-text.json'); + shown.harness.presenter.close(9101); + await pumpEventQueue(); + expect(shown.harness.server.events, ['9101:show', '9101:close']); + expect(shown.harness.engine.openIds, isEmpty); + }); +} diff --git a/test/popups_v3/popups_v3_api_test.dart b/test/popups_v3/popups_v3_api_test.dart new file mode 100644 index 0000000..7e8d736 --- /dev/null +++ b/test/popups_v3/popups_v3_api_test.dart @@ -0,0 +1,257 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/personalization_sdk.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_api.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; + +import 'fixtures.dart'; +import 'harness.dart'; + +const PopupsV3Identity _id = ( + shopId: 'c1140c8254976de297c3caf971701a', + did: 'DID123', + sid: 'SID123', +); + +/// URL из фикстуры: путь и параметры (порядок параметров не важен). +void _expectUrl(Uri actual, Map request) { + final expected = Uri.parse(request['url'] as String); + expect(actual.scheme, expected.scheme); + expect(actual.host, expected.host); + expect(actual.path, expected.path); + expect(actual.queryParameters, expected.queryParameters); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final requests = popupsV3Fixture('requests.json'); + Map request(String name) => + requests[name] as Map; + + group('requests.json', () { + test('the list, with test mode and debug', () { + _expectUrl(PopupsV3Api.listUri('app.rees46.ru', _id), request('list')); + _expectUrl( + PopupsV3Api.listUri('app.rees46.ru', _id, testMode: true, debug: true), + request('list_testmode_debug'), + ); + }); + + test('one popup, with test mode', () { + _expectUrl(PopupsV3Api.oneUri('app.rees46.ru', 516, _id), request('one')); + _expectUrl( + PopupsV3Api.oneUri('app.rees46.ru', 516, _id, testMode: true), + request('one_testmode'), + ); + }); + + test('events: channel only with subscribe', () { + _expectUrl( + PopupsV3Api.eventsUri('app.rees46.ru', 512), + request('event_show'), + ); + expect( + PopupsV3Api.eventBody(_id, PopupV3Event.show, channel: 'email'), + request('event_show')['json'], + ); + expect( + PopupsV3Api.eventBody(_id, PopupV3Event.subscribe, channel: 'email'), + request('event_subscribe')['json'], + ); + }); + + test('the promo code', () { + _expectUrl( + PopupsV3Api.promoUri('api.rees46.ru', _id, '7'), + request('promo'), + ); + }); + + test('segments/add by did', () async { + final server = FakeServer(); + await PopupsV3Api( + send: server.send, + ).segmentAdd('api.rees46.ru', _id, '123'); + final sent = server.requests.single; + final expected = request('segment_add'); + expect(sent.method, expected['method']); + expect(sent.uri.toString(), expected['url']); + expect(sent.body, containsPair('shop_id', _id.shopId)); + (expected['json_subset'] as Map).forEach( + (key, value) => expect(sent.body![key], value, reason: key), + ); + }); + + test( + 'reviews go to /polls/{kind}/reviews with the popup channel', + () async { + final host = FakeHostApi(); + final sdk = PersonalizationSdk(api: host, shopId: _id.shopId); + final sent = []; + final original = StoriesApiV3.send; + addTearDown(() => StoriesApiV3.send = original); + StoriesApiV3.send = (method, uri, body) async { + sent.add(( + method: method, + uri: uri, + body: jsonDecode(body!) as Map, + )); + return (status: 200, body: '{"status":"success"}'); + }; + addTearDown(PopupsV3.reset); + final popups = sdk.popups..appHost = 'https://app.rees46.ru/'; + Map body(String name) => { + for (final entry + in (request(name)['json'] as Map).entries) + if (!['shop_id', 'did', 'sid'].contains(entry.key)) + entry.key: entry.value!, + }; + await popups.engine.platform.review('nps', body('review_nps')); + await popups.engine.platform.review( + 'csat', + body('review_csat_no_comment'), + ); + final nps = request('review_nps'); + expect(sent.first.uri.toString(), nps['url']); + expect(sent.first.body, nps['json']); + final csat = request('review_csat_no_comment'); + expect(sent.last.uri.toString(), csat['url']); + expect(sent.last.body, csat['json']); + }, + ); + }); + + group('error-responses.json', () { + final errors = popupsV3Fixture('error-responses.json'); + + test( + 'the list: 4xx is a client error, 5xx and no network are failures', + () async { + for (final name in [ + 'list_400', + 'list_402', + 'list_403', + 'list_404', + ]) { + final status = int.parse(name.substring(5)); + final api = PopupsV3Api( + send: (method, uri, body) async => + (status: status, body: jsonEncode(errors[name])), + ); + final result = await api.list('app.rees46.ru', _id); + expect(result.outcome, PopupsV3ListOutcome.clientError, reason: name); + expect(result.list.popups, isEmpty); + } + final down = PopupsV3Api( + send: (method, uri, body) async => (status: 502, body: 'Bad gateway'), + ); + expect( + (await down.list('app.rees46.ru', _id)).outcome, + PopupsV3ListOutcome.failure, + ); + final offline = PopupsV3Api( + send: (method, uri, body) async => throw Exception('offline'), + ); + expect( + (await offline.list('app.rees46.ru', _id)).outcome, + PopupsV3ListOutcome.failure, + ); + }, + ); + + test('one popup: 404 is nothing, with the reason', () async { + final api = PopupsV3Api( + send: (method, uri, body) async => + (status: 404, body: jsonEncode(errors['one_404'])), + ); + String? reason; + expect( + await api.one( + 'app.rees46.ru', + 1, + _id, + onError: (error) => reason = error, + ), + isNull, + ); + expect(reason, contains('Resource not found')); + }); + + test('events: 429 pauses sending for a minute', () async { + final clock = FakeClock(); + var calls = 0; + var status = 429; + final api = PopupsV3Api( + now: clock.now, + send: (method, uri, body) async { + calls++; + return (status: status, body: jsonEncode(errors['events_429'])); + }, + ); + expect(await api.event('app.rees46.ru', 1, _id, PopupV3Event.show), 429); + status = 200; + expect( + await api.event('app.rees46.ru', 1, _id, PopupV3Event.click), + isNull, + ); + expect(calls, 1); + clock.advance(const Duration(seconds: 61)); + expect(await api.event('app.rees46.ru', 1, _id, PopupV3Event.click), 200); + expect(calls, 2); + }); + + test('events: one retry on 5xx and no network, none on 4xx', () async { + final statuses = [503, 200]; + var calls = 0; + final api = PopupsV3Api( + send: (method, uri, body) async { + calls++; + final status = statuses.removeAt(0); + if (status == null) throw Exception('offline'); + return (status: status, body: '{}'); + }, + ); + expect(await api.event('app.rees46.ru', 1, _id, PopupV3Event.show), 200); + expect(calls, 2); + + calls = 0; + statuses.addAll([null, null]); + expect( + await api.event('app.rees46.ru', 1, _id, PopupV3Event.show), + isNull, + ); + expect(calls, 2); + + calls = 0; + statuses.add(400); + expect(await api.event('app.rees46.ru', 1, _id, PopupV3Event.show), 400); + expect(calls, 1); + }); + + test( + 'promo codes: 404 is no code; a code is remembered for 2 hours', + () async { + final clock = FakeClock(); + var calls = 0; + var reply = (status: 404, body: jsonEncode(errors['promo_404'])); + final api = PopupsV3Api( + now: clock.now, + send: (method, uri, body) async { + calls++; + return reply; + }, + ); + expect(await api.promoCode('api.rees46.ru', _id, '7'), isNull); + reply = (status: 200, body: jsonEncode(errors['promo_ok'])); + expect(await api.promoCode('api.rees46.ru', _id, '7'), 'ABC123'); + expect(await api.promoCode('api.rees46.ru', _id, '7'), 'ABC123'); + expect(calls, 2); + clock.advance(const Duration(hours: 2, seconds: 1)); + reply = (status: 200, body: '{"code":"NEW"}'); + expect(await api.promoCode('api.rees46.ru', _id, '7'), 'NEW'); + }, + ); + }); +} diff --git a/test/popups_v3/popups_v3_design_test.dart b/test/popups_v3/popups_v3_design_test.dart new file mode 100644 index 0000000..edfa024 --- /dev/null +++ b/test/popups_v3/popups_v3_design_test.dart @@ -0,0 +1,661 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/popups_v3/popup_v3.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/css_color.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_markup.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_v3_design.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_v3_elements.dart'; + +import 'fixtures.dart'; + +final Set _types = popupV3ElementBuilders.keys.toSet(); + +PopupV3Design _design( + Map popup, { + Map runtime = const {}, + TargetPlatform platform = TargetPlatform.android, +}) => PopupV3Design.parse( + popup['design'] as Map, + layout: PopupV3Layout.parse(popup['layout'])!, + types: _types, + runtime: runtime, + platform: platform, +); + +Map _span(PopupMarkupSpan span) => { + 'text': span.text, + if (span.bold) 'bold': true, + if (span.italic) 'italic': true, + if (span.underline) 'underline': true, + if (span.strike) 'strike': true, + if (span.overline) 'overline': true, +}; + +String _hex(Color color) => cssColorHex(color); + +void main() { + test('element-text.json: markup, numbers as strings, shadow alpha, link', () { + final fixture = popupsV3Fixture('element-text.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + + final full = design.element('el-text-full')!; + final fullExpect = expectations['el-text-full'] as Map; + final box = full.box; + expect( + design.variables.rich(full.text('message')).map(_span).toList(), + fullExpect['spans'], + ); + expect(full.messageAlign, TextAlign.center); + expect(full.alignIn(PopupV3Align.left), PopupV3Align.center); + expect(full.messageFontSize, fullExpect['fontSize']); + expect(full.messageFontWeight, fullExpect['fontWeight']); + expect(box.lineHeight, fullExpect['lineHeight']); + expect(box.letterSpacing, fullExpect['letterSpacing']); + expect(box.opacity, fullExpect['opacity']); + expect(box.paddingX, fullExpect['paddingX']); + expect(box.paddingY, fullExpect['paddingY']); + expect(_hex(box.textColor), fullExpect['textColor']); + expect(_hex(box.background), fullExpect['bgColor']); + expect(_hex(box.borderColor), fullExpect['borderColor']); + final shadow = fullExpect['shadow'] as Map; + expect(box.shadow!.y, shadow['y']); + expect(box.shadow!.blur, shadow['blur']); + expect(_hex(box.shadow!.color), shadow['color']); + expect(full.link(design.variables), fullExpect['link']); + + final bare = design.element('el-text-bare')!; + final bareExpect = expectations['el-text-bare'] as Map; + expect(bare.messageFontSize, bareExpect['fontSize']); + expect(bare.messageFontWeight, bareExpect['fontWeight']); + expect(_hex(bare.box.background), bareExpect['bgColor']); + expect(_hex(bare.box.textColor), bareExpect['textColor']); + expect(bare.box.lineHeight, bareExpect['lineHeight']); + expect(bare.messageAlign, TextAlign.left); + expect(bare.box.shadow, isNull); + + // CSS-позиционирование не поддерживается, элемент остаётся в потоке. + expect(design.element('el-text-css-position'), isNotNull); + }); + + test('element-box.json: the box defaults and an empty plate', () { + final fixture = popupsV3Fixture('element-box.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + for (final id in ['el-box-defaults', 'el-box-empty']) { + final element = design.element(id)!; + final expected = expectations[id] as Map; + expect(_hex(element.box.background), expected['bgColor'], reason: id); + expect(element.box.radius, expected['borderRadius'], reason: id); + expect(element.box.paddingX, expected['paddingX'], reason: id); + expect(element.box.paddingY, expected['paddingY'], reason: id); + } + expect(design.element('el-box-defaults')!.messageFontSize, 12); + expect(design.element('el-box-empty')!.text('message'), isNull); + }); + + group('element-button.json', () { + final fixture = popupsV3Fixture('element-button.json'); + final expectations = popupsV3Expect(fixture); + + test('actions, hrefs and copy texts', () { + final android = _design(fixture); + final ios = _design(fixture, platform: TargetPlatform.iOS); + final link = android.element('el-btn-link')!; + final linkExpect = expectations['el-btn-link'] as Map; + final href = linkExpect['href'] as Map; + expect(link.buttonAction, 'link'); + expect(link.buttonHref(android.variables), href['android']); + expect( + ios.element('el-btn-link')!.buttonHref(ios.variables), + href['ios'], + ); + expect( + android.variables.rich(link.text('buttonText')).map(_span).toList(), + linkExpect['spans'], + ); + expect(link.alignIn(PopupV3Align.center), PopupV3Align.left); + expect(_hex(link.color('buttonBgColor', '#000')), linkExpect['bgColor']); + expect( + _hex(link.color('buttonTextColor', '#000')), + linkExpect['textColor'], + ); + expect(link.number('buttonFontSize', 12), linkExpect['fontSize']); + expect(link.number('buttonRadius', 0), linkExpect['radius']); + expect(link.number('buttonPaddingX', 0), linkExpect['paddingX']); + expect(link.number('buttonPaddingY', 0), linkExpect['paddingY']); + // Обёртка кнопки без фона и рамки. + expect(link.box.background.a, 0); + + expect( + android.element('el-btn-ios-var')!.buttonHref(android.variables), + (expectations['el-btn-ios-var'] as Map)['href'], + ); + expect(android.element('el-btn-close')!.buttonAction, 'close'); + final copy = android.element('el-btn-copy')!; + expect(copy.buttonAction, 'copy'); + expect( + copy.copyText(android.variables), + (expectations['el-btn-copy'] as Map)['clipboard'], + ); + expect( + android.element('el-btn-copy-fallback')!.copyText(android.variables), + (expectations['el-btn-copy-fallback'] + as Map)['clipboard'], + ); + final legacy = android.element('el-btn-legacy-href')!; + expect(legacy.buttonAction, 'link'); + expect( + legacy.buttonHref(android.variables), + (expectations['el-btn-legacy-href'] as Map)['href'], + ); + final unknown = android.element('el-btn-unknown-action')!; + expect(unknown.buttonAction, 'link'); + expect( + unknown.buttonHref(android.variables), + (expectations['el-btn-unknown-action'] as Map)['href'], + ); + }); + + test('an empty button takes the editor defaults', () { + final design = _design(fixture); + final button = design.element('el-btn-defaults')!; + final expected = expectations['el-btn-defaults'] as Map; + expect(button.buttonAction, expected['action']); + expect(button.text('buttonText'), isNull); + expect(button.alignIn(PopupV3Align.left), PopupV3Align.center); + expect(_hex(button.color('buttonBgColor', '#000')), expected['bgColor']); + expect( + _hex(button.color('buttonTextColor', '#000')), + expected['textColor'], + ); + expect(button.number('buttonFontSize', 12), expected['fontSize']); + expect(button.number('buttonPaddingX', 0), expected['paddingX']); + expect(button.number('buttonPaddingY', 0), expected['paddingY']); + expect(button.number('buttonRadius', 0), expected['radius']); + expect(button.buttonHref(design.variables), isNull); + }); + }); + + test('element-close.json: modes, the × default, size 8–128', () { + final fixture = popupsV3Fixture('element-close.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + + final close = design.element('el-close-default')!; + final closeExpect = + expectations['el-close-default'] as Map; + expect(close.buttonAction, 'close'); + expect(close.closeMode, closeExpect['mode']); + expect(close.text('buttonText'), isNull); + expect(close.alignIn(PopupV3Align.left), PopupV3Align.right); + expect(_hex(close.color('buttonBgColor', '#000')), closeExpect['bgColor']); + expect( + _hex(close.color('buttonTextColor', '#000')), + closeExpect['textColor'], + ); + expect(close.number('buttonFontSize', 0), closeExpect['fontSize']); + expect(close.number('buttonPaddingX', 0), closeExpect['paddingX']); + expect(close.number('buttonPaddingY', 0), closeExpect['paddingY']); + expect(close.number('buttonRadius', 0), closeExpect['radius']); + + final text = design.element('el-close-text')!; + expect(text.text('buttonText'), 'Закрыть ×'); + expect(text.alignIn(PopupV3Align.right), PopupV3Align.left); + expect(text.number('buttonFontSize', 22), 16); + + final image = design.element('el-close-image')!; + final imageExpect = expectations['el-close-image'] as Map; + expect(image.closeMode, 'image'); + expect(image.closeImageUrl(design.variables), imageExpect['url']); + expect(image.closeIconSize, imageExpect['size']); + + final svg = design.element('el-close-svg')!; + expect(svg.closeMode, 'svg'); + expect(svg.closeIconSize, 8); + expect(svg.closeSvg, isNot(contains('script'))); + expect(svg.closeSvg, isNot(contains('onload'))); + expect(svg.closeSvg, startsWith('; + expect(auto.stretch, isTrue); + expect( + popupV3ImageUrl(auto.text('imageUrl'), design.variables), + autoExpect['url'], + ); + expect(auto.imageHeight, const PopupV3ImageHeight.auto()); + expect(auto.imageFit, BoxFit.cover); + expect(auto.number('imageRadius', 0), autoExpect['radius']); + expect(auto.number('imageMarginBottom', 0), autoExpect['marginBottom']); + expect(auto.link(design.variables), autoExpect['link']); + + final px = design.element('el-img-px')!; + expect(px.imageHeight, const PopupV3ImageHeight.px(180)); + expect(px.imageFit, BoxFit.contain); + expect( + design.element('el-img-percent')!.imageHeight, + const PopupV3ImageHeight.percent(100), + ); + final vh = design.element('el-img-vh')!.imageHeight; + expect(vh, const PopupV3ImageHeight.vh(40)); + expect(vh.resolve(800), 320); + expect( + design.element('el-img-ratio')!.imageAspectRatio, + closeTo(1.7778, 0.0001), + ); + final bad = design.element('el-img-bad-ratio')!; + expect(bad.imageAspectRatio, isNull); + expect(bad.imageFit, BoxFit.cover); + expect(design.element('el-img-hidden')!.showImage, isFalse); + }); + + test('element-email-collector.json: layouts, consent fields, success', () { + final fixture = popupsV3Fixture('element-email-collector.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + + final inline = design.element('el-email-inline')!; + final inlineExpect = + expectations['el-email-inline'] as Map; + expect(inline.emailInline, isTrue); + expect(inline.emailConsentFields, inlineExpect['consentFields']); + expect( + design.variables.rich(inline.emailConsentLabel).map(_span).toList(), + inlineExpect['consentSpans'], + ); + expect(inline.segmentId('emailSegmentId'), inlineExpect['segmentId']); + final success = inlineExpect['success'] as Map; + expect(inline.text('emailSuccessTitle'), success['title']); + expect(inline.text('emailSuccessMessage'), success['message']); + expect(_hex(inline.color('emailSuccessBg', '#000')), success['bg']); + expect(inline.value('emailSuccessAlign'), success['align']); + + final legacy = design.element('el-email-stacked-legacy')!; + final legacyExpect = + expectations['el-email-stacked-legacy'] as Map; + expect(legacy.emailInline, isFalse); + expect(legacy.emailConsentFields, legacyExpect['consentFields']); + expect(legacy.emailConsentLabel, legacyExpect['consentLabel']); + + final bare = design.element('el-email-bare')!; + final bareExpect = expectations['el-email-bare'] as Map; + expect(bare.emailInline, isFalse); + expect(bare.emailConsentFields, bareExpect['consentFields']); + expect(bare.emailConsentLabel, isNull); + expect(bare.segmentId('emailSegmentId'), isNull); + // Коробка формы: белый фон, текст #0f172a, радиус 12, поля 12. + expect(_hex(bare.box.background), '#ffffffff'); + expect(_hex(bare.box.textColor), '#0f172aff'); + expect(bare.box.radius, 12); + expect(bare.box.paddingX, 12); + }); + + test('element-form.json: fields normalized like the compiler', () { + final fixture = popupsV3Fixture('element-form.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + final form = design.element('el-form')!; + final expected = expectations['el-form'] as Map; + expect( + >[ + for (final field in form.formFields) + { + 'id': field.id, + 'kind': field.kind, + 'required': field.required, + 'propertyKey': field.propertyKey, + }, + ], + >[ + for (final field + in (expected['fields'] as List).cast>()) + { + 'id': field['id'], + 'kind': field['kind'], + 'required': field['required'], + 'propertyKey': field['propertyKey'], + }, + ], + ); + expect(form.formConsentFields, expected['consentFields']); + expect(form.segmentId('formSegmentId'), expected['segmentId']); + + final bare = design.element('el-form-bare')!; + expect(bare.formFields, isEmpty); + expect(bare.formConsentFields, isEmpty); + }); + + test('element-promo-code.json: personal and static codes', () { + final fixture = popupsV3Fixture('element-promo-code.json'); + final expectations = popupsV3Expect(fixture); + final design = _design( + fixture, + runtime: {'promo_code': 'ABC123'}, + ); + + final personal = design.element('el-promo-personal')!; + final personalExpect = + expectations['el-promo-personal'] as Map; + expect(personal.promoStatic, isFalse); + expect(personal.promoCode(design.variables), 'ABC123'); + expect(personal.value('messageAlign'), personalExpect['align']); + expect( + personal.number('promoCodeFontSize', 20), + personalExpect['fontSize'], + ); + expect(personal.promoShowCopy, isTrue); + expect(personal.text('promoCopiedText'), 'Скопировано!'); + expect( + personal.promoApplyHref(design.variables), + 'rees46demo://cart?promo=ABC123', + ); + + final stat = design.element('el-promo-static')!; + expect(stat.promoStatic, isTrue); + expect( + stat.promoCode(design.variables), + (expectations['el-promo-static'] as Map)['code'], + ); + expect(stat.promoShowCopy, isFalse); + + final text = design.element('el-text-with-code')!; + expect( + design.variables.rich(text.text('message')).map(_span).toList(), + (expectations['el-text-with-code'] + as Map)['spans_after_substitution_example'], + ); + }); + + test('element-survey.json: scales and codes', () { + final fixture = popupsV3Fixture('element-survey.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + for (final id in [ + 'el-survey-nps', + 'el-survey-csat', + 'el-survey-ces', + 'el-survey-unknown', + ]) { + final element = design.element(id)!; + final scale = (expectations[id] as Map)['scale'] as List; + expect(element.surveyScale.first, scale.first, reason: id); + expect(element.surveyScale.last, scale.last, reason: id); + } + expect(design.element('el-survey-unknown')!.surveyType, 'nps'); + expect( + design.element('el-survey-ces')!.string('surveyCampaignCode'), + 'MN TEST', + ); + final csat = design.element('el-survey-csat')!; + final defaults = + (expectations['el-survey-csat'] as Map)['defaults'] + as Map; + expect(_hex(csat.color('surveyScaleBg', '#000')), defaults['scaleBg']); + expect( + _hex(csat.color('surveyScaleActiveBg', '#000')), + defaults['activeBg'], + ); + expect(csat.text('surveySubmitText'), isNull); + // Без bgColor у опроса — белая коробка компилятора. + expect(_hex(csat.box.background), '#ffffffff'); + }); + + test( + 'element-recommendation.json: the block code; a blank code is dropped', + () { + final fixture = popupsV3Fixture('element-recommendation.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + final block = design.element('el-rec')!; + expect( + block.recommenderCode, + (expectations['el-rec'] as Map)['code'], + ); + // Коробка рекомендаций прозрачная, без отступов, даже если они заданы. + expect(block.box.background.a, 0); + expect(block.box.paddingX, 0); + expect(design.element('el-rec-empty')!.recommenderCode, isNull); + }, + ); + + test('grid.json: fractions, alignment, order, defaults, dropped', () { + final fixture = popupsV3Fixture('grid.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + final rows = expectations['rows'] as Map; + for (final row in design.rows) { + final expected = rows[row.id] as Map; + final fractions = (expected['fractions'] as List).cast(); + expect(row.fractions.length, fractions.length, reason: row.id); + for (final (index, fraction) in row.fractions.indexed) { + expect(fraction, closeTo(fractions[index], 0.0001), reason: row.id); + } + expect(row.gap, expected['gap'], reason: row.id); + expect(row.minHeight, expected['minHeight'], reason: row.id); + final cells = expected['cells']; + if (cells is List) { + for (final (index, cell) in row.cells.indexed) { + final expectedCell = cells[index] as Map; + expect( + cell.align.name, + expectedCell['align'], + reason: '${row.id}[$index]', + ); + expect( + cell.verticalAlign.name, + expectedCell['verticalAlign'], + reason: '${row.id}[$index]', + ); + expect( + cell.elements.map((element) => element.id).toList(), + expectedCell['elements'], + reason: '${row.id}[$index]', + ); + } + } + } + final rowC = design.rows.firstWhere((row) => row.id == 'row-c'); + final background = + (rows['row-c'] as Map)['background'] + as Map; + expect(_hex(rowC.background!), background['color']); + expect(rowC.backgroundImage, background['image']); + expect(rowC.backgroundSize, background['size']); + expect(rowC.backgroundPosition, background['position']); + expect(rowC.backgroundRepeat, background['repeat']); + expect( + design.element('c1')!.alignIn(rowC.cells[1].align), + PopupV3Align.right, + ); + final rowD = design.rows.firstWhere((row) => row.id == 'row-d'); + expect(rowD.cells.length, 6); + expect(rowD.cells[5].elements.single.id, 'd5'); + expect( + design.dropped.keys.toSet(), + (expectations['dropped'] as List).toSet(), + ); + }); + + group('layouts.json', () { + final fixture = popupsV3Fixture('layouts.json'); + final expectations = popupsV3Expect(fixture); + final popups = (fixture['popups'] as List).cast>(); + PopupV3Design design(int id) => + _design(popups.firstWhere((popup) => popup['id'] == id)); + + test('a top banner: no overlay, offsets, full width', () { + final frame = design(9201).frame; + expect(frame.overlay.enabled, isFalse); + expect(frame.offsetX, 12); + expect(frame.offsetY, 16); + expect(frame.lockBackground, isFalse); + final metrics = frame.metrics(const Size(390, 844)); + // Экран − 2×12. + expect(metrics.resolveWidth(390 - 2 * frame.offsetX), 366); + expect(metrics.maxWidth, isNull); + }); + + test('a bottom banner with an overlay and a locked background', () { + final frame = design(9202).frame; + final expected = expectations['9202'] as Map; + final overlay = expected['overlay'] as Map; + expect(frame.overlay.enabled, isTrue); + expect(frame.overlay.color.a, closeTo(overlay['opacity'] as num, 0.01)); + expect(frame.lockBackground, isTrue); + expect(frame.offsetX, 0); + }); + + test('a modal: the overlay by default, min height, frame', () { + final frame = design(9203).frame; + expect(frame.overlay.enabled, isTrue); + expect(cssColorHex(frame.overlay.color), '#00000080'); + final metrics = frame.metrics(const Size(390, 844)); + expect(metrics.resolveWidth(390), closeTo(358.8, 0.01)); + expect(metrics.minHeight, 200); + expect(metrics.radius, 16); + expect(metrics.padding, 20); + expect(frame.borderWidth, 1); + expect(cssColorHex(frame.borderColor), '#e5e7ebff'); + }); + + test('fullscreen: no overlay', () { + final frame = design(9204).frame; + expect(frame.overlay.enabled, isFalse); + expect(cssColorHex(frame.background), '#0f172aff'); + }); + }); + + test('breakpoints.json: the frame on screens 390, 414 and 800', () { + final fixture = popupsV3Fixture('breakpoints.json'); + final expectations = popupsV3Expect(fixture); + final frame = _design(fixture).frame; + for (final width in [390, 414, 800]) { + final expected = expectations['screen_$width'] as Map; + final metrics = frame.metrics(Size(width.toDouble(), 800)); + expect( + metrics.resolveWidth(width.toDouble()), + closeTo(expected['width'] as num, 0.01), + reason: 'screen $width', + ); + if (expected.containsKey('maxWidth')) { + expect(metrics.maxWidth, expected['maxWidth'], reason: 'screen $width'); + } + expect(metrics.padding, expected['padding'], reason: 'screen $width'); + expect(metrics.radius, expected['borderRadius'], reason: 'screen $width'); + if (expected.containsKey('minHeight')) { + expect( + metrics.minHeight, + expected['minHeight'], + reason: 'screen $width', + ); + } + } + }); + + test('variables.json: static, runtime and unknown keys', () { + final fixture = popupsV3Fixture('variables.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + final statics = Map.from( + expectations['static_variables'] as Map, + )..remove('promo_code'); + expect(design.variables.statics, statics); + final text = design.element('t')!.string('message'); + expect(design.variables.applyStatic(text), expectations['t_after_static']); + final withCode = PopupV3Variables( + statics: design.variables.statics, + runtime: const {'promo_code': 'ABC123'}, + ); + expect(withCode.apply(text), expectations['t_at_show_with_code_ABC123']); + expect( + design.element('b')!.buttonHref(design.variables), + expectations['b_href'], + ); + expect( + popupV3ImageUrl(design.element('i')!.text('imageUrl'), design.variables), + expectations['i_url'], + ); + expect( + design.variables.apply(design.element('e')!.string('emailPlaceholder')), + expectations['e_placeholder'], + ); + }); + + test( + 'unknown-element.json: unknown types are skipped, a bad style is empty', + () { + final fixture = popupsV3Fixture('unknown-element.json'); + final expectations = popupsV3Expect(fixture); + final design = _design(fixture); + expect( + design.elements.map((element) => element.id).toList(), + expectations['rendered'], + ); + expect(design.dropped.keys.toSet(), { + 'wheel', + 'countdown', + 'no-type', + }); + expect(design.element('bad-style')!.style, isEmpty); + }, + ); + + test('legacy-free-elements.json: in the flow by y, then x', () { + final fixture = popupsV3Fixture('legacy-free-elements.json'); + final design = _design(fixture); + expect( + design.elements.map((element) => element.id).toList(), + popupsV3Expect(fixture)['order'], + ); + }); + + test('empty-design.json: the empty frame, nothing to show', () { + final fixture = popupsV3Fixture('empty-design.json'); + final design = _design(fixture); + expect(design.isEmpty, isTrue); + final metrics = design.frame.metrics(const Size(1000, 800)); + expect(metrics.resolveWidth(1000), 480); + expect(metrics.height, isNull); + expect(cssColorHex(design.frame.background), '#ffffffff'); + expect(metrics.radius, 16); + expect(metrics.padding, 20); + }); + + test('live-list-181-182.json: both designs parse whole', () { + final fixture = popupsV3Fixture('live-list-181-182.json'); + final popups = + ((fixture['payload'] as Map)['popups'] as List) + .cast>(); + final banner = _design(popups.first); + expect(banner.dropped, isEmpty); + expect(banner.elements.map((element) => element.type).toList(), [ + 'close', + 'text', + 'button', + 'image', + 'emailCollector', + 'survey', + ]); + expect(banner.rows.single.minHeight, 60); + expect(banner.frame.overlay.enabled, isFalse); + final modal = _design(popups.last); + expect(modal.elements.map((element) => element.type).toList(), [ + 'promoCode', + 'survey', + 'recommendation', + ]); + expect( + modal.element('el-mw0k6x8f-r')!.promoCode(modal.variables), + 'Fix Test', + ); + expect(modal.frame.overlay.enabled, isTrue); + }); +} diff --git a/test/popups_v3/popups_v3_engine_test.dart b/test/popups_v3/popups_v3_engine_test.dart new file mode 100644 index 0000000..a482d44 --- /dev/null +++ b/test/popups_v3/popups_v3_engine_test.dart @@ -0,0 +1,535 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/personalization_sdk.dart'; +import 'package:rees46_sdk/src/popups_v3/popup_v3.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_engine.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_frequency.dart'; +import 'package:rees46_sdk/src/sdk_init_config.dart'; + +import 'fixtures.dart'; +import 'harness.dart'; + +/// Попапы `list-response.json` по id. +Map> _listPopups() { + final fixture = popupsV3Fixture('list-response.json'); + return >{ + for (final popup + in ((fixture['payload'] as Map)['popups'] as List) + .cast>()) + popup['id'] as int: popup, + }; +} + +/// Попап [id] из списка, с правками [changes]. +Map _popup( + int id, [ + Map changes = const {}, +]) => {..._listPopups()[id]!, ...changes}; + +Future _started(List> popups) async { + final harness = EngineHarness(server: FakeServer(popups: popups)); + await harness.engine.start(); + await pumpEventQueue(); + return harness; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(PopupsV3Slots.reset); + + group('scenarios.json', () { + test('the fixture has 18 scenarios', () { + expect( + (popupsV3Fixture('scenarios.json')['scenarios'] as List).length, + 18, + ); + }); + + test('app_start without screens: shown at list loaded', () async { + final harness = await _started(>[_popup(512)]); + expect(harness.presenter.shown, [512]); + expect(harness.server.events, ['512:show']); + }); + + test('app_start waits for a matching screen', () async { + final harness = await _started(>[ + _popup(512, { + 'target_screens': ['product'], + }), + ]); + expect(harness.presenter.shown, isEmpty); + harness.engine.screenOpened('home'); + await pumpEventQueue(); + expect(harness.presenter.shown, isEmpty); + harness.engine.screenOpened('product'); + await pumpEventQueue(); + expect(harness.presenter.shown, [512]); + }); + + test('screen_open on a listed screen', () async { + final harness = await _started(>[_popup(513)]); + harness.engine.screenOpened('home'); + await pumpEventQueue(); + expect(harness.presenter.shown, isEmpty); + harness.engine.screenOpened('product'); + await pumpEventQueue(); + expect(harness.presenter.shown, [513]); + }); + + test('screen_open with no screens: any screen', () async { + final harness = await _started(>[ + _popup(513, {'target_screens': []}), + ]); + harness.engine.screenOpened('home'); + await pumpEventQueue(); + expect(harness.presenter.shown, [513]); + }); + + test('time_on_screen: left the screen early', () async { + final harness = await _started(>[_popup(514)]); + harness.engine.screenOpened('home'); + harness.clock.advance(const Duration(seconds: 9)); + harness.engine.screenOpened('category'); + harness.clock.advance(const Duration(seconds: 11)); + await pumpEventQueue(); + expect(harness.presenter.shown, isEmpty); + }); + + test('time_on_screen: stayed long enough', () async { + final harness = await _started(>[_popup(514)]); + harness.engine.screenOpened('home'); + harness.clock.advance(const Duration(milliseconds: 9900)); + await pumpEventQueue(); + expect(harness.presenter.shown, isEmpty); + harness.clock.advance(const Duration(milliseconds: 100)); + await pumpEventQueue(); + expect(harness.presenter.shown, [514]); + }); + + test('time_on_screen: the background resets the timer', () async { + final harness = await _started(>[_popup(514)]); + harness.engine.screenOpened('home'); + harness.clock.advance(const Duration(seconds: 5)); + harness.engine.onBackground(); + harness.clock.advance(const Duration(seconds: 25)); + harness.engine.onForeground(); + harness.clock.advance(const Duration(seconds: 9)); + await pumpEventQueue(); + expect(harness.presenter.shown, isEmpty); + harness.clock.advance(const Duration(seconds: 1)); + await pumpEventQueue(); + expect(harness.presenter.shown, [514]); + }); + + test('track_event', () async { + final harness = await _started(>[_popup(515)]); + harness.engine.onTrackEvent('other'); + await pumpEventQueue(); + expect(harness.presenter.shown, isEmpty); + harness.engine.onTrackEvent('promo_view'); + await pumpEventQueue(); + expect(harness.presenter.shown, [515]); + }); + + test( + 'track_event on another screen does not wait for the screen', + () async { + final harness = await _started(>[ + _popup(515, { + 'target_screens': ['cart'], + }), + ]); + harness.engine.screenOpened('home'); + harness.engine.onTrackEvent('promo_view'); + harness.engine.screenOpened('cart'); + await pumpEventQueue(); + expect(harness.presenter.shown, isEmpty); + }, + ); + + test('manual: GET the popup, show it, no frequency', () async { + final harness = await _started(>[_popup(516)]); + harness.engine.screenOpened('home'); + await pumpEventQueue(); + expect(harness.presenter.shown, isEmpty); + await harness.engine.show(516); + await pumpEventQueue(); + expect(harness.presenter.shown, [516]); + expect( + harness.server.requests.map((request) => request.uri.path), + contains('/api/v3/storefront/popups/516'), + ); + expect(harness.storage.shows[516], isNull); + }); + + test( + 'once_session: shown, not again in the session, again in a new one', + () async { + final first = await _started(>[_popup(512)]); + expect(first.presenter.shown, [512]); + first.presenter.close(512); + await pumpEventQueue(); + + final sameSession = first.restart(); + await sameSession.engine.start(); + await pumpEventQueue(); + expect(sameSession.presenter.shown, isEmpty); + + sameSession.host.sid = 'SID456'; + final newSession = sameSession.restart(); + await newSession.engine.start(); + await pumpEventQueue(); + expect(newSession.presenter.shown, [512]); + }, + ); + + test( + 'app_start once_session: not again on other screens, again in a new session', + () async { + final harness = await _started(>[_popup(512)]); + harness.presenter.close(512); + await pumpEventQueue(); + await harness.engine.refresh(); + harness.engine.screenOpened('home'); + harness.engine.screenOpened('product'); + await pumpEventQueue(); + expect(harness.presenter.shown, [512]); + harness.host.sid = 'SID456'; + harness.engine.onBackground(); + harness.engine.onForeground(); + await pumpEventQueue(); + expect(harness.presenter.shown, [512, 512]); + }, + ); + + test('once_day with a 60 minute cooldown', () async { + final harness = await _started(>[_popup(513)]); + final shown = []; + Future visit(Duration after) async { + harness.clock.advance(after); + final before = harness.presenter.shown.length; + harness.engine.screenOpened('product'); + await pumpEventQueue(); + shown.add(harness.presenter.shown.length > before); + if (harness.presenter.open.containsKey(513)) { + harness.presenter.close(513); + await pumpEventQueue(); + } + } + + await visit(Duration.zero); + await visit(const Duration(minutes: 30)); + await visit(const Duration(hours: 23) - const Duration(minutes: 30)); + await visit(const Duration(hours: 1)); + expect(shown, [true, false, false, true]); + }); + + test('every_page: once per screen opening', () async { + final rules = PopupsV3FrequencyRules(PopupsV3MemoryStorage()); + final popup = PopupV3.tryParse( + _popup(512, {'frequency': 'every_page'}), + )!; + final now = DateTime(2026, 11, 3); + expect(await rules.check(popup, now: now, sid: 's'), isNull); + await rules.record(popup, now: now, sid: 's'); + expect(await rules.check(popup, now: now, sid: 's'), isNotNull); + rules.newPage(); + expect(await rules.check(popup, now: now, sid: 's'), isNull); + + // app_start с every_page: показ на каждом экране, но раз на экран. + final harness = EngineHarness( + server: FakeServer( + popups: >[ + _popup(512, {'frequency': 'every_page'}), + ], + ), + ); + harness.engine.screenOpened('home'); + await harness.engine.start(); + await pumpEventQueue(); + expect(harness.presenter.shown, [512]); + harness.presenter.close(512); + await pumpEventQueue(); + await harness.engine.refresh(force: true); + await pumpEventQueue(); + expect(harness.presenter.shown, [512]); + harness.engine.screenOpened('product'); + await pumpEventQueue(); + expect(harness.presenter.shown, [512, 512]); + + // track_event с every_page — так же. + harness.presenter.close(512); + await pumpEventQueue(); + final events = await _started(>[ + _popup(515, {'frequency': 'every_page'}), + ]); + events.engine.screenOpened('home'); + events.engine.onTrackEvent('promo_view'); + await pumpEventQueue(); + events.presenter.close(515); + await pumpEventQueue(); + events.engine.onTrackEvent('promo_view'); + await pumpEventQueue(); + expect(events.presenter.shown, [515]); + events.engine.screenOpened('product'); + events.engine.onTrackEvent('promo_view'); + await pumpEventQueue(); + expect(events.presenter.shown, [515, 515]); + }); + + test('test mode writes no frequency', () async { + final popups = >[ + _popup(512, {'frequency': 'once_life'}), + ]; + final first = EngineHarness(server: FakeServer(popups: popups)) + ..engine.testMode = true; + await first.engine.start(); + await pumpEventQueue(); + expect(first.presenter.shown, [512]); + expect(first.storage.shows, isEmpty); + expect(first.server.lists.single.uri.queryParameters['testmode'], 'true'); + first.presenter.close(512); + await pumpEventQueue(); + final second = first.restart()..engine.testMode = true; + await second.engine.start(); + await pumpEventQueue(); + expect(second.presenter.shown, [512]); + }); + + test('one modal: the second waits for the first to close', () async { + final harness = await _started(>[ + _popup(513), + _popup(513, {'id': 613}), + ]); + harness.engine.screenOpened('product'); + await pumpEventQueue(); + expect(harness.presenter.shown, [513]); + expect(harness.engine.queuedIds, [613]); + harness.presenter.close(513); + await pumpEventQueue(); + expect(harness.presenter.shown, [513, 613]); + }); + + test('a banner does not wait for the modal', () async { + final harness = await _started(>[ + _popup(512), + _popup(514, { + 'trigger_type': 'app_start', + 'target_screens': [], + }), + ]); + expect(harness.presenter.shown, unorderedEquals([512, 514])); + expect(harness.presenter.open.keys, unorderedEquals([512, 514])); + }); + + test('no promo code: no show and no show event', () async { + final promo = popupsV3Fixture('element-promo-code.json'); + final harness = await _started(>[ + _popup(519, {'design': promo['design']}), + ]); + expect(harness.presenter.shown, isEmpty); + expect(harness.server.events, isEmpty); + expect( + harness.server.requests.last.uri.toString(), + 'https://api.rees46.ru/promo_codes/fetch?shop_id=c1140c8254976de297c3caf971701a&did=DID123&sid=SID123&id=7', + ); + }); + + test('a promo code becomes the promo_code variable', () async { + final promo = popupsV3Fixture('element-promo-code.json'); + final server = FakeServer( + popups: >[ + _popup(519, {'design': promo['design']}), + ], + )..promoCode = 'ABC123'; + final harness = EngineHarness(server: server); + await harness.engine.start(); + await pumpEventQueue(); + expect(harness.presenter.shown, [519]); + expect(harness.presenter.variables[519], { + 'promo_code': 'ABC123', + }); + }); + + test('a context change refetches the list once per new data', () async { + final harness = await _started(>[_popup(513)]); + expect(harness.server.lists, hasLength(1)); + harness.engine.onContextChanged('profile', 'set', { + 'email': 'a@b.c', + }); + harness.clock.advance(const Duration(seconds: 1)); + await pumpEventQueue(); + expect(harness.server.lists, hasLength(1)); + harness.clock.advance(const Duration(seconds: 1)); + await pumpEventQueue(); + expect(harness.server.lists, hasLength(2)); + harness.engine.onContextChanged('profile', 'set', { + 'email': 'a@b.c', + }); + harness.clock.advance(const Duration(seconds: 3)); + await pumpEventQueue(); + expect(harness.server.lists, hasLength(2)); + harness.engine.onPurchase(); + harness.clock.advance(const Duration(seconds: 2)); + await pumpEventQueue(); + expect(harness.server.lists, hasLength(3)); + }); + }); + + group('list cache', () { + test('a valid cache is used; an expired one is requested again', () async { + final harness = await _started(>[_popup(513)]); + await harness.engine.refresh(); + expect(harness.server.lists, hasLength(1)); + harness.clock.advance(const Duration(seconds: 301)); + await harness.engine.refresh(); + expect(harness.server.lists, hasLength(2)); + }); + + test( + '4xx is cached as an empty list for 300 s; 5xx is not cached', + () async { + final server = FakeServer(popups: >[_popup(512)]) + ..listReply = (status: 402, body: '{"status":"fail"}'); + final harness = EngineHarness(server: server); + await harness.engine.start(); + await harness.engine.refresh(); + expect(server.lists, hasLength(1)); + expect(harness.engine.popups, isEmpty); + + harness.clock.advance(const Duration(seconds: 301)); + server.listReply = (status: 503, body: 'down'); + await harness.engine.refresh(); + await harness.engine.refresh(); + expect(server.lists, hasLength(3)); + + server.listReply = null; + await harness.engine.refresh(); + await pumpEventQueue(); + expect(harness.presenter.shown, [512]); + }, + ); + + test('events sent before the list arrives fire once it does', () async { + final harness = EngineHarness( + server: FakeServer(popups: >[_popup(515)]), + ); + final start = harness.engine.start(); + harness.engine.onTrackEvent('promo_view'); + await start; + await pumpEventQueue(); + expect(harness.presenter.shown, [515]); + }); + + test('a screen opened before the list arrives still counts', () async { + final harness = EngineHarness( + server: FakeServer(popups: >[_popup(513)]), + ); + harness.engine.screenOpened('product'); + await harness.engine.start(); + await pumpEventQueue(); + expect(harness.presenter.shown, [513]); + }); + + test('a stopped engine makes no requests', () async { + final harness = EngineHarness( + server: FakeServer(popups: >[_popup(512)]), + ); + harness.engine.screenOpened('home'); + harness.engine.onTrackEvent('promo_view'); + await harness.engine.refresh(); + await pumpEventQueue(); + expect(harness.server.requests, isEmpty); + }); + }); + + group('automatic presentation', () { + test('off: triggers are skipped, a manual show is shown', () async { + final harness = EngineHarness( + server: FakeServer(popups: >[_popup(512)]), + ); + harness.engine.autoPresentation = () => false; + await harness.engine.start(); + harness.engine.screenOpened('home'); + await pumpEventQueue(); + expect(harness.presenter.shown, isEmpty); + expect(harness.server.events, isEmpty); + expect(harness.storage.shows[512], isNull); + + await harness.engine.show(512); + await pumpEventQueue(); + expect(harness.presenter.shown, [512]); + expect(harness.server.events, ['512:show']); + }); + + test('follows enableAutoPopupPresentation of the init', () async { + addTearDown(PopupsV3.reset); + final sdk = PersonalizationSdk( + api: FakeHostApi(), + shopId: 'c1140c8254976de297c3caf971701a', + ); + expect(sdk.popups.engine.autoPresentation(), isTrue); + await sdk.initialize( + const SdkInitConfig( + shopId: 'c1140c8254976de297c3caf971701a', + enableAutoPopupPresentation: false, + ), + ); + expect(sdk.popups.engine.autoPresentation(), isFalse); + await sdk.initialize( + const SdkInitConfig(shopId: 'c1140c8254976de297c3caf971701a'), + ); + expect(sdk.popups.engine.autoPresentation(), isTrue); + }); + + test('follows enableAutoPopupPresentation changed on the go', () async { + addTearDown(PopupsV3.reset); + final sdk = PersonalizationSdk( + api: FakeHostApi(), + shopId: 'c1140c8254976de297c3caf971701a', + ); + await sdk.initialize( + const SdkInitConfig(shopId: 'c1140c8254976de297c3caf971701a'), + ); + sdk.enableAutoPopupPresentation = false; + expect(sdk.popups.engine.autoPresentation(), isFalse); + sdk.enableAutoPopupPresentation = true; + expect(sdk.popups.engine.autoPresentation(), isTrue); + }); + }); + + group('slots', () { + test('a modal waits for an old popup on screen', () async { + var legacy = true; + PopupsV3Slots.legacyModal = () => legacy; + final harness = await _started(>[ + _popup(512), + _popup(514, { + 'trigger_type': 'app_start', + 'target_screens': [], + }), + ]); + expect(harness.presenter.shown, [514]); + legacy = false; + PopupsV3Slots.notify(); + await pumpEventQueue(); + expect(harness.presenter.shown, [514, 512]); + expect(PopupsV3Slots.isTaken(PopupsV3Slots.modal), isTrue); + harness.presenter.close(512); + await pumpEventQueue(); + expect(PopupsV3Slots.isTaken(PopupsV3Slots.modal), isFalse); + }); + + test('two shops share the modal slot', () async { + final first = await _started(>[_popup(512)]); + final second = await _started(>[ + _popup(512, {'id': 712}), + ]); + expect(first.presenter.shown, [512]); + expect(second.presenter.shown, isEmpty); + first.presenter.close(512); + await pumpEventQueue(); + expect(second.presenter.shown, [712]); + }); + }); +} diff --git a/test/popups_v3/popups_v3_model_test.dart b/test/popups_v3/popups_v3_model_test.dart new file mode 100644 index 0000000..6e90294 --- /dev/null +++ b/test/popups_v3/popups_v3_model_test.dart @@ -0,0 +1,133 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/popups_v3/popup_v3.dart'; + +import 'fixtures.dart'; + +void main() { + group('list-response.json', () { + final fixture = popupsV3Fixture('list-response.json'); + final expectations = popupsV3Expect(fixture); + final list = PopupsV3List.parse(fixture['payload'] as Map); + + test('ttl as a string', () { + expect(list.ttl, Duration(seconds: expectations['ttl_seconds'] as int)); + }); + + test('mobile triggers are armed, manual is only manual', () { + final byTrigger = [ + for (final popup in list.popups) + if (popup.trigger != PopupV3Trigger.manual) popup.id, + ]; + expect(byTrigger, expectations['armed']); + expect([ + for (final popup in list.popups) + if (popup.trigger == PopupV3Trigger.manual) popup.id, + ], expectations['manual_only']); + }); + + test('a web trigger and a web layout are skipped with a reason', () { + final skipped = expectations['skipped_logged'] as Map; + expect( + list.skipped.keys.map((id) => '$id').toSet(), + skipped.keys.toSet(), + ); + expect(list.skipped[517], contains('trigger')); + expect(list.skipped[518], contains('layout')); + }); + + test('nulls take the defaults', () { + final manual = list.popups.firstWhere((popup) => popup.id == 516); + expect(manual.frequency, PopupV3Frequency.onceSession); + expect(manual.targetScreens, isEmpty); + final event = list.popups.firstWhere((popup) => popup.id == 515); + expect(event.cooldownMinutes, 0); + expect(event.triggerEvent, 'promo_view'); + final time = list.popups.firstWhere((popup) => popup.id == 514); + expect(time.triggerDelay, const Duration(seconds: 10)); + expect(time.placement, PopupV3Placement.bottom); + expect(time.isModal, isFalse); + }); + + test('excluded popups are kept for the debug log', () { + expect(>[ + for (final item in list.excluded) + {'id': item.id, 'reason': item.reason}, + ], expectations['excluded_logged_in_debug']); + }); + + test('a promo list without {{promo_code}} needs no code', () { + final promo = list.popups.firstWhere((popup) => popup.id == 519); + expect(promo.promoCodeListId, '7'); + expect(promo.needsPromoCode, isFalse); + }); + }); + + test('popup-response.json: the manual popup', () { + final fixture = popupsV3Fixture('popup-response.json'); + final popup = PopupV3.tryParse( + (fixture['payload'] as Map)['popup'], + )!; + expect(popup.id, popupsV3Expect(fixture)['id']); + expect(popup.layout, PopupV3Layout.fullscreen); + expect(popup.isModal, isTrue); + }); + + test('element-promo-code.json: a personal code element needs the code', () { + final popup = PopupV3.tryParse(popupsV3Fixture('element-promo-code.json'))!; + expect(popup.needsPromoCode, isTrue); + expect( + PopupV3( + id: 1, + layout: PopupV3Layout.modal, + placement: PopupV3Placement.center, + trigger: PopupV3Trigger.manual, + promoCodeListId: '7', + design: const { + 'elements': [ + { + 'type': 'promoCode', + 'style': {'promoSource': 'static'}, + }, + ], + }, + ).needsPromoCode, + isFalse, + ); + }); + + test('live-list-181-182.json: the banner and the modal of the demo shop', () { + final fixture = popupsV3Fixture('live-list-181-182.json'); + final list = PopupsV3List.parse(fixture['payload'] as Map); + expect(list.popups.map((popup) => popup.id), [181, 182]); + final banner = list.popups.first; + expect(banner.layout, PopupV3Layout.banner); + expect(banner.placement, PopupV3Placement.top); + expect(banner.trigger, PopupV3Trigger.appStart); + expect(banner.frequency, PopupV3Frequency.onceSession); + expect(banner.needsPromoCode, isFalse); + final modal = list.popups.last; + expect(modal.layout, PopupV3Layout.modal); + expect(modal.placement, PopupV3Placement.center); + expect(modal.isModal, isTrue); + }); + + test('ids as strings, unknown frequency, bad screens', () { + final popup = PopupV3.tryParse({ + 'id': '42', + 'layout': 'banner', + 'placement': 'center', + 'trigger_type': 'screen_open', + 'frequency': 'sometimes', + 'target_screens': [' home ', '', null, 5], + 'cooldown_minutes': '15', + })!; + expect(popup.id, 42); + expect(popup.placement, PopupV3Placement.top); + expect(popup.frequency, PopupV3Frequency.onceSession); + expect(popup.targetScreens, ['home', '5']); + expect(popup.cooldownMinutes, 15); + expect(popup.matchesScreen('home'), isTrue); + expect(popup.matchesScreen(null), isFalse); + expect(PopupV3.tryParse({'layout': 'modal'}), isNull); + }); +} diff --git a/test/popups_v3/popups_v3_parsing_test.dart b/test/popups_v3/popups_v3_parsing_test.dart new file mode 100644 index 0000000..94a44ae --- /dev/null +++ b/test/popups_v3/popups_v3_parsing_test.dart @@ -0,0 +1,100 @@ +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/popups_v3/popup_v3_values.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/css_color.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_markup.dart'; + +import 'fixtures.dart'; + +Map _span(PopupMarkupSpan span) => { + 'text': span.text, + if (span.bold) 'bold': true, + if (span.italic) 'italic': true, + if (span.underline) 'underline': true, + if (span.strike) 'strike': true, + if (span.overline) 'overline': true, +}; + +void main() { + final parsing = popupsV3Fixture('parsing.json'); + + group('parsing.json', () { + test('colors: CSS → #rrggbbaa or nothing', () { + for (final vector in parsing['colors'] as List) { + final item = vector as Map; + final color = parseCssColor(item['in']); + expect( + color == null ? null : cssColorHex(color), + item['out'], + reason: 'in: ${item['in']}', + ); + } + }); + + test('numbers: a number, a string with a number or the fallback', () { + for (final vector in parsing['numbers'] as List) { + final item = vector as Map; + expect( + cssNum(item['in'], (item['fallback'] as num).toDouble()), + (item['out'] as num).toDouble(), + reason: 'in: ${item['in']}', + ); + } + }); + + test('booleans', () { + for (final vector in parsing['booleans'] as List) { + final item = vector as Map; + expect(cssBool(item['in']), item['out'], reason: 'in: ${item['in']}'); + } + }); + }); + + group('markup.json', () { + final markup = popupsV3Fixture('markup.json'); + final cases = + (markup['_fixture'] as Map)['expect'] as List; + + test('left to right, no nesting, HTML stays text', () { + for (final item in cases.cast>()) { + expect( + parsePopupMarkup(item['input'] as String).map(_span).toList(), + item['spans'], + reason: 'input: ${item['input']}', + ); + } + }); + + test('the spans become a text span with the base style', () { + final span = popupMarkupTextSpan( + parsePopupMarkup('**a** __b__ ~~c~~ ^^d^^ *e*'), + const TextStyle(fontSize: 14), + ); + final children = span.children!.cast(); + expect(span.style!.fontSize, 14); + expect(children.first.style!.fontWeight, FontWeight.w700); + expect(children[2].style!.decoration, TextDecoration.underline); + expect(children[4].style!.decoration, TextDecoration.lineThrough); + expect(children[6].style!.decoration, TextDecoration.overline); + expect(children[8].style!.fontStyle, FontStyle.italic); + }); + }); + + group('values', () { + test('presence: blank strings and non-strings are missing', () { + expect(cssPresent(' '), isNull); + expect(cssPresent(''), isNull); + expect(cssPresent(null), isNull); + expect(cssPresent(' a '), ' a '); + expect(cssPresent(7), '7'); + expect(cssPresent(7.5), '7.5'); + }); + + test('rgb with percents and out-of-range channels', () { + expect(cssColorHex(parseCssColor('rgb(100%, 0%, 50%)')!), '#ff0080ff'); + expect(cssColorHex(parseCssColor('rgba(300, -5, 0, 2)')!), '#ff0000ff'); + expect(parseCssColor('rgb(1, 2)'), isNull); + expect(parseCssColor('#12345'), isNull); + }); + }); +} diff --git a/test/popups_v3/popups_v3_render_test.dart b/test/popups_v3/popups_v3_render_test.dart new file mode 100644 index 0000000..3b8ff50 --- /dev/null +++ b/test/popups_v3/popups_v3_render_test.dart @@ -0,0 +1,1097 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/personalization_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/popups_v3/popup_v3.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_api.dart'; +import 'package:rees46_sdk/src/popups_v3/popups_v3_engine.dart'; +import 'package:rees46_sdk/src/ui/components/personalization_checkbox.dart'; +import 'package:rees46_sdk/src/ui/components/personalization_product.dart'; +import 'package:rees46_sdk/src/ui/components/personalization_product_card.dart'; +import 'package:rees46_sdk/src/ui/personalization_colors.dart'; +import 'package:rees46_sdk/src/ui/personalization_theme.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_v3_design.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_v3_elements.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_v3_grid.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_v3_host.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_v3_texts.dart'; +import 'package:rees46_sdk/src/ui/popups_v3/popup_v3_view.dart'; +import 'package:rees46_sdk/src/ui/widgets/personalization_request_cache.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; + +import 'fixtures.dart'; +import 'harness.dart'; + +/// Действия попапа, записанные для проверки. +class RecordingActions implements PopupV3Actions { + RecordingActions({FakeHostApi? host}) + : sdk = PersonalizationSdk(api: host ?? FakeHostApi(), shopId: 'shop'); + + @override + final PersonalizationSdk sdk; + + final List events = []; + final List links = []; + final List calls = []; + Object? error; + + @override + void event(PopupV3Event event, {String? channel}) => + events.add(channel == null ? event.wire : '${event.wire}:$channel'); + + /// Что ответит [openLink]: ссылку открыл хост. + bool hostOpensLinks = false; + + @override + bool openLink(String url) { + links.add(url); + return hostOpensLinks; + } + + /// Что ответит [openProduct]: товар открыл хост. + bool hostOpensProducts = false; + + @override + bool openProduct(PersonalizationProduct product) { + calls.add('product ${product.id}'); + return hostOpensProducts; + } + + Future _call(String call) async { + calls.add(call); + final error = this.error; + if (error != null) throw error; + } + + @override + Future subscribeEmail({ + required String email, + required List consentFields, + String? segmentId, + }) => _call('subscribe $email $consentFields $segmentId'); + + @override + Future submitProfile(PopupV3ProfileSubmission submission) => _call( + 'profile ${submission.email} ${submission.phone} ${submission.firstName} ' + '${submission.custom} ${submission.consentFields} ${submission.segmentId}', + ); + + @override + Future review({ + required String kind, + required String code, + required int rate, + String? comment, + }) => _call('review $kind "$code" $rate "${comment ?? ''}"'); +} + +/// Мост, который отвечает на рекомендации живым ответом из test/fixtures без картинок +/// (в виджет-тестах они не грузятся). +class _RecommendationsHostApi extends FakeHostApi { + @override + Future getRecommendation( + String code, + String? paramsJson, + String? shopId, + ) async { + final answer = + jsonDecode( + File('test/fixtures/recommend_extended.json').readAsStringSync(), + ) + as Map; + for (final product in (answer['recommends'] as List).cast()) { + product + ..remove('picture') + ..remove('image_url') + ..remove('image_url_resized'); + } + return jsonEncode(answer); + } + + @override + Future trackSetSource( + pigeon.TrackingSourceWire source, + String? shopId, + ) async {} +} + +/// Буфер обмена без платформы: что в него клали, по порядку. +List _mockClipboard(WidgetTester tester) { + final copied = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied.add( + (call.arguments as Map)['text'] as String?, + ); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + return copied; +} + +PopupV3Design _parse( + Map popup, { + Map runtime = const {}, +}) => PopupV3Design.parse( + popup['design'] as Map, + layout: PopupV3Layout.parse(popup['layout'])!, + types: popupV3ElementBuilders.keys.toSet(), + runtime: runtime, +); + +/// Цвета чекбокса согласия: пустой — фон и рамка поля, отмеченный — фон кнопки и +/// галка цветом её текста. +typedef _ConsentColors = ({ + Color field, + Color border, + Color button, + Color text, +}); + +/// Попап из одного элемента [type] со стилем [style]. +Map _single(String type, Map style) { + final popup = popupsV3Fixture('element-email-collector.json'); + final design = popup['design'] as Map; + design['rows'] = [(design['rows'] as List).first]; + design['elements'] = [ + { + 'id': 'el', + 'type': type, + 'rowId': 'row-1', + 'partIndex': 0, + 'style': style, + }, + ]; + return popup; +} + +/// Попап [popup] в рамке на экране 390×844. +Future<({RecordingActions actions, List closes})> _pump( + WidgetTester tester, + Map popup, { + double maxHeight = 760, + Map runtime = const {}, + RecordingActions? actions, + ThemeData? theme, +}) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + actions ??= RecordingActions(); + final closes = []; + final design = _parse(popup, runtime: runtime); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Scaffold( + body: PopupV3Scope( + design: design, + actions: actions, + texts: PopupV3Texts.ru, + onClose: () => closes.add('close'), + onDismiss: () => closes.add('dismiss'), + child: Material( + type: MaterialType.transparency, + child: Center( + child: PopupV3FrameView( + design: design, + layout: PopupV3Layout.parse(popup['layout'])!, + screen: const Size(390, 844), + maxWidth: 390, + maxHeight: maxHeight, + ), + ), + ), + ), + ), + ), + ); + await tester.pump(); + return (actions: actions, closes: closes); +} + +void main() { + const fixtures = [ + 'element-text.json', + 'element-box.json', + 'element-button.json', + 'element-close.json', + 'element-image.json', + 'element-email-collector.json', + 'element-form.json', + 'element-promo-code.json', + 'element-survey.json', + 'element-recommendation.json', + 'grid.json', + 'breakpoints.json', + 'variables.json', + 'markup.json', + 'unknown-element.json', + 'legacy-free-elements.json', + ]; + + for (final name in fixtures) { + testWidgets('$name renders without errors', (tester) async { + await _pump( + tester, + popupsV3Fixture(name), + runtime: const {'promo_code': 'ABC123'}, + ); + expect(tester.takeException(), isNull); + expect(find.byType(PopupV3FrameView), findsOneWidget); + }); + } + + testWidgets('layouts.json renders every layout', (tester) async { + for (final popup + in (popupsV3Fixture('layouts.json')['popups'] as List) + .cast>()) { + await _pump(tester, popup); + expect(tester.takeException(), isNull); + } + }); + + testWidgets('live 181 and 182 render all their elements', (tester) async { + final popups = + ((popupsV3Fixture('live-list-181-182.json')['payload'] + as Map)['popups'] + as List) + .cast>(); + await _pump(tester, popups.first); + expect(find.text('×'), findsOneWidget); + expect(find.text('Test !@#%\$%^&*'), findsOneWidget); + expect(find.text('Подробнее'), findsOneWidget); + expect(find.text('Подписаться'), findsOneWidget); + expect(find.text('Согласен получать рассылки'), findsOneWidget); + expect( + find.text('Насколько вероятно, что вы порекомендуете нас друзьям?'), + findsOneWidget, + ); + expect(find.text('10'), findsOneWidget); + await _pump(tester, popups.last); + expect(find.text('Fix Test'), findsOneWidget); + expect(find.text('Ваш промокод'), findsOneWidget); + expect(find.text('5'), findsOneWidget); + expect(find.text('6'), findsNothing); + }); + + testWidgets('a tall popup scrolls inside a frame that stays put', ( + tester, + ) async { + final popup = + ((popupsV3Fixture('live-list-181-182.json')['payload'] + as Map)['popups'] + as List) + .first + as Map; + await _pump(tester, popup, maxHeight: 300); + final frame = tester.getRect(find.byType(PopupV3FrameView)); + expect(frame.height, 300); + final question = find.text( + 'Насколько вероятно, что вы порекомендуете нас друзьям?', + ); + final before = tester.getTopLeft(question).dy; + await tester.drag( + find.byType(SingleChildScrollView), + const Offset(0, -200), + ); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(question).dy, lessThan(before)); + expect(tester.getRect(find.byType(PopupV3FrameView)), frame); + }); + + testWidgets('the row: fractions, gap, min height, cell alignment', ( + tester, + ) async { + await _pump(tester, popupsV3Fixture('grid.json')); + final rows = tester + .renderObjectList(find.byType(PopupV3RowLayout)) + .toList(); + // row-a: minHeight 80, две колонки по 50 % с промежутком 12. + expect(rows.first.size.height, greaterThanOrEqualTo(80)); + final rowA = find.byType(PopupV3RowLayout).first; + final cells = find.descendant( + of: rowA, + matching: find.byType(PopupV3CellLayout), + ); + final left = tester.getRect(cells.at(0)); + final right = tester.getRect(cells.at(1)); + expect(right.left - left.right, closeTo(12, 0.01)); + expect(left.width, closeTo(right.width, 0.01)); + expect(left.height, rows.first.size.height); + // a1 в правой ячейке — по центру по обеим осям. + final a1 = tester.getRect(find.text('A1')); + expect(a1.center.dx, closeTo(right.center.dx, 1)); + expect(a1.center.dy, closeTo(right.center.dy, 1)); + // row-b: выравнивание строки — справа и снизу. + final b0 = tester.getRect(find.text('B0')); + final rowB = tester.getRect(find.byType(PopupV3RowLayout).at(1)); + expect( + b0.right, + closeTo( + tester + .getRect( + find + .descendant( + of: find.byType(PopupV3RowLayout).at(1), + matching: find.byType(PopupV3CellLayout), + ) + .first, + ) + .right, + 0.5, + ), + ); + expect(b0.bottom, closeTo(rowB.bottom, 0.5)); + // row-d: шесть ячеек. + expect( + find.descendant( + of: find.byType(PopupV3RowLayout).at(3), + matching: find.byType(PopupV3CellLayout), + ), + findsNWidgets(6), + ); + expect(find.text('Нет такой строки'), findsNothing); + }); + + testWidgets('buttons: close, copy and link', (tester) async { + final copied = _mockClipboard(tester); + final pumped = await _pump(tester, popupsV3Fixture('element-button.json')); + await tester.tap(find.text('Не сейчас')); + expect(pumped.closes, ['close']); + await tester.tap(find.text('Скопировать код')); + await tester.pump(); + expect(pumped.actions.events, ['click']); + expect(copied, ['SALE10']); + expect(find.text('Скопировано'), findsOneWidget); + await tester.pump(const Duration(seconds: 3)); + await tester.tap(find.text('Старый документ')); + expect(pumped.actions.links, ['https://demo.rees46.ru']); + expect(find.text('Подробнее'), findsOneWidget); + await tester.tap(find.text('Подробнее')); + expect(pumped.actions.links, hasLength(1)); + expect(pumped.actions.events, ['click', 'click', 'click']); + }); + + testWidgets('the close element: × by default, images and SVG as a cross', ( + tester, + ) async { + final pumped = await _pump(tester, popupsV3Fixture('element-close.json')); + await tester.tap(find.text('×')); + expect(pumped.closes, ['close']); + expect(find.byType(PopupV3CloseCross), findsWidgets); + }); + + testWidgets('a text with a link opens it with a click event', (tester) async { + final pumped = await _pump(tester, popupsV3Fixture('element-text.json')); + await tester.tap(find.textContaining('Скидка 10%', findRichText: true)); + expect(pumped.actions.links, ['https://demo.rees46.ru/sale']); + expect(pumped.actions.events, ['click']); + }); + + testWidgets('email: consent and format are checked, then success', ( + tester, + ) async { + final pumped = await _pump( + tester, + popupsV3Fixture('element-email-collector.json'), + ); + final field = find.byType(TextField).first; + await tester.enterText(field, 'not an email'); + await tester.tap(find.text('Подписаться').first); + await tester.pump(); + expect(find.text('Проверьте email'), findsOneWidget); + expect(pumped.actions.calls, isEmpty); + + await tester.enterText(field, 'demo+flutter@rees46.test'); + await tester.tap( + find.textContaining('Согласен получать', findRichText: true), + ); + await tester.tap(find.text('Подписаться').first); + await tester.pumpAndSettle(); + expect(pumped.actions.calls, [ + 'subscribe demo+flutter@rees46.test [email_bulk, email_chain] 123', + ]); + expect(find.text('Готово!'), findsOneWidget); + expect(find.text('Проверьте почту'), findsOneWidget); + }); + + testWidgets( + 'email: a failed subscription shows an error and can be retried', + (tester) async { + final pumped = await _pump( + tester, + popupsV3Fixture('element-email-collector.json'), + ); + pumped.actions.error = Exception('offline'); + await tester.enterText(find.byType(TextField).first, 'a@b.ru'); + await tester.tap( + find.textContaining('Согласен получать', findRichText: true), + ); + await tester.tap(find.text('Подписаться').first); + await tester.pumpAndSettle(); + expect(find.text(PopupV3Texts.ru.sendError), findsOneWidget); + pumped.actions.error = null; + await tester.tap(find.text('Подписаться').first); + await tester.pumpAndSettle(); + expect(pumped.actions.calls, hasLength(2)); + expect(find.text('Готово!'), findsOneWidget); + }, + ); + + testWidgets('form: required fields, then the profile', (tester) async { + final pumped = await _pump(tester, popupsV3Fixture('element-form.json')); + await tester.tap(find.text('Сохранить')); + await tester.pump(); + expect(find.text('Заполните обязательные поля'), findsOneWidget); + final fields = find.byType(TextField); + await tester.enterText(fields.at(0), 'anna@example.com'); + await tester.enterText(fields.at(2), 'Анна'); + await tester.enterText(fields.at(4), 'зелёный'); + await tester.tap(find.text('Согласен на обработку данных')); + await tester.tap(find.text('Женский')); + await tester.ensureVisible(find.text('Сохранить')); + await tester.tap(find.text('Сохранить')); + await tester.pumpAndSettle(); + expect(pumped.actions.calls, [ + 'profile anna@example.com null Анна {fav_color: зелёный} [email_bulk] 456', + ]); + expect(find.text('Данные сохранены'), findsOneWidget); + }); + + group('consent checkbox in the form colors', () { + tearDown(() { + PersonalizationTheme.mode = ThemeMode.system; + PersonalizationTheme.configure(); + }); + + Finder box() => find.descendant( + of: find.byType(PersonalizationCheckbox), + matching: find.byType(CustomPaint), + ); + + const _ConsentColors designed = ( + field: Color(0xfffef3c7), + border: Color(0xffd97706), + button: Color(0xff16a34a), + text: Color(0xff111827), + ); + const _ConsentColors defaults = ( + field: Color(0xfff8fafc), + border: Color(0xffcbd5e1), + button: Color(0xff2563eb), + text: Color(0xffffffff), + ); + + for (final (type, prefix, extra) + in <(String, String, Map)>[ + ('emailCollector', 'email', const {}), + ( + 'form', + 'form', + const {'formConsentLabel': 'Согласен'}, + ), + ]) { + for (final (name, style, colors) + in <(String, Map, _ConsentColors)>[ + ('by default', extra, defaults), + ( + 'from the design', + { + ...extra, + '${prefix}InputBg': '#fef3c7', + '${prefix}InputBorderColor': '#d97706', + 'buttonBgColor': '#16a34a', + 'buttonTextColor': '#111827', + }, + designed, + ), + ]) { + for (final mode in [ThemeMode.light, ThemeMode.dark]) { + testWidgets('$type, $name, kit theme ${mode.name}: empty like the ' + 'field, checked like the button', (tester) async { + PersonalizationTheme.mode = mode; + await _pump(tester, _single(type, style)); + expect( + box(), + paints + ..rrect(color: colors.field, style: PaintingStyle.fill) + ..rrect(color: colors.border, style: PaintingStyle.stroke), + ); + await tester.tap(find.byType(PersonalizationCheckbox)); + await tester.pump(); + expect( + box(), + paints + ..rrect(color: colors.button, style: PaintingStyle.fill) + ..path(color: colors.text), + ); + }); + } + } + } + }); + + testWidgets('survey: a score opens the comment, then thanks', (tester) async { + final pumped = await _pump(tester, popupsV3Fixture('element-survey.json')); + // Оценки шкалы — в ряд, а не по одной на всю ширину. + expect( + tester.getCenter(find.text('1').first).dy, + tester.getCenter(find.text('2').first).dy, + ); + expect( + tester + .getSize( + find + .ancestor( + of: find.text('1').first, + matching: find.byType(Container), + ) + .first, + ) + .width, + lessThan(60), + ); + expect(find.text('Что можно улучшить?'), findsNothing); + await tester.tap(find.text('0').first); + await tester.pump(); + expect(find.text('Что можно улучшить?'), findsOneWidget); + await tester.enterText(find.byType(TextField), 'Долгая доставка'); + await tester.ensureVisible(find.text('Отправить').first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Отправить').first); + await tester.pumpAndSettle(); + expect(pumped.actions.calls, [ + 'review nps "test" 0 "Долгая доставка"', + ]); + expect(find.text('Спасибо за оценку!'), findsOneWidget); + }); + + testWidgets('survey: a failed review shows the error, the retry works', ( + tester, + ) async { + final pumped = await _pump(tester, popupsV3Fixture('element-survey.json')); + pumped.actions.error = StoriesV3Exception('HTTP 404: Channel not found'); + await tester.tap(find.text('5').at(1)); + await tester.pump(); + await tester.ensureVisible(find.text('Отправить').first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Отправить').first); + await tester.pumpAndSettle(); + expect( + find.text('${PopupV3Texts.ru.sendError} (HTTP 404: Channel not found)'), + findsOneWidget, + ); + pumped.actions.error = null; + await tester.tap(find.text('Отправить').first); + await tester.pumpAndSettle(); + expect(pumped.actions.calls, [ + 'review csat "MNTEST" 5 ""', + 'review csat "MNTEST" 5 ""', + ]); + expect(find.text('Спасибо!'), findsOneWidget); + }); + + testWidgets('promo code: copy, then «copied» and the apply link', ( + tester, + ) async { + final copied = _mockClipboard(tester); + final pumped = await _pump( + tester, + popupsV3Fixture('element-promo-code.json'), + runtime: const {'promo_code': 'ABC123'}, + ); + expect(find.text('ABC123'), findsOneWidget); + expect(find.text('WELCOME5'), findsOneWidget); + await tester.tap(find.text('Копировать')); + await tester.pump(); + expect(find.text('Скопировано!'), findsOneWidget); + expect(copied, ['ABC123']); + expect(pumped.actions.links, ['rees46demo://cart?promo=ABC123']); + expect(pumped.actions.events, ['click']); + }); + + for (final hostOpens in [true, false]) { + testWidgets( + 'a product of the recommendations: click, then ' + '${hostOpens ? 'the host opens it and the popup goes without close' : 'its link, the popup stays'}', + (tester) async { + PersonalizationRequestCache.shared.clear(); + final actions = RecordingActions(host: _RecommendationsHostApi()) + ..hostOpensProducts = hostOpens; + final pumped = await _pump( + tester, + popupsV3Fixture('element-recommendation.json'), + actions: actions, + ); + await tester.pumpAndSettle(); + await tester.tap(find.byType(PersonalizationProductCard).first); + await tester.pump(); + expect(actions.events, ['click']); + expect(actions.calls, ['product 52173']); + expect(pumped.closes, hostOpens ? ['dismiss'] : isEmpty); + }, + ); + } + + for (final hostOpens in [true, false]) { + testWidgets( + 'links of a button, a text and a promo code: click, then ' + '${hostOpens ? 'the host opens them and the popup goes without close' : 'the system, the popup stays'}', + (tester) async { + _mockClipboard(tester); + final button = await _pump( + tester, + popupsV3Fixture('element-button.json'), + actions: RecordingActions()..hostOpensLinks = hostOpens, + ); + await tester.tap(find.text('Старый документ')); + expect(button.actions.events, ['click']); + expect(button.actions.links, ['https://demo.rees46.ru']); + expect(button.closes, hostOpens ? ['dismiss'] : isEmpty); + + final text = await _pump( + tester, + popupsV3Fixture('element-text.json'), + actions: RecordingActions()..hostOpensLinks = hostOpens, + ); + await tester.tap(find.textContaining('Скидка 10%', findRichText: true)); + expect(text.actions.events, ['click']); + expect(text.actions.links, ['https://demo.rees46.ru/sale']); + expect(text.closes, hostOpens ? ['dismiss'] : isEmpty); + + final promo = await _pump( + tester, + popupsV3Fixture('element-promo-code.json'), + runtime: const {'promo_code': 'ABC123'}, + actions: RecordingActions()..hostOpensLinks = hostOpens, + ); + await tester.tap(find.text('Копировать')); + await tester.pump(); + expect(promo.actions.events, ['click']); + expect(promo.actions.links, ['rees46demo://cart?promo=ABC123']); + expect(promo.closes, hostOpens ? ['dismiss'] : isEmpty); + }, + ); + } + + group('kit inside a popup: the theme by the popup background', () { + final dark = ThemeData(brightness: Brightness.dark); + + Map recommendation({String? frame}) { + final popup = popupsV3Fixture('element-recommendation.json'); + if (frame != null) { + ((popup['design'] as Map)['frameStyle'] + as Map)['bgColor'] = + frame; + } + return popup; + } + + Future card( + WidgetTester tester, + Map popup, { + ThemeData? theme, + }) async { + PersonalizationRequestCache.shared.clear(); + await _pump( + tester, + popup, + theme: theme, + actions: RecordingActions(host: _RecommendationsHostApi()), + ); + await tester.pumpAndSettle(); + return tester.element(find.byType(PersonalizationProductCard).first); + } + + testWidgets('a white popup in a dark system theme — the light kit', ( + tester, + ) async { + final context = await card(tester, recommendation(), theme: dark); + expect(PersonalizationTheme.brightnessOf(context), Brightness.light); + expect( + PersonalizationTheme.of(context).colors, + PersonalizationColors.light, + ); + }); + + testWidgets('a dark popup in a light system theme — the dark kit', ( + tester, + ) async { + final context = await card(tester, recommendation(frame: '#111827')); + expect(PersonalizationTheme.brightnessOf(context), Brightness.dark); + expect( + PersonalizationTheme.of(context).colors, + PersonalizationColors.dark, + ); + }); + + testWidgets('outside a popup the kit follows the system', (tester) async { + late BuildContext outside; + await tester.pumpWidget( + MaterialApp( + theme: dark, + home: Builder( + builder: (context) { + outside = context; + return const SizedBox(); + }, + ), + ), + ); + expect(PersonalizationTheme.brightnessOf(outside), Brightness.dark); + }); + + test( + 'the background under an element: its own, else the frame, else white', + () { + Brightness under(Map style, {String? frame}) { + final popup = _single('text', { + 'message': 'Текст', + ...style, + }); + final frameStyle = + (popup['design'] as Map)['frameStyle'] + as Map; + if (frame == null) { + frameStyle.remove('bgColor'); + } else { + frameStyle['bgColor'] = frame; + } + final design = _parse(popup); + return PersonalizationBrightness.on( + popupV3BackgroundUnder(design, design.elements.single), + ); + } + + expect(under({'bgColor': '#0f172a'}), Brightness.dark); + expect( + under({'bgColor': 'rgba(0, 0, 0, 0.8)'}), + Brightness.dark, + ); + expect( + under({'bgColor': 'transparent'}, frame: '#1f2937'), + Brightness.dark, + ); + expect( + under({'bgColor': 'transparent'}, frame: '#ffffff'), + Brightness.light, + ); + expect( + under({ + 'bgColor': 'transparent', + }, frame: 'transparent'), + Brightness.light, + ); + expect( + under({'bgColor': '#fef3c7'}), + Brightness.light, + ); + }, + ); + }); + + group('host', () { + late List> live; + + setUp(() { + live = + ((popupsV3Fixture('live-list-181-182.json')['payload'] + as Map)['popups'] + as List) + .cast>(); + }); + + Future app(WidgetTester tester) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: Text('App'))), + ); + } + + testWidgets('a modal over the root navigator; × closes it with an event', ( + tester, + ) async { + await app(tester); + final actions = RecordingActions(); + final host = PopupV3Host(texts: PopupV3Texts.ru); + final popup = PopupV3.tryParse(live.last)!; + final shown = await host.present( + popup, + const {}, + actions, + ); + await tester.pumpAndSettle(); + expect(find.text('Fix Test'), findsOneWidget); + var closed = false; + shown!.closed.then((_) => closed = true); + // Тап по затемнению закрывает окно. + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + expect(find.text('Fix Test'), findsNothing); + expect(closed, isTrue); + expect(actions.events, ['close']); + }); + + for (final hostOpens in [true, false]) { + testWidgets( + 'a link button: ' + '${hostOpens ? 'the host opened it — the modal goes without close' : 'the system opens it — the modal stays'}', + (tester) async { + await app(tester); + final actions = RecordingActions()..hostOpensLinks = hostOpens; + final host = PopupV3Host(texts: PopupV3Texts.ru); + final popup = PopupV3.tryParse( + popupsV3Fixture('element-button.json'), + )!; + final shown = await host.present( + popup, + const {}, + actions, + ); + await tester.pumpAndSettle(); + var closed = false; + shown!.closed.then((_) => closed = true); + await tester.tap(find.text('Старый документ')); + await tester.pumpAndSettle(); + expect(actions.links, ['https://demo.rees46.ru']); + expect(actions.events, ['click']); + expect( + find.text('Старый документ'), + hostOpens ? findsNothing : findsOneWidget, + ); + expect(closed, hostOpens); + if (!hostOpens) { + shown.dismiss(); + await tester.pumpAndSettle(); + } + }, + ); + } + + for (final handler in ['opens', 'throws']) { + testWidgets( + 'engine and host: the link handler ${handler == 'opens' ? 'opened the link — click without close, the modal goes' : 'threw — the system opens it, the modal stays'}', + (tester) async { + PopupsV3Slots.reset(); + addTearDown(PopupsV3Slots.reset); + await app(tester); + final harness = EngineHarness( + server: FakeServer( + popups: >[ + popupsV3Fixture('element-button.json'), + ], + ), + ); + final handled = []; + harness.engine.onLink = (url) { + handled.add(url); + if (handler == 'throws') throw StateError('no screen'); + return true; + }; + await harness.engine.show(9103); + await tester.pump(); + final shown = await PopupV3Host(texts: PopupV3Texts.ru).present( + PopupV3.tryParse(popupsV3Fixture('element-button.json'))!, + const {}, + harness.presenter.actions[9103]!, + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Старый документ')); + await tester.pumpAndSettle(); + expect(handled, ['https://demo.rees46.ru']); + expect(harness.server.events, ['9103:show', '9103:click']); + if (handler == 'opens') { + expect(find.text('Старый документ'), findsNothing); + expect(harness.host.opened, isEmpty); + } else { + expect(find.text('Старый документ'), findsOneWidget); + expect(harness.host.opened, ['https://demo.rees46.ru']); + shown!.dismiss(); + await tester.pumpAndSettle(); + } + expect(harness.server.events, isNot(contains('9103:close'))); + }, + ); + } + + testWidgets('a banner leaves the app tappable; × closes it', ( + tester, + ) async { + var taps = 0; + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.bottomCenter, + child: TextButton( + onPressed: () => taps++, + child: const Text('App button'), + ), + ), + ), + ), + ); + final actions = RecordingActions(); + final popup = PopupV3.tryParse(live.first)!; + final shown = await PopupV3Host( + texts: PopupV3Texts.ru, + ).present(popup, const {}, actions); + await tester.pumpAndSettle(); + expect(find.text('Подробнее'), findsOneWidget); + // Баннер сверху не выше экрана без поля 16 снизу. + final banner = tester.getRect(find.byType(PopupV3FrameView)); + expect(banner.top, 0); + expect(banner.bottom, lessThanOrEqualTo(844 - 16)); + await tester.tap(find.text('App button')); + expect(taps, 1); + await tester.tap(find.text('×')); + await tester.pumpAndSettle(); + expect(find.text('Подробнее'), findsNothing); + expect(actions.events, ['close']); + var closed = false; + await shown!.closed.then((_) => closed = true); + expect(closed, isTrue); + }); + + for (final (index, name) in <(int, String)>[(0, 'banner'), (1, 'modal')]) { + testWidgets( + 'the keyboard: the $name frame and the field in focus stay above it', + (tester) async { + await app(tester); + final popup = PopupV3.tryParse(live[index])!; + await PopupV3Host( + texts: PopupV3Texts.ru, + ).present(popup, const {}, RecordingActions()); + await tester.pumpAndSettle(); + // Оценка открывает комментарий опроса. + final score = find.text(index == 0 ? '9' : '5'); + await tester.ensureVisible(score.first); + await tester.pumpAndSettle(); + await tester.tap(score.first); + await tester.pumpAndSettle(); + final comment = find.byType(TextField).last; + await tester.showKeyboard(comment); + tester.view.viewInsets = const FakeViewPadding(bottom: 300); + await tester.pumpAndSettle(); + const visibleBottom = 844.0 - 300; + final frame = tester.getRect(find.byType(PopupV3FrameView)); + expect(frame.bottom, lessThanOrEqualTo(visibleBottom - 16 + 0.01)); + final field = tester.getRect(comment); + expect(field.bottom, lessThanOrEqualTo(frame.bottom)); + expect(field.top, greaterThanOrEqualTo(frame.top)); + }, + ); + } + + /// Попадает ли касание в точку крестика баннера в сам крестик. + bool closeReachable(WidgetTester tester) { + final cross = find.text('×'); + final result = tester.hitTestOnBinding(tester.getCenter(cross)); + final paragraph = tester.renderObject(cross); + return result.path.any((entry) => entry.target == paragraph); + } + + for (final bannerFirst in [true, false]) { + testWidgets('layers: the modal and its overlay lie over the banner ' + '(banner ${bannerFirst ? 'first' : 'second'})', (tester) async { + await app(tester); + final host = PopupV3Host(texts: PopupV3Texts.ru); + final bannerActions = RecordingActions(); + final modalActions = RecordingActions(); + Future banner() => host.present( + PopupV3.tryParse(live.first)!, + const {}, + bannerActions, + ); + Future modal() => host.present( + PopupV3.tryParse(live.last)!, + const {}, + modalActions, + ); + if (bannerFirst) { + await banner(); + await tester.pumpAndSettle(); + expect(closeReachable(tester), isTrue); + await modal(); + } else { + await modal(); + await tester.pumpAndSettle(); + await banner(); + } + await tester.pumpAndSettle(); + expect(find.text('Fix Test'), findsOneWidget); + expect(find.text('Подробнее'), findsOneWidget); + // Баннер под затемнением окна: его крестик не нажать. + expect(closeReachable(tester), isFalse); + // Ещё одна страница приложения не поднимает баннер над окном. + unawaited( + tester + .state(find.byType(Navigator)) + .push( + MaterialPageRoute(builder: (_) => const Text('Page')), + ), + ); + await tester.pumpAndSettle(); + expect(closeReachable(tester), isFalse); + // Первое «назад» закрывает страницу, второе — окно; баннер снова доступен. + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.text('Fix Test'), findsOneWidget); + expect(closeReachable(tester), isFalse); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.text('Fix Test'), findsNothing); + expect(modalActions.events, ['close']); + expect(closeReachable(tester), isTrue); + await tester.tap(find.text('×')); + await tester.pumpAndSettle(); + expect(bannerActions.events, ['close']); + }); + } + + testWidgets('dismiss removes the popup without an event', (tester) async { + await app(tester); + final actions = RecordingActions(); + final shown = await PopupV3Host(texts: PopupV3Texts.ru).present( + PopupV3.tryParse(live.last)!, + const {}, + actions, + ); + await tester.pumpAndSettle(); + shown!.dismiss(); + await tester.pumpAndSettle(); + expect(find.text('Fix Test'), findsNothing); + expect(actions.events, isEmpty); + }); + + testWidgets('an empty design is not shown', (tester) async { + await app(tester); + final shown = await PopupV3Host().present( + PopupV3.tryParse(popupsV3Fixture('empty-design.json'))!, + const {}, + RecordingActions(), + ); + expect(shown, isNull); + }); + }); +} diff --git a/test/product_bridge_shapes_test.dart b/test/product_bridge_shapes_test.dart new file mode 100644 index 0000000..839a217 --- /dev/null +++ b/test/product_bridge_shapes_test.dart @@ -0,0 +1,207 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +// Recommendations and categories reach Dart re-serialized by the bridges, not as the raw +// API answer. These samples rebuild the live answers (test/fixtures) the way each bridge +// does it today: +// - Android: Gson of the native models of android-sdk v2.45.0, the version the plugin +// pins. Its Product has no deeplink_android, deeplink_ios or discount_percent, so they +// stay null until a native release with them is pinned. +// - iOS: the dictionaries of Rees46FlutterSdkPlugin.swift over REES46 3.35.0. Recommended +// has no discount_formatted, discount_percent, deeplink_android or is_new; the category +// product has no old price, discount, app links or is_new, and the category no filters +// or price range. They stay null until a native release with them, plus the matching +// lines in the Swift bridge. + +Map _fixture(String name) => + jsonDecode(File('test/fixtures/$name.json').readAsStringSync()) + as Map; + +/// Fields of the Android `Product` (v2.45.0) that Gson writes back out. +const Set _androidProductKeys = { + 'brand', 'categories', 'category_ids', 'location_ids', 'currency', // + 'description', '_id', 'id', 'image_url', 'image_url_handle', // + 'image_url_resized', 'name', 'picture', 'price', 'price_formatted', // + 'price_full', 'price_full_formatted', 'relative_sales_rate', 'sales_rate', // + 'url', 'url_handle', 'oldprice', 'oldprice_formatted', 'discount', // + 'discount_formatted', 'is_new', +}; + +/// [keys] of [raw] as Gson writes them: absent and `null` fields are left out. +Map _gson(Map raw, Set keys) => + { + for (final key in keys) + if (raw[key] != null) key: raw[key], + }; + +Map _androidProduct(dynamic raw) => + _gson(raw as Map, _androidProductKeys); + +/// `_productToDict(Recommended)` of the iOS bridge. +Map _iosRecommended(dynamic product) { + final raw = product as Map; + double number(String key) => (raw[key] as num?)?.toDouble() ?? 0; + final oldPrice = number('oldprice'); + final discount = raw['discount'] is int ? raw['discount'] as int : 0; + final deeplink = raw['deeplink_ios'] as String? ?? ''; + return { + for (final key in ['id', 'name', 'brand', 'description']) + key: raw[key] ?? '', + 'image_url': raw['image_url'] ?? '', + 'picture': raw['picture'] ?? '', + 'image_url_resized': raw['image_url_resized'] ?? {}, + 'url': raw['url'] ?? '', + 'price': number('price'), + 'price_full': number('price_full'), + 'currency': raw['currency'] ?? '', + 'sales_rate': raw['sales_rate'] ?? 0, + 'relative_sales_rate': raw['relative_sales_rate'] ?? 0, + 'categories': [], + if (raw['price_formatted'] != null) + 'price_formatted': raw['price_formatted'], + if (raw['price_full_formatted'] != null) + 'price_full_formatted': raw['price_full_formatted'], + if (oldPrice > 0) 'oldprice': oldPrice, + if ((raw['oldprice_formatted'] as String? ?? '').isNotEmpty) + 'oldprice_formatted': raw['oldprice_formatted'], + if (discount > 0) 'discount': discount, + if (deeplink.isNotEmpty) 'deeplink_ios': deeplink, + }; +} + +/// `_categoryProductToDict(CategoryProduct)` of the iOS bridge. +Map _iosCategoryProduct(dynamic product) { + final raw = product as Map; + return { + for (final key in [ + 'id', 'name', 'brand', 'price', 'price_formatted', 'price_full', // + 'price_full_formatted', 'currency', 'image_url', 'url', 'picture', + ]) + if (raw[key] != null) key: raw[key], + }; +} + +void main() { + final recommend = _fixture('recommend_extended'); + final category = _fixture('category'); + + group('recommendation, Android bridge (Gson, v2.45.0)', () { + final response = RecommendationResponse.fromJson({ + 'html': '', + 'id': recommend['id'], + 'title': recommend['title'], + 'recommends': (recommend['recommends'] as List) + .map(_androidProduct) + .toList(), + }); + + test('old price and discount, with the display form', () { + final product = response.products.first; + expect(product.oldPrice, 174990); + expect(product.oldPriceFormatted, '174 990 ₽'); + expect(product.discount, 6); + expect(product.discountFormatted, '6%'); + expect(product.resizedImageUrl, contains('/resize-images/180/')); + }); + + test('app links and discount_percent wait for a native release', () { + for (final product in response.products) { + expect(product.deeplinkAndroid, isNull); + expect(product.deeplinkIos, isNull); + expect(product.discountPercent, isNull); + } + }); + }); + + group('recommendation, iOS bridge (REES46 3.35.0)', () { + final response = RecommendationResponse.fromJson({ + 'title': recommend['title'], + 'recommends': (recommend['recommends'] as List) + .map(_iosRecommended) + .toList(), + }); + + test('old price, discount and the iOS app link', () { + final product = response.products.first; + expect(product.oldPrice, 174990); + expect(product.oldPriceFormatted, '174 990 ₽'); + expect(product.discount, 6); + expect( + product.deeplinkIos, + 'https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173', + ); + }); + + test('a product without a discount sends none of it', () { + final product = response.products[1]; + expect(product.oldPrice, isNull); + expect(product.oldPriceFormatted, isNull); + expect(product.discount, isNull); + }); + + test('the display form, discount_percent, deeplink_android and is_new wait ' + 'for a native release', () { + final product = response.products.first; + expect(product.discountFormatted, isNull); + expect(product.discountPercent, isNull); + expect(product.deeplinkAndroid, isNull); + expect(product.isNew, isNull); + }); + }); + + group('category, Android bridge (Gson, v2.45.0)', () { + final response = CategoryResponse.fromJson({ + ..._gson(category, { + 'products_total', 'brands', 'categories', 'price_range', // + 'price_ranges', 'price_median', 'filters', + }), + 'products': (category['products'] as List).map(_androidProduct).toList(), + }); + + test('facets come through', () { + expect(response.productsTotal, 2320); + expect(response.brands, ['A-Case', 'ACEFAST', 'AULA']); + expect(response.filters['NFC']!.values, {'Нет': 6}); + expect(response.priceRange!.max, 1863890); + }); + + test('products keep the picture; app links wait for a native release', () { + for (final product in response.products) { + expect(product.picture, isNotNull); + expect(product.deeplinkAndroid, isNull); + expect(product.deeplinkIos, isNull); + expect(product.discountPercent, isNull); + } + }); + }); + + group('category, iOS bridge (REES46 3.35.0)', () { + final response = CategoryResponse.fromJson({ + 'products_total': category['products_total'], + 'products': (category['products'] as List) + .map(_iosCategoryProduct) + .toList(), + 'brands': category['brands'], + }); + + test('brands come through; filters and price range wait', () { + expect(response.brands, ['A-Case', 'ACEFAST', 'AULA']); + expect(response.filters, isEmpty); + expect(response.priceRange, isNull); + }); + + test('products carry price and picture; the rest waits', () { + final product = response.products.first; + expect(product.price, 15990); + expect(product.priceFormatted, '15 990 ₽'); + expect(product.picture, isNotNull); + expect(product.oldPrice, isNull); + expect(product.discount, isNull); + expect(product.deeplinkIos, isNull); + expect(product.isNew, isNull); + }); + }); +} diff --git a/test/product_fields_test.dart b/test/product_fields_test.dart new file mode 100644 index 0000000..22ec2e9 --- /dev/null +++ b/test/product_fields_test.dart @@ -0,0 +1,272 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; + +/// Live API answers (shop c1140c…, api.rees46.ru). The Android bridge passes them on as +/// they are for product info, products list and full search; recommendations and +/// categories reach Dart re-serialized by the bridges, see +/// `product_bridge_shapes_test.dart`. +Map _fixture(String name) => + jsonDecode(File('test/fixtures/$name.json').readAsStringSync()) + as Map; + +void main() { + // Parser only: no bridge sends this shape yet (both drop the app links, see the + // bridge-shaped samples). + group('recommendation, parser only (raw API shape)', () { + final response = RecommendationResponse.fromJson( + _fixture('recommend_extended'), + ); + + test('a discounted product carries the old price and the discount', () { + final product = response.products.first; + expect(product.id, '52173'); + expect(product.oldPrice, 174990); + expect(product.oldPriceFormatted, '174 990 ₽'); + expect(product.discount, 6); + expect(product.discountFormatted, '6%'); + expect(product.discountPercent, 5); + expect(product.isNew, isNull); + }); + + test('a product without a discount has none of the discount fields', () { + final product = response.products[1]; + expect(product.oldPrice, isNull); + expect(product.oldPriceFormatted, isNull); + expect(product.discount, isNull); + expect(product.discountFormatted, isNull); + expect(product.discountPercent, isNull); + }); + + test('app links and the resized picture', () { + final product = response.products[1]; + expect( + product.deeplinkAndroid, + 'https://www.technodom.kz/p/naushniki-nakladnye-honor-choice-headphones-lite-gray-5504adgf-300252', + ); + expect(product.deeplinkIos, product.deeplinkAndroid); + expect(product.resizedImageUrl, contains('/resize-images/180/')); + }); + }); + + group('products list (raw on Android)', () { + final response = ProductsListResponse.fromJson(_fixture('products')); + + test('facets: brands, filters, price range', () { + expect(response.productsTotal, 10000); + expect(response.brands, ['1STPLAYER', '2E', '70mai']); + expect(response.filters.keys, hasLength(3)); + expect(response.filters['AC гнезда']!.count, 1); + expect(response.filters['AC гнезда']!.values, {'4': 1}); + expect(response.priceRange!.min, 10); + expect(response.priceRange!.max, 8000000); + }); + + test('a discounted product and one without a discount', () { + final plain = response.products[0]; + final discounted = response.products[1]; + expect(plain.oldPrice, isNull); + expect(plain.discount, isNull); + expect(plain.discountPercent, isNull); + expect(discounted.oldPrice, 174990); + expect(discounted.oldPriceFormatted, '174 990 ₽'); + expect(discounted.discount, 6); + expect(discounted.discountFormatted, '6%'); + expect(discounted.discountPercent, 5); + expect(discounted.picture, contains('/resize-images/180/')); + expect( + discounted.deeplinkAndroid, + 'https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173', + ); + expect(discounted.deeplinkIos, discounted.deeplinkAndroid); + }); + + test('iOS bridge shape: brands as plain names', () { + final ios = ProductsListResponse.fromJson({ + 'products': [], + 'products_total': 0, + 'brands': ['Apple', ''], + 'filters': { + 'color': { + 'count': 2, + 'values': {'red': 2}, + }, + }, + }); + expect(ios.brands, ['Apple']); + expect(ios.filters['color']!.values, {'red': 2}); + // The native model has no categories yet, so the bridge sends none. + expect(ios.categories, isEmpty); + }); + + test('categories of the listing, top-level ones without a parent', () { + expect(response.categories.map((c) => c.id), [ + 'noutbuki-i-komp-jutery', + 'bytovaja-tehnika', + 'tehnika-dlja-kuhni', + ]); + final first = response.categories.first; + expect(first.name, 'Ноутбуки и компьютеры'); + expect(first.parentId, isNull); + expect(first.url, contains('/catalog/noutbuki-i-komp-jutery')); + }); + + test('a nested category keeps its parent', () { + final nested = ProductsListResponse.fromJson({ + 'products': [], + 'products_total': 0, + 'categories': [ + {'id': 'phones', 'name': 'Phones'}, + { + 'id': 'headphones', + 'name': 'Headphones', + 'parent_id': 'phones', + }, + ], + }); + expect(nested.categories.map((c) => c.parentId), [ + null, + 'phones', + ]); + }); + + test('a response without facets keeps them empty', () { + final bare = ProductsListResponse.fromJson({ + 'products': [], + 'products_total': 0, + }); + expect(bare.brands, isEmpty); + expect(bare.filters, isEmpty); + expect(bare.categories, isEmpty); + }); + }); + + // Parser only: the bridges re-serialize the native category, see the bridge-shaped + // samples. + group('category, parser only (raw API shape)', () { + final response = CategoryResponse.fromJson(_fixture('category')); + + test('facets: brands, filters, price range', () { + expect(response.productsTotal, 2320); + expect(response.brands, ['A-Case', 'ACEFAST', 'AULA']); + expect(response.filters['NFC']!.count, 6); + expect(response.filters['NFC']!.values, {'Нет': 6}); + expect(response.priceRange!.min, 190); + expect(response.priceRange!.max, 1863890); + }); + + test('products without a discount, with app links', () { + for (final product in response.products) { + expect(product.oldPrice, isNull); + expect(product.discount, isNull); + expect(product.deeplinkAndroid, isNotNull); + expect(product.deeplinkIos, isNotNull); + expect(product.picture, isNotNull); + } + }); + + test('a category without facets (an older native) keeps them empty', () { + final bare = CategoryResponse.fromJson({ + 'products_total': 0, + 'products': [], + }); + expect(bare.brands, isEmpty); + expect(bare.filters, isEmpty); + expect(bare.priceRange, isNull); + }); + }); + + group('product info (raw on Android)', () { + final product = Product.fromJson(_fixture('product_info')); + + test('discount `false` reads as no discount', () { + expect(product.id, '868'); + expect(product.discount, isNull); + expect(product.oldPrice, isNull); + expect(product.oldPriceFormatted, isNull); + }); + + test('app links, picture and the price string', () { + expect( + product.deeplinkAndroid, + 'https://www.technodom.kz/p/garnitura-nakladnaa-logitech-h-white-868', + ); + expect(product.deeplinkIos, product.deeplinkAndroid); + expect(product.picture, startsWith('https://')); + expect(product.price, 14990); + }); + }); + + group('search full (raw on Android)', () { + final response = SearchFullResponse.fromJson(_fixture('search_full')); + + test('products carry app links, no discount', () { + final product = response.products.first; + expect( + product.deeplinkAndroid, + 'https://www.technodom.kz/p/stiralnaya-mashina-samsung-ww60ak4s00celt-292523', + ); + expect(product.deeplinkIos, product.deeplinkAndroid); + expect(product.discountPercent, isNull); + expect(product.isNew, isNull); + expect(product.oldPrice, 0); + }); + + test('facets still parse', () { + expect(response.brands.first, 'Samsung'); + expect(response.filters['merchant']!.values, { + 'Technodom': 833, + }); + }); + }); + + group('bridge tolerance', () { + Product product(Map extra) => Product.fromJson( + {'id': '1', 'name': 'Item', ...extra}, + ); + + test('is_new as a bool, a number or a string', () { + expect(product({'is_new': true}).isNew, isTrue); + expect(product({'is_new': 0}).isNew, isFalse); + expect(product({'is_new': 'true'}).isNew, isTrue); + expect(product({'is_new': 'x'}).isNew, isNull); + }); + + test('empty strings from the iOS models read as absent', () { + final p = product({ + 'deeplink_ios': '', + 'oldprice_formatted': '', + 'picture': '', + }); + expect(p.deeplinkIos, isNull); + expect(p.oldPriceFormatted, isNull); + expect(p.picture, isNull); + }); + + test('numbers as strings', () { + final p = product({ + 'oldprice': '199.5', + 'discount': '10', + 'discount_percent': 9, + }); + expect(p.oldPrice, 199.5); + expect(p.discount, 10); + expect(p.discountPercent, 9); + }); + + test('search products read the new fields too', () { + final p = SearchProduct.fromJson({ + 'id': '1', + 'deeplink_ios': 'app://p/1', + 'is_new': true, + 'discount_percent': 12, + }); + expect(p.deeplinkIos, 'app://p/1'); + expect(p.deeplinkAndroid, isNull); + expect(p.isNew, isTrue); + expect(p.discountPercent, 12); + }); + }); +} diff --git a/test/stories/stories_poll_response_test.dart b/test/stories/stories_poll_response_test.dart new file mode 100644 index 0000000..17dea81 --- /dev/null +++ b/test/stories/stories_poll_response_test.dart @@ -0,0 +1,465 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/stories/stories_response.dart'; + +/// The shared feed of every platform: campaign 9001 with all six kinds, an answered +/// choice with results and an unknown `quiz`; numbers partly come as strings. +StoriesBlock _fixture() { + final json = + jsonDecode( + File('test/fixtures/stories_polls_feed.json').readAsStringSync(), + ) + as Map; + return StoriesBlock.fromJson(json['payload'] as Map); +} + +StoryPollElement? _poll(StorySlide slide) => + slide.elements.whereType().firstOrNull; + +StorySlide _slide(List> elements, {String id = '1'}) => + StorySlide.fromJson({ + 'id': id, + 'type': 'image', + 'elements': elements, + }); + +void main() { + test( + 'the fixture: all six kinds, an answered one, the unknown one dropped', + () { + final slides = _fixture().stories.single.slides; + expect(slides, hasLength(8)); + final polls = slides.map(_poll).toList(); + expect( + polls.map((poll) => (poll?.pollType, poll?.kind)).toList(), + <(StoryPollType?, StoryMiniPollKind?)>[ + (StoryPollType.miniPoll, StoryMiniPollKind.singleChoice), + (StoryPollType.miniPoll, StoryMiniPollKind.multipleChoice), + (StoryPollType.miniPoll, StoryMiniPollKind.text), + (StoryPollType.nps, null), + (StoryPollType.csat, null), + (StoryPollType.ces, null), + (StoryPollType.miniPoll, StoryMiniPollKind.singleChoice), + (null, null), + ], + ); + expect(slides.last.elements, isEmpty, reason: '"quiz" is not drawn'); + expect(polls.map((poll) => poll?.yOffset).toList(), [ + 50, 40, 30, 60, 90, 5, 50, null, // + ]); + }, + ); + + test('a single choice with labels', () { + final poll = _poll(_fixture().stories.single.slides[0])!; + expect(poll.code, 'demo_single'); + expect(poll.question, 'Что вам больше нравится?'); + expect(poll.allowReanswer, isTrue); + expect(poll.showResults, isTrue); + expect(poll.submitLabel, isEmpty); + expect(poll.thanksText, 'Спасибо за ответ!'); + expect(poll.options.map((option) => (option.id, option.label)), [ + (1, 'Кроссовки'), + (2, 'Ботинки'), + (3, 'Сандалии'), + ]); + expect(poll.labels.reanswer, 'Ответить заново'); + expect(poll.labels.error, 'Не удалось отправить ответ. Попробуйте еще раз'); + expect(poll.labels.submit, isNull); + expect(poll.answer, isNull); + expect(poll.results, isNull); + }); + + test('numbers as strings: y_offset, max_length, rate_min / rate_max', () { + final slides = _fixture().stories.single.slides; + expect(_poll(slides[1])!.yOffset, 40); + final text = _poll(slides[2])!; + expect(text.maxLength, 120); + expect(text.placeholder, 'Ваш ответ'); + expect(text.showResults, isFalse); + final ces = _poll(slides[5])!; + expect((ces.rateMin, ces.rateMax), (1, 7)); + expect(ces.bands, isEmpty); + expect(ces.channel, 'stories'); + }); + + test('scales: channel, ranges and bands; nulls stay unset', () { + final slides = _fixture().stories.single.slides; + final nps = _poll(slides[3])!; + expect(nps.code, 'test'); + expect(nps.channel, 'test'); + expect((nps.rateMin, nps.rateMax), (0, 10)); + expect(nps.bands.map((band) => (band.from, band.to, band.success)), [ + (0, 6, 'Спасибо, мы станем лучше'), + (7, 8, 'Спасибо за оценку'), + (9, 10, 'Спасибо, мы рады!'), + ]); + final csat = _poll(slides[4])!; + expect(csat.channel, isEmpty); + expect((csat.rateMin, csat.rateMax), (null, null)); + expect(csat.labels.reanswer, isNull); + expect(csat.allowReanswer, isFalse); + }); + + test('an answer and results from the feed', () { + final poll = _poll(_fixture().stories.single.slides[6])!; + expect(poll.answer!.id, 77); + expect(poll.answer!.optionIds, [2]); + expect(poll.answer!.text, isNull); + expect(poll.answer!.isAnswered, isTrue); + expect(poll.results!.total, 120); + expect(poll.results!.percentOf(1), 40); + expect(poll.results!.percentOf(2), 60); + expect(poll.results!.percentOf(3), 0); + }); + + test('isAnswered: options, text or a rate', () { + expect(const StoryPollAnswer().isAnswered, isFalse); + expect(const StoryPollAnswer(optionIds: []).isAnswered, isFalse); + expect(const StoryPollAnswer(text: '').isAnswered, isFalse); + expect(const StoryPollAnswer(optionIds: [1]).isAnswered, isTrue); + expect(const StoryPollAnswer(text: 'a').isAnswered, isTrue); + expect(const StoryPollAnswer(rate: 0).isAnswered, isTrue); + expect(StoryPollAnswer.tryParse({'rate': '3'})!.rate, 3); + expect(StoryPollAnswer.tryParse('x'), isNull); + // A blank text is still an answer: only "" is empty. + expect(const StoryPollAnswer(text: ' ').isAnswered, isTrue); + }); + + test('any numeric rate is an answer, a fractional one too', () { + StoryPollAnswer? rate(Object? value) => + StoryPollAnswer.tryParse({'rate': value}); + expect(rate(9.5)!.rate, 9.5); + expect(rate(9.5)!.isAnswered, isTrue); + expect(rate('6.5')!.rate, 6.5); + expect(rate('7')!.rate, 7); + for (final value in [null, 'x', 'NaN', true]) { + expect(rate(value)!.isAnswered, isFalse, reason: '$value'); + } + }); + + test('blank strings are not empty: shown, sent and override', () { + final poll = StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'mini_poll', + 'labels': {'reanswer': ' ', 'error': '', 'submit': ' '}, + 'poll': { + 'code': 'x', + 'kind': 'text', + 'question': ' ', + 'placeholder': ' ', + 'submit_label': ' ', + 'thanks_text': ' ', + }, + })!; + expect([ + poll.question, + poll.placeholder, + poll.submitLabel, + poll.thanksText, + ], everyElement(' ')); + expect( + (poll.labels.reanswer, poll.labels.error, poll.labels.submit), + (' ', null, ' '), + ); + final scale = StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'nps', + 'poll': { + 'code': 'x', + 'channel': ' ', + 'bands': [ + {'from': 0, 'to': 10, 'success': ' '}, + ], + }, + })!; + expect(scale.channel, ' '); + expect(scale.bands.single.success, ' '); + }); + + test('a product slide keeps its poll; broken elements do not break it', () { + final slide = _slide(id: '39_0', >[ + {'type': 'poll', 'poll_type': 'nps', 'poll': null}, + {'type': 'poll', 'poll_type': 'mini_poll', 'poll': 5}, + { + 'type': 'poll', + 'poll_type': 'mini_poll', + 'poll': {'code': 'x', 'kind': 'rating'}, + }, + { + 'type': 'poll', + 'poll_type': 'mini_poll', + 'y_offset': 'top', + 'allow_reanswer': null, + 'labels': {'reanswer': '', 'submit': 7}, + 'poll': { + 'code': 15, + 'kind': 'multiple_choice', + 'max_length': 0, + 'options': [ + {'id': '4', 'label': 'Four'}, + {'label': 'no id'}, + null, + ], + }, + 'answer': { + 'option_ids': ['4', null], + }, + 'results': { + 'options': [ + {'id': 4, 'percent': '99.6'}, + ], + }, + }, + ]); + expect(slide.id, '39_0'); + final poll = _poll(slide)!; + expect(slide.elements, hasLength(1)); + expect(poll.code, '15'); + expect(poll.yOffset, isNull); + expect(poll.allowReanswer, isFalse); + expect(poll.maxLength, isNull); + expect(poll.options.map((option) => option.id), [4]); + expect(poll.labels.reanswer, isNull); + expect(poll.labels.submit, isNull); + expect(poll.answer!.optionIds, [4]); + expect(poll.results!.percentOf(4), 100); + }); + + test('every optional field null: a mini poll and a scale still parse', () { + final mini = StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'mini_poll', + 'y_offset': null, + 'allow_reanswer': null, + 'labels': null, + 'poll': { + 'code': null, + 'kind': 'text', + 'question': null, + 'placeholder': null, + 'max_length': null, + 'submit_label': null, + 'thanks_text': null, + 'show_results': null, + 'options': null, + }, + 'answer': null, + 'results': null, + })!; + expect(mini.kind, StoryMiniPollKind.text); + expect(mini.code, isEmpty, reason: 'no code — an empty one, still drawn'); + expect(mini.yOffset, isNull); + expect(mini.allowReanswer, isFalse); + expect(mini.showResults, isFalse); + expect([ + mini.question, + mini.placeholder, + mini.submitLabel, + mini.thanksText, + ], everyElement(isEmpty)); + expect(mini.maxLength, isNull); + expect(mini.options, isEmpty); + expect(mini.answer, isNull); + expect(mini.results, isNull); + expect( + (mini.labels.reanswer, mini.labels.error, mini.labels.submit), + (null, null, null), + ); + + final scale = StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'ces', + 'poll': { + 'code': 'support', + 'channel': null, + 'name': null, + 'rate_min': null, + 'rate_max': null, + 'question': null, + 'bands': [ + {'from': 1, 'to': 7, 'success': null}, + null, + ], + }, + 'answer': {'rate': null}, + })!; + expect(scale.kind, isNull); + expect((scale.channel, scale.name, scale.question), ('', '', '')); + expect((scale.rateMin, scale.rateMax), (null, null)); + expect(scale.bands.single.success, isNull); + expect(scale.answer!.isAnswered, isFalse); + }); + + test('flags: only true, 1 or "true"', () { + bool reanswer(Object? value) => StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'nps', + 'allow_reanswer': value, + 'poll': {'code': 'x'}, + })!.allowReanswer; + expect([true, 1, 1.0, 'true'].map(reanswer), everyElement(isTrue)); + expect( + [ + false, + 0, + 2, + '1', + 'yes', + 'True', + 'TRUE', + ' true', + null, + [], + ].map(reanswer), + everyElement(isFalse), + ); + }); + + test('scale bounds: whole numbers only, also as strings', () { + (int?, int?) bounds(Object? min, Object? max) { + final poll = StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'nps', + 'poll': { + 'code': 'x', + 'rate_min': min, + 'rate_max': max, + }, + })!; + return (poll.rateMin, poll.rateMax); + } + + expect(bounds(2, '9'), (2, 9)); + expect(bounds(1.0, '7.0'), (1, 7)); + expect(bounds(2.5, '3.5'), (null, null), reason: 'not whole — defaults'); + expect(bounds('x', true), (null, null)); + }); + + test('results: percents rounded and clamped, a missing one 0', () { + final results = StoryPollResults.tryParse({ + 'total': '7', + 'options': [ + {'id': 1, 'percent': 40.5}, + {'id': 2, 'percent': 120}, + {'id': 3, 'percent': -3}, + {'id': 4, 'percent': 'NaN'}, + {'id': 5, 'percent': 'Infinity'}, + {'id': 6, 'percent': null}, + {'id': '7', 'percent': '33.4'}, + ], + })!; + expect(results.total, 7); + expect( + [for (var id = 1; id <= 8; id++) results.percentOf(id)], + [41, 100, 0, 0, 100, 0, 33, 0], + ); + }); + + test('results without an options array have no percents', () { + for (final options in [null, 'x', {}]) { + final results = StoryPollResults.tryParse({ + 'total': 3, + 'options': options, + })!; + expect(results.options, isNull); + expect(results.percentOf(1), isNull); + } + expect(const StoryPollResults().percentOf(1), isNull); + expect( + const StoryPollResults( + options: <({int id, double percent})>[], + ).percentOf(1), + 0, + ); + }); + + test('y_offset: a number or a numeric string, otherwise unset', () { + double? offset(Object? value) => + StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'csat', + 'y_offset': value, + 'poll': {'code': 'x'}, + })!.yOffset; + expect([35, '35', 35.0].map(offset), everyElement(35)); + expect( + [null, 'top', 'NaN', 'Infinity', double.nan].map(offset), + everyElement(isNull), + ); + expect(offset(-20), -20, reason: 'clamped when laid out'); + }); + + test('poll_type and kind as they are: no trimming, case matters', () { + StoryPollElement? parse(String type, [String? kind]) => + StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': type, + 'poll': {'code': 'x', 'kind': kind}, + }); + expect(parse('nps'), isNotNull); + expect(parse('mini_poll', 'single_choice'), isNotNull); + for (final type in [' nps', 'NPS', 'csat ']) { + expect(parse(type), isNull, reason: type); + } + for (final kind in ['Single_choice', 'text ', ' text']) { + expect(parse('mini_poll', kind), isNull, reason: kind); + } + }); + + test('options: a whole id stays, no label is an empty one', () { + final poll = StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'mini_poll', + 'poll': { + 'code': 'x', + 'kind': 'single_choice', + 'options': [ + {'id': 1}, + {'id': '2', 'label': null}, + {'id': 3.0, 'label': 'Three'}, + {'id': 1.5, 'label': 'Half'}, + {'id': '2.5', 'label': 'Half'}, + {'id': 'x', 'label': 'X'}, + {'label': 'No id'}, + ], + }, + 'answer': { + 'option_ids': [2, 1.5, '3'], + }, + })!; + expect(poll.options.map((option) => (option.id, option.label)), [ + (1, ''), + (2, ''), + (3, 'Three'), + ]); + expect(poll.answer!.optionIds, [2, 3]); + }); + + test('unknown kinds and types are logged and dropped', () { + final logs = []; + final print = debugPrint; + debugPrint = (message, {wrapWidth}) => logs.add(message ?? ''); + addTearDown(() => debugPrint = print); + final slide = _slide(>[ + { + 'type': 'poll', + 'poll_type': 'emoji', + 'poll': {'code': 'x'}, + }, + { + 'type': 'poll', + 'poll_type': 'mini_poll', + 'poll': {'code': 'x', 'kind': 'quiz'}, + }, + {'type': 'text_block', 'text_input': 'Hi'}, + ]); + expect(slide.elements.single, isA()); + expect(logs, hasLength(2)); + expect(logs.first, contains('"emoji"')); + expect(logs.last, contains('"quiz"')); + }); +} diff --git a/test/stories/stories_response_test.dart b/test/stories/stories_response_test.dart index d0a0c65..3f9ec50 100644 --- a/test/stories/stories_response_test.dart +++ b/test/stories/stories_response_test.dart @@ -4,7 +4,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; import 'package:rees46_sdk/src/personalization_sdk.dart' - show PersonalizationStoriesBridge; + show PersonalizationStoryViewerBridge; import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; import 'package:rees46_sdk/src/stories/stories_response.dart'; diff --git a/test/ui/personalization_catalog_test.dart b/test/ui/personalization_catalog_test.dart index 183f573..c439a27 100644 --- a/test/ui/personalization_catalog_test.dart +++ b/test/ui/personalization_catalog_test.dart @@ -227,4 +227,57 @@ void main() { PersonalizationSpacing.lg, ); }); + + testWidgets('the rating shows only with showRating', (tester) async { + Widget catalog({required bool showRating}) => _host( + PersonalizationCatalog( + showRating: showRating, + products: const [ + PersonalizationProduct( + id: '1', + name: 'Rated', + price: '1', + rating: PersonalizationProductRating(value: '4,7', reviews: 12), + ), + ], + ), + ); + + await tester.pumpWidget(catalog(showRating: true)); + expect(find.byType(PersonalizationRating), findsOneWidget); + + await tester.pumpWidget(catalog(showRating: false)); + expect(find.byType(PersonalizationRating), findsNothing); + }); + + testWidgets('an empty state action sits under it and hides while loading', ( + tester, + ) async { + var taps = 0; + Widget catalog({required bool loading}) => _host( + PersonalizationCatalog( + products: const [], + emptyText: 'Failed', + emptyActionText: 'Retry', + onEmptyAction: () => taps++, + loading: loading, + ), + ); + + await tester.pumpWidget(catalog(loading: false)); + final retry = find.widgetWithText(PersonalizationButton, 'Retry'); + expect(retry, findsOneWidget); + expect( + tester.getRect(retry).top, + greaterThan( + tester.getRect(find.byType(PersonalizationEmptyState)).bottom, + ), + ); + await tester.tap(retry); + expect(taps, 1); + + await tester.pumpWidget(catalog(loading: true)); + expect(retry, findsNothing); + expect(find.byType(PersonalizationLoader), findsOneWidget); + }); } diff --git a/test/ui/personalization_category_screen_test.dart b/test/ui/personalization_category_screen_test.dart new file mode 100644 index 0000000..2c21cfa --- /dev/null +++ b/test/ui/personalization_category_screen_test.dart @@ -0,0 +1,382 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; + +/// Host API that answers `getCategory` from memory: [total] products, a page of the +/// requested limit at a time, with the facets the API sends with a category. +class _FakeHostApi extends pigeon.PersonalizationHostApi { + int total = 200; + + /// Products there really are, when fewer than [total] claims. + int? available; + + final List categories = []; + final List pages = []; + + /// The filters JSON of each request, `null` — none. + final List?> params = ?>[]; + Completer? hold; + + /// Pages that fail while listed here. + final Set failing = {}; + + final List categoryViews = []; + int sources = 0; + + /// Shop facets of the answer: name → its product count and values. + Map filters = { + 'Мощность': { + 'count': 40, + 'values': {'1000': 20, '2000': 20}, + }, + 'Материал': { + 'count': 90, + 'values': {'Металл': 50, 'Пластик': 40}, + }, + // One value: nothing to choose from. + 'Страна': { + 'count': 200, + 'values': {'Китай': 200}, + }, + }; + + @override + Future getCategory( + String category, + int? limit, + int? page, + String? paramsJson, + String? shopId, + ) async { + categories.add(category); + pages.add(page!); + params.add( + paramsJson == null + ? null + : jsonDecode(paramsJson) as Map, + ); + await hold?.future; + if (failing.contains(page)) throw StateError('offline'); + final from = (page - 1) * limit!; + return jsonEncode({ + 'products': >[ + for (int i = from; i < from + limit && i < (available ?? total); i++) + {'id': '$i', 'name': 'Item $i', 'price': i}, + ], + 'products_total': total, + 'brands': >[ + {'name': 'Bosch', 'count': 3}, + {'name': 'Philips', 'count': 2}, + ], + 'price_range': {'min': 10, 'max': 900}, + 'filters': filters, + }); + } + + @override + Future trackCategoryView(String categoryId, String? shopId) async { + categoryViews.add(categoryId); + } + + @override + Future trackSetSource( + pigeon.TrackingSourceWire source, + String? shopId, + ) async { + sources++; + } +} + +Widget _host(Widget screen) => MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, height: 600, child: screen), + ), +); + +PersonalizationCatalog _catalog(WidgetTester tester) => + tester.widget(find.byType(PersonalizationCatalog)); + +PersonalizationSearchResultsTitle _title(WidgetTester tester) => + tester.widget( + find.byType(PersonalizationSearchResultsTitle), + ); + +/// Opens the filters screen from the title and returns its sections. +Future> _openFilters( + WidgetTester tester, +) async { + _title(tester).onFilters!(); + await tester.pump(); + return tester + .widget(find.byType(PersonalizationFilters)) + .sections; +} + +/// [sections] with [ids] checked in the options section [sectionId]. +List _check( + List sections, + String sectionId, + Set ids, +) => [ + for (final section in sections) + if (section is PersonalizationFilterOptions && section.id == sectionId) + section.copyWith( + options: [ + for (final option in section.options) + option.copyWith(checked: ids.contains(option.id)), + ], + ) + else + section, +]; + +void main() { + late _FakeHostApi api; + late PersonalizationSdk sdk; + + setUp(() { + api = _FakeHostApi(); + sdk = PersonalizationSdk(api: api); + }); + + Widget screen({ + String categoryId = 'tehnika-dlja-kuhni', + String? sortBy, + String? sortDir, + ValueChanged? onProductTap, + }) => _host( + PersonalizationCategoryScreen( + sdk: sdk, + categoryId: categoryId, + titleText: 'Техника для кухни', + sortBy: sortBy, + sortDir: sortDir, + onProductTap: onProductTap, + ), + ); + + testWidgets('asks for the category page by page under its title', ( + tester, + ) async { + await tester.pumpWidget(screen()); + await tester.pump(); + + expect(api.categories, ['tehnika-dlja-kuhni']); + expect(api.pages, [1]); + // No filter set: the request carries none. + expect(api.params, [null]); + expect(find.text('Техника для кухни'), findsOneWidget); + // "200 products": no prefix in front of the count. + expect(find.text('200'), findsOneWidget); + expect(find.text('products'), findsOneWidget); + expect(find.text('Found'), findsNothing); + expect(find.text('Item 0'), findsOneWidget); + + _catalog(tester).onLoadMore!(); + await tester.pump(); + expect(api.pages, [1, 2]); + expect(_catalog(tester).count!.shown, 40); + }); + + testWidgets('tracks the category view once: not per page, filter, sort or ' + 'retry', (tester) async { + await tester.pumpWidget(screen()); + await tester.pump(); + expect(api.categoryViews, ['tehnika-dlja-kuhni']); + + _catalog(tester).onLoadMore!(); + await tester.pump(); + + final sections = await _openFilters(tester); + tester + .widget(find.byType(PersonalizationFilters)) + .onApply!(_check(sections, 'brands', {'Bosch'})); + await tester.pump(); + + await tester.pumpWidget(screen(sortBy: 'price', sortDir: 'asc')); + await tester.pump(); + + api.failing.add(2); + _catalog(tester).onLoadMore!(); + await tester.pump(); + api.failing.clear(); + _catalog(tester).onLoadMore!(); + await tester.pump(); + + expect(api.pages, [1, 2, 1, 1, 2, 2]); + expect(api.categoryViews, ['tehnika-dlja-kuhni']); + + // Another category is another view. + await tester.pumpWidget(screen(categoryId: 'pylesosy')); + await tester.pump(); + expect(api.categoryViews, ['tehnika-dlja-kuhni', 'pylesosy']); + }); + + testWidgets('applied brands and facets, and the sort, go into the request', ( + tester, + ) async { + await tester.pumpWidget(screen(sortBy: 'discount', sortDir: 'desc')); + await tester.pump(); + expect(api.params.single, { + 'sort_by': 'discount', + 'sort_dir': 'desc', + }); + + var sections = await _openFilters(tester); + sections = _check(sections, 'brands', {'Bosch', 'Philips'}); + sections = _check(sections, 'facet:Материал', {'Металл'}); + tester + .widget(find.byType(PersonalizationFilters)) + .onApply!(sections); + await tester.pump(); + + expect(api.pages, [1, 1]); + expect(api.params.last, { + 'brands': 'Bosch,Philips', + 'filters': { + 'Материал': ['Металл'], + }, + 'sort_by': 'discount', + 'sort_dir': 'desc', + }); + // The applied values are tags under the title. + expect(_title(tester).filters.map((tag) => tag.label), [ + 'Bosch', + 'Philips', + 'Металл', + ]); + + _title(tester).filters.first.onRemove(); + await tester.pump(); + expect(api.params.last!['brands'], 'Philips'); + }); + + testWidgets('filter sections come from the category answer, with the price ' + 'range and the sort button', (tester) async { + await tester.pumpWidget(screen()); + await tester.pump(); + + expect(_title(tester).showSortButton, isTrue); + expect(_title(tester).showFiltersButton, isTrue); + + final sections = await _openFilters(tester); + // The price range, then brands and the facets with more than one value, the + // commonest first. No colour or size: a category has no industrial_filters. + expect(sections.map((section) => section.id), [ + 'price', + 'brands', + 'facet:Материал', + 'facet:Мощность', + ]); + final brands = sections[1] as PersonalizationFilterOptions; + // With the product count of each brand from the answer. + expect(brands.options.map((option) => option.label), [ + 'Bosch (3)', + 'Philips (2)', + ]); + }); + + testWidgets('a failed first page shows the error and retries it', ( + tester, + ) async { + final errors = []; + api.failing.add(1); + await tester.pumpWidget( + _host( + PersonalizationCategoryScreen( + sdk: sdk, + categoryId: 'tehnika-dlja-kuhni', + onError: errors.add, + ), + ), + ); + await tester.pump(); + + expect( + find.text(PersonalizationCategoryScreen.defaultErrorText), + findsOneWidget, + ); + expect(find.widgetWithText(PersonalizationButton, 'Retry'), findsOneWidget); + expect(find.text('products'), findsNothing); + expect(errors, hasLength(1)); + + api.failing.clear(); + await tester.tap(find.text('Retry')); + await tester.pump(); + + expect(api.pages, [1, 1]); + expect(find.text('Item 0'), findsOneWidget); + expect(find.text('Retry'), findsNothing); + expect(api.categoryViews, hasLength(1)); + }); + + testWidgets('a failed next page turns load more into retry', (tester) async { + await tester.pumpWidget(screen()); + await tester.pump(); + + api.failing.add(2); + _catalog(tester).onLoadMore!(); + await tester.pump(); + expect(_catalog(tester).loadMoreText, 'Retry'); + expect(find.text('Item 0'), findsOneWidget); + + api.failing.clear(); + _catalog(tester).onLoadMore!(); + await tester.pump(); + expect(api.pages, [1, 2, 2]); + expect(_catalog(tester).loadMoreText, 'Load more'); + expect(_catalog(tester).count!.shown, 40); + }); + + testWidgets('an empty category says so', (tester) async { + api.total = 0; + await tester.pumpWidget(screen()); + await tester.pump(); + + expect(find.text('No products in this category yet.'), findsOneWidget); + expect(find.text('0'), findsOneWidget); + expect(_catalog(tester).loadMoreText, isNull); + }); + + testWidgets('a page that comes back empty ends the feed, whatever the total ' + 'says', (tester) async { + api.available = 20; + await tester.pumpWidget(screen()); + await tester.pump(); + expect(_catalog(tester).loadMoreText, 'Load more'); + _catalog(tester).onLoadMore!(); + await tester.pump(); + + expect(api.pages, [1, 2]); + expect(_catalog(tester).loadMoreText, isNull); + _catalog(tester).onLoadMore!(); + await tester.pump(); + expect(api.pages, [1, 2]); + }); + + testWidgets('a product tap goes to the host with no tracking source', ( + tester, + ) async { + final tapped = []; + await tester.pumpWidget(screen(onProductTap: tapped.add)); + await tester.pump(); + + _catalog(tester).onProductTap!(_catalog(tester).products.first); + expect(tapped.single.id, '0'); + expect(api.sources, 0); + }); + + testWidgets('without a category nothing is asked or tracked', (tester) async { + await tester.pumpWidget(screen(categoryId: ' ')); + await tester.pump(); + + expect(api.pages, isEmpty); + expect(api.categoryViews, isEmpty); + expect(_catalog(tester).loading, isFalse); + }); +} diff --git a/test/ui/personalization_checkbox_test.dart b/test/ui/personalization_checkbox_test.dart new file mode 100644 index 0000000..da7b931 --- /dev/null +++ b/test/ui/personalization_checkbox_test.dart @@ -0,0 +1,133 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +/// Чекбокс в приложении светлой или тёмной темы. +Widget _host(Widget child, {Brightness brightness = Brightness.light}) => + MaterialApp( + theme: ThemeData(), + darkTheme: ThemeData(brightness: Brightness.dark), + themeMode: brightness == Brightness.dark + ? ThemeMode.dark + : ThemeMode.light, + home: Center(child: child), + ); + +Finder get _box => find.descendant( + of: find.byType(PersonalizationCheckbox), + matching: find.byType(CustomPaint), +); + +/// Пустой: заливка и рамка. +PaintPattern _unchecked(Color fill, Color border) => paints + ..rrect(color: fill, style: PaintingStyle.fill) + ..rrect(color: border, style: PaintingStyle.stroke); + +/// Отмеченный: заливка и галка. +PaintPattern _checked(Color fill, Color glyph) => paints + ..rrect(color: fill, style: PaintingStyle.fill) + ..path(color: glyph); + +void main() { + for (final (brightness, colors) in <(Brightness, PersonalizationColors)>[ + (Brightness.light, PersonalizationColors.light), + (Brightness.dark, PersonalizationColors.dark), + ]) { + testWidgets('without colors: the kit tokens of the ${brightness.name} ' + 'theme', (tester) async { + await tester.pumpWidget( + _host(const PersonalizationCheckbox(), brightness: brightness), + ); + await tester.pumpAndSettle(); + expect(_box, _unchecked(colors.backgroundInput, colors.lineInput)); + + await tester.pumpWidget( + _host( + const PersonalizationCheckbox( + state: PersonalizationCheckboxState.checked, + ), + brightness: brightness, + ), + ); + await tester.pumpAndSettle(); + expect(_box, _checked(colors.buttonPrimary, colors.textLightPrimary)); + }); + } + + testWidgets('with colors: the same in the light and the dark theme', ( + tester, + ) async { + const checked = Color(0xff16a34a); + const checkmark = Color(0xff111827); + const unchecked = Color(0xfffefce8); + const border = Color(0xffa16207); + for (final brightness in Brightness.values) { + await tester.pumpWidget( + _host( + const PersonalizationCheckbox( + checkedColor: checked, + checkmarkColor: checkmark, + uncheckedColor: unchecked, + borderColor: border, + ), + brightness: brightness, + ), + ); + await tester.pumpAndSettle(); + expect(_box, _unchecked(unchecked, border)); + + await tester.pumpWidget( + _host( + const PersonalizationCheckbox( + state: PersonalizationCheckboxState.checked, + checkedColor: checked, + checkmarkColor: checkmark, + uncheckedColor: unchecked, + borderColor: border, + ), + brightness: brightness, + ), + ); + await tester.pumpAndSettle(); + expect(_box, _checked(checked, checkmark)); + } + }); + + testWidgets('disabled with colors keeps the disabled fills of the kit', ( + tester, + ) async { + const colors = PersonalizationColors.light; + await tester.pumpWidget( + _host( + const PersonalizationCheckbox( + disabled: true, + checkedColor: Color(0xff16a34a), + uncheckedColor: Color(0xfffefce8), + ), + ), + ); + expect( + _box, + paints..rrect( + color: colors.backgroundInputDisabled, + style: PaintingStyle.fill, + ), + ); + + await tester.pumpWidget( + _host( + const PersonalizationCheckbox( + state: PersonalizationCheckboxState.checked, + disabled: true, + checkedColor: Color(0xff16a34a), + uncheckedColor: Color(0xfffefce8), + ), + ), + ); + expect( + _box, + paints + ..rrect(color: colors.buttonPrimaryDisabled, style: PaintingStyle.fill), + ); + }); +} diff --git a/test/ui/personalization_filter_values_test.dart b/test/ui/personalization_filter_values_test.dart new file mode 100644 index 0000000..369842d --- /dev/null +++ b/test/ui/personalization_filter_values_test.dart @@ -0,0 +1,273 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/ui/widgets/personalization_results_screen_base.dart' + show facetValueLabel, jsonValueTitle; + +/// A value that is an object with a title, as stickers come in a feed. +const String _sticker = + '{"slug": "super_price", "title": "Суперцена", "text_color": "#ffffff", ' + '"background_color": "#f48012", "priority": 1}'; + +/// One page answer of search and category alike: brands with counts, colours and +/// sizes (search only) and shop facets, one of them with object values. +Map _answer() => { + 'products': [ + {'id': '1', 'name': 'Item', 'price': 1}, + ], + 'products_total': 1, + 'brands': [ + {'name': 'Bosch', 'count': 3}, + // A bare name, as iOS sends the brands of a full search: no count. + 'Philips', + ], + 'industrial_filters': { + 'colors': [ + {'color': 'red', 'count': 4}, + {'color': 'blue'}, + ], + 'fashion_sizes': [ + {'size': '42', 'count': 2}, + ], + }, + 'filters': { + 'stickers': { + 'count': 9, + 'values': {_sticker: 5, 'new': 4}, + }, + 'product_type': { + 'count': 8, + 'values': {'regular': 6, 'digital': 2}, + }, + }, +}; + +class _FakeHostApi extends pigeon.PersonalizationHostApi { + /// The filters JSON of each request. + final List> params = >[]; + + @override + Future searchFull( + String query, + String? paramsJson, + String? shopId, + ) async { + params.add(jsonDecode(paramsJson!) as Map); + return jsonEncode(_answer()); + } + + @override + Future getCategory( + String category, + int? limit, + int? page, + String? paramsJson, + String? shopId, + ) async { + params.add( + paramsJson == null + ? {} + : jsonDecode(paramsJson) as Map, + ); + return jsonEncode(_answer()); + } + + @override + Future trackSearch( + String query, + List? results, + String? shopId, + ) async {} + + @override + Future trackCategoryView(String categoryId, String? shopId) async {} +} + +Widget _host(Widget screen) => + MaterialApp(home: SizedBox(width: 400, height: 600, child: screen)); + +/// Opens the filters and returns the labels of each options section by its id. +Future>> _labels(WidgetTester tester) async { + tester + .widget( + find.byType(PersonalizationSearchResultsTitle), + ) + .onFilters!(); + await tester.pump(); + return >{ + for (final section + in tester + .widget(find.byType(PersonalizationFilters)) + .sections) + if (section is PersonalizationFilterOptions) + section.id: [ + for (final option in section.options) option.label, + ], + }; +} + +void main() { + group('jsonValueTitle', () { + test('an object with a title is labelled by the title', () { + expect(jsonValueTitle(_sticker), 'Суперцена'); + expect(jsonValueTitle(' {"title": "Hit"} '), 'Hit'); + }); + + test('anything else is shown as it is', () { + for (final value in [ + 'regular', + '{"title": "Hit"', + '{"slug": "hit"}', + '{"title": 1}', + '{"title": " "}', + '["title"]', + '', + ]) { + expect(jsonValueTitle(value), isNull, reason: value); + } + }); + }); + + test('a label from the host comes first, then the title, then the value', () { + String? host(String facet, String value) => + facet == 'product_type' && value == 'digital' ? 'Цифровой' : null; + + expect(facetValueLabel('product_type', 'digital', host), 'Цифровой'); + expect(facetValueLabel('product_type', 'regular', host), 'regular'); + expect(facetValueLabel('stickers', _sticker, host), 'Суперцена'); + expect(facetValueLabel('stickers', _sticker, (_, _) => ''), 'Суперцена'); + expect(facetValueLabel('stickers', _sticker, (_, _) => 'Mine'), 'Mine'); + expect(facetValueLabel('stickers', 'new', null), 'new'); + }); + + late _FakeHostApi api; + late PersonalizationSdk sdk; + + setUp(() { + api = _FakeHostApi(); + sdk = PersonalizationSdk(api: api); + }); + + testWidgets('search: titles of object values and product counts next to ' + 'brands, colours, sizes and facet values', (tester) async { + await tester.pumpWidget( + _host(PersonalizationSearchResultsScreen(sdk: sdk, query: 'q')), + ); + await tester.pump(); + + final labels = await _labels(tester); + expect(labels['brands'], ['Bosch (3)', 'Philips']); + expect(labels['colors'], ['red (4)', 'blue']); + expect(labels['sizes'], ['42 (2)']); + expect(labels['facet:stickers'], ['new (4)', 'Суперцена (5)']); + expect(labels['facet:product_type'], [ + 'digital (2)', + 'regular (6)', + ]); + }); + + testWidgets('showValueCounts off leaves the counts out', (tester) async { + await tester.pumpWidget( + _host( + PersonalizationSearchResultsScreen( + sdk: sdk, + query: 'q', + showValueCounts: false, + ), + ), + ); + await tester.pump(); + + final labels = await _labels(tester); + expect(labels['brands'], ['Bosch', 'Philips']); + expect(labels['colors'], ['red', 'blue']); + expect(labels['facet:stickers'], ['new', 'Суперцена']); + }); + + testWidgets('category: the request carries the original value, the tag its ' + 'title without a count', (tester) async { + await tester.pumpWidget( + _host( + PersonalizationCategoryScreen( + sdk: sdk, + categoryId: 'c', + titleText: 'C', + ), + ), + ); + await tester.pump(); + + final labels = await _labels(tester); + expect(labels['brands'], ['Bosch (3)', 'Philips']); + expect(labels['facet:stickers'], ['new (4)', 'Суперцена (5)']); + + final filters = tester.widget( + find.byType(PersonalizationFilters), + ); + filters.onApply!([ + for (final section in filters.sections) + if (section is PersonalizationFilterOptions && + section.id == 'facet:stickers') + section.copyWith( + options: [ + for (final option in section.options) + option.copyWith(checked: option.id == _sticker), + ], + ) + else + section, + ]); + await tester.pump(); + + expect(api.params.last['filters'], { + 'stickers': [_sticker], + }); + final tags = tester + .widget( + find.byType(PersonalizationSearchResultsTitle), + ) + .filters; + expect(tags.map((tag) => tag.label), ['Суперцена']); + }); + + testWidgets('labels from the host win over titles; facet titles fall back ' + 'to the kit', (tester) async { + await tester.pumpWidget( + _host( + PersonalizationCategoryScreen( + sdk: sdk, + categoryId: 'c', + facetTitle: (name) => name == 'stickers' ? 'Стикеры' : null, + facetValueTitle: (facet, value) => switch ((facet, value)) { + ('product_type', 'regular') => 'Обычный', + ('product_type', 'digital') => 'Цифровой', + ('stickers', _sticker) => 'Акция', + _ => null, + }, + ), + ), + ); + await tester.pump(); + + final labels = await _labels(tester); + expect(labels['facet:product_type'], [ + 'Обычный (6)', + 'Цифровой (2)', + ]); + expect(labels['facet:stickers'], ['new (4)', 'Акция (5)']); + final titles = { + for (final section + in tester + .widget( + find.byType(PersonalizationFilters), + ) + .sections) + section.id: section.title, + }; + expect(titles['facet:stickers'], 'Стикеры'); + expect(titles['facet:product_type'], 'Product type'); + }); +} diff --git a/test/ui/personalization_filters_test.dart b/test/ui/personalization_filters_test.dart new file mode 100644 index 0000000..d579294 --- /dev/null +++ b/test/ui/personalization_filters_test.dart @@ -0,0 +1,74 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +/// Dozens of facets do not push Apply off the screen: the title and the buttons +/// stay put and only the sections scroll. Inside a host's scroll the screen is +/// as tall as its content. +PersonalizationFilters _filters(int sections) => PersonalizationFilters( + title: 'Filters', + resetText: 'Reset', + applyText: 'Apply', + sections: [ + for (int i = 1; i <= sections; i++) + PersonalizationFilterOptions( + id: 'facet$i', + title: 'Facet $i', + options: [ + for (int j = 1; j <= 3; j++) + PersonalizationFilterOption(id: '$i-$j', label: 'Value $i.$j'), + ], + ), + ], +); + +void main() { + testWidgets( + 'with a set height the buttons stay on screen and sections scroll', + (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 360, height: 600, child: _filters(30)), + ), + ), + ); + + expect(tester.takeException(), isNull); + expect( + tester.getBottomLeft(find.text('Apply')).dy, + lessThanOrEqualTo(600), + ); + expect(tester.getTopLeft(find.text('Filters')).dy, lessThan(60)); + expect(tester.getTopLeft(find.text('Facet 30')).dy, greaterThan(600)); + + await tester.drag( + find.byType(SingleChildScrollView), + const Offset(0, -5000), + ); + await tester.pump(); + expect(tester.getTopLeft(find.text('Facet 30')).dy, lessThan(600)); + expect( + tester.getBottomLeft(find.text('Apply')).dy, + lessThanOrEqualTo(600), + ); + }, + ); + + testWidgets('inside a host scroll the screen follows its content', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: SingleChildScrollView( + child: SizedBox(width: 360, child: _filters(2)), + ), + ), + ); + + expect(tester.takeException(), isNull); + expect(find.text('Facet 2'), findsOneWidget); + expect(find.text('Apply'), findsOneWidget); + }); +} diff --git a/test/ui/personalization_load_state_test.dart b/test/ui/personalization_load_state_test.dart new file mode 100644 index 0000000..209773d --- /dev/null +++ b/test/ui/personalization_load_state_test.dart @@ -0,0 +1,120 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/widgets/personalization_load_state.dart'; + +void main() { + late PersonalizationLoadController> controller; + late List>> states; + + setUp(() { + controller = PersonalizationLoadController>(); + states = >>[]; + controller.addListener(() => states.add(controller.value)); + }); + + tearDown(() => controller.dispose()); + + test('starts idle', () { + expect(controller.value, isA>>()); + }); + + test('loading, then the data', () async { + await controller.load(() async => ['a']); + expect(states, hasLength(2)); + expect(states[0], isA>>()); + final content = states[1] as PersonalizationLoadContent>; + expect(content.data, ['a']); + }); + + test('an empty answer is empty, not content', () async { + await controller.load(() async => []); + expect(controller.value, isA>>()); + }); + + test('a custom emptiness check', () async { + final custom = PersonalizationLoadController(isEmpty: (n) => n == 0); + addTearDown(custom.dispose); + await custom.load(() async => 0); + expect(custom.value, isA>()); + await custom.load(() async => 3); + expect((custom.value as PersonalizationLoadContent).data, 3); + }); + + test('an error, and retry repeats the same request', () async { + var calls = 0; + Future> load() async { + calls++; + if (calls == 1) throw StateError('offline'); + return ['a']; + } + + await controller.load(load); + final error = controller.value as PersonalizationLoadError>; + expect(error.error, isStateError); + + await controller.retry(); + expect(calls, 2); + expect(states.map((s) => s.runtimeType).toList(), [ + PersonalizationLoadLoading>, + PersonalizationLoadError>, + PersonalizationLoadLoading>, + PersonalizationLoadContent>, + ]); + }); + + test('retry without a request does nothing', () async { + await controller.retry(); + expect(states, isEmpty); + }); + + test('an answer to an older request is dropped', () async { + final slow = Completer>(); + final first = controller.load(() => slow.future); + await controller.load(() async => ['new']); + slow.complete(['old']); + await first; + expect( + (controller.value as PersonalizationLoadContent>).data, + ['new'], + ); + }); + + test('reset goes back to idle and drops the request in flight', () async { + final slow = Completer>(); + final pending = controller.load(() => slow.future); + controller.reset(); + slow.complete(['late']); + await pending; + expect(controller.value, isA>>()); + await controller.retry(); + expect(controller.value, isA>>()); + }); + + test('an answer after dispose is dropped quietly', () async { + final own = PersonalizationLoadController>(); + final slow = Completer>(); + final pending = own.load(() => slow.future); + own.dispose(); + slow.complete(['late']); + await pending; + }); + + test('after dispose load, retry and reset do nothing', () async { + final own = PersonalizationLoadController>(); + var calls = 0; + await own.load(() async { + calls++; + throw StateError('offline'); + }); + own.dispose(); + + await own.load(() async { + calls++; + return ['a']; + }); + await own.retry(); + own.reset(); + expect(calls, 1); + }); +} diff --git a/test/ui/personalization_products_block_test.dart b/test/ui/personalization_products_block_test.dart new file mode 100644 index 0000000..a9bb523 --- /dev/null +++ b/test/ui/personalization_products_block_test.dart @@ -0,0 +1,66 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +Widget _host(Widget child) => MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, child: child), + ), +); + +const List _rated = [ + PersonalizationProduct( + id: '1', + name: 'Rated', + price: '1', + rating: PersonalizationProductRating(value: '4,7', reviews: 12), + ), +]; + +void main() { + testWidgets('no title and no show-all button — no title row', (tester) async { + for (final title in [null, '']) { + await tester.pumpWidget( + _host( + PersonalizationProductsBlock( + layout: PersonalizationProductsLayout.list, + title: title, + products: _rated, + ), + ), + ); + expect(find.byType(PersonalizationTitle), findsNothing); + expect(find.text('Rated'), findsOneWidget); + } + }); + + testWidgets('the show-all button keeps the title row without a title', ( + tester, + ) async { + await tester.pumpWidget( + _host( + PersonalizationProductsBlock(showAllText: 'Show all', products: _rated), + ), + ); + expect(find.byType(PersonalizationTitle), findsOneWidget); + expect(find.text('Show all'), findsOneWidget); + }); + + testWidgets('the rating shows only with showRating', (tester) async { + Widget block({required bool showRating}) => _host( + PersonalizationProductsBlock( + title: 'Rated', + layout: PersonalizationProductsLayout.grid, + showRating: showRating, + products: _rated, + ), + ); + + await tester.pumpWidget(block(showRating: true)); + expect(find.byType(PersonalizationRating), findsOneWidget); + + await tester.pumpWidget(block(showRating: false)); + expect(find.byType(PersonalizationRating), findsNothing); + }); +} diff --git a/test/ui/personalization_recommender_block_test.dart b/test/ui/personalization_recommender_block_test.dart new file mode 100644 index 0000000..eae0735 --- /dev/null +++ b/test/ui/personalization_recommender_block_test.dart @@ -0,0 +1,473 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/ui/widgets/personalization_request_cache.dart'; + +const String _code = 'e6249bb15043644bf25b135006149962'; + +/// A live answer from test/fixtures without its pictures: images do not load in +/// widget tests. +Map _fixture(String name, String list) { + final json = + jsonDecode(File('test/fixtures/$name.json').readAsStringSync()) + as Map; + for (final product in json[list] as List) { + (product as Map) + ..remove('picture') + ..remove('image_url') + ..remove('image_url_resized'); + } + return json; +} + +/// Host API that answers recommendations (title «Популярные», two products, the +/// first discounted) and collections from the fixtures. While [hold] is set, +/// answers wait for it; while [failure] is set, they fail with it. +class _FakeHostApi extends pigeon.PersonalizationHostApi { + Map recommendation = _fixture( + 'recommend_extended', + 'recommends', + ); + Map collection = _fixture('products', 'products'); + + /// `paramsJson` of every recommendation request, in order. + final List recommendations = []; + final List collections = []; + final List sources = []; + Completer? hold; + Object? failure; + + @override + Future getRecommendation( + String code, + String? paramsJson, + String? shopId, + ) async { + recommendations.add(paramsJson); + await hold?.future; + if (failure != null) throw failure!; + return jsonEncode(recommendation); + } + + @override + Future getCollection(String collectionId, String? shopId) async { + collections.add(collectionId); + await hold?.future; + if (failure != null) throw failure!; + return jsonEncode(collection); + } + + @override + Future trackSetSource( + pigeon.TrackingSourceWire source, + String? shopId, + ) async { + sources.add(source); + } +} + +Widget _host(Widget block) => MaterialApp( + home: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(key: Key('above'), height: 10), + block, + const SizedBox(key: Key('below'), height: 10), + ], + ), + ), +); + +/// Cards of a list take the screen's width: the test font draws every glyph a +/// square, and the live prices do not fit a carousel card in it. +const PersonalizationProductsLayout _list = PersonalizationProductsLayout.list; + +final Finder _block = find.byType(PersonalizationProductsBlock); +final Finder _cards = find.byType(PersonalizationProductCard); + +/// The answer arrives, and the block fades in. +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); +} + +/// Opacity of the block's fade-in. +double _opacity(WidgetTester tester) => tester + .widget( + find.ancestor(of: _block, matching: find.byType(FadeTransition)).first, + ) + .opacity + .value; + +/// Space the block takes between its neighbours. +double _gap(WidgetTester tester) => + tester.getTopLeft(find.byKey(const Key('below'))).dy - + tester.getBottomLeft(find.byKey(const Key('above'))).dy; + +void main() { + late _FakeHostApi api; + late PersonalizationSdk sdk; + + setUp(() { + PersonalizationRequestCache.shared.clear(); + api = _FakeHostApi(); + sdk = PersonalizationSdk(api: api); + }); + + group('title', () { + testWidgets('comes from the answer', (tester) async { + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock(code: _code, layout: _list, sdk: sdk), + ), + ); + await _settle(tester); + expect(find.text('Популярные'), findsOneWidget); + expect(_cards, findsNWidgets(2)); + }); + + testWidgets('of the host wins over the answer', (tester) async { + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + title: 'For you', + ), + ), + ); + await _settle(tester); + expect(find.text('For you'), findsOneWidget); + expect(find.text('Популярные'), findsNothing); + }); + + testWidgets('empty — no title row', (tester) async { + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + title: '', + ), + ), + ); + await _settle(tester); + expect(find.byType(PersonalizationTitle), findsNothing); + expect(_cards, findsNWidgets(2)); + }); + }); + + group('hidden', () { + testWidgets('while loading: no block and no space', (tester) async { + api.hold = Completer(); + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock(code: _code, layout: _list, sdk: sdk), + ), + ); + await tester.pump(); + expect(_block, findsNothing); + expect(_gap(tester), 0); + + // The answer is in: the block takes its place and fades in. + api.hold!.complete(); + await tester.pump(); + await tester.pump(); + expect(_block, findsOneWidget); + expect(_gap(tester), greaterThan(0)); + expect(_opacity(tester), lessThan(1)); + await tester.pump(const Duration(milliseconds: 150)); + expect(_opacity(tester), 1); + }); + + testWidgets('fewer products than minProducts — onLoaded(0)', ( + tester, + ) async { + final loaded = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + minProducts: 3, + onLoaded: loaded.add, + ), + ), + ); + await _settle(tester); + expect(_block, findsNothing); + expect(_gap(tester), 0); + expect(loaded, [0]); + }); + + testWidgets('an empty answer — onLoaded(0)', (tester) async { + api.recommendation = { + 'title': 'Популярные', + 'recommends': [], + }; + final loaded = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + minProducts: 0, + onLoaded: loaded.add, + ), + ), + ); + await _settle(tester); + expect(_block, findsNothing); + expect(loaded, [0]); + }); + + testWidgets('an error — onError, no onLoaded', (tester) async { + api.failure = StateError('offline'); + final errors = []; + final loaded = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + onLoaded: loaded.add, + onError: errors.add, + ), + ), + ); + await _settle(tester); + expect(_block, findsNothing); + expect(_gap(tester), 0); + expect(errors.single, isStateError); + expect(loaded, isEmpty); + }); + + testWidgets('an unknown shop — onError', (tester) async { + final errors = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + shopId: 'no-such-shop', + onError: errors.add, + ), + ), + ); + await _settle(tester); + expect(_block, findsNothing); + expect(errors.single, isA()); + }); + }); + + testWidgets('limit cuts the answer on the client', (tester) async { + final loaded = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + limit: 1, + onLoaded: loaded.add, + ), + ), + ); + await _settle(tester); + expect(_cards, findsOneWidget); + expect(loaded, [1]); + }); + + testWidgets('a second block with the same parameters shows the cached ' + 'answer in its first frame, without a request', (tester) async { + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock(code: _code, layout: _list, sdk: sdk), + ), + ); + await _settle(tester); + expect(api.recommendations, hasLength(1)); + + // The feed recreated the cell: a new state, same parameters. + final loaded = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + key: const Key('again'), + code: _code, + layout: _list, + sdk: sdk, + onLoaded: loaded.add, + ), + ), + ); + expect(_cards, findsNWidgets(2)); + expect(_opacity(tester), 1); + await _settle(tester); + expect(api.recommendations, hasLength(1)); + expect(loaded, [2]); + }); + + testWidgets( + 'reload goes past the cache and keeps the block until the answer', + (tester) async { + final controller = PersonalizationRecommenderBlockController(); + final loaded = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + controller: controller, + onLoaded: loaded.add, + ), + ), + ); + await _settle(tester); + + api.hold = Completer(); + var done = false; + unawaited(controller.reload().then((_) => done = true)); + await tester.pump(); + expect(api.recommendations, hasLength(2)); + expect(_cards, findsNWidgets(2)); + expect(done, isFalse); + + api.recommendation['recommends'] = [ + (api.recommendation['recommends'] as List).first, + ]; + api.hold!.complete(); + await _settle(tester); + expect(done, isTrue); + expect(_cards, findsOneWidget); + expect(loaded, [2, 1]); + }, + ); + + testWidgets('new parameters load again', (tester) async { + Widget block(String itemId) => _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + itemId: itemId, + ), + ); + await tester.pumpWidget(block('1')); + await _settle(tester); + await tester.pumpWidget(block('2')); + await _settle(tester); + expect( + api.recommendations.map( + (params) => (jsonDecode(params!) as Map)['item_id'], + ), + ['1', '2'], + ); + }); + + testWidgets('a tap sets the dynamic source with the code, then calls the ' + 'host with the mapped product', (tester) async { + final tapped = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + onProductTap: (product) { + // The source is asked for before the host hears of the tap. + expect(api.sources, hasLength(1)); + tapped.add(product); + }, + ), + ), + ); + await _settle(tester); + await tester.tap(_cards.first); + await tester.pump(); + + expect(api.sources.single.type, 'dynamic'); + expect(api.sources.single.code, _code); + final product = tapped.single; + expect(product.id, '52173'); + expect(product.price, '164 990 ₽'); + expect(product.oldPrice, '174 990 ₽'); + expect(product.discount, '-6%'); + expect( + product.deeplink, + 'https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173', + ); + expect(product.url, startsWith('https://www.technodom.kz/p/holodilnik')); + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + + testWidgets('the card button sets the dynamic source with the code, then ' + 'calls the host', (tester) async { + final added = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock( + code: _code, + layout: _list, + sdk: sdk, + actionText: 'Buy', + onProductAction: (product) { + // The source is asked for before the host hears of the button. + expect(api.sources, hasLength(1)); + added.add(product); + }, + ), + ), + ); + await _settle(tester); + await tester.tap(find.text('Buy').first); + await tester.pump(); + + expect(api.sources.single.type, 'dynamic'); + expect(api.sources.single.code, _code); + expect(added.single.id, '52173'); + }); + + testWidgets('a collection: no title of its own, no source on a tap or ' + 'the card button', (tester) async { + final tapped = []; + final added = []; + await tester.pumpWidget( + _host( + PersonalizationRecommenderBlock.collection( + collectionId: '42', + layout: _list, + sdk: sdk, + actionText: 'Buy', + onProductTap: tapped.add, + onProductAction: added.add, + ), + ), + ); + await _settle(tester); + expect(api.collections, ['42']); + expect(api.recommendations, isEmpty); + expect(find.byType(PersonalizationTitle), findsNothing); + expect(_cards, findsNWidgets(2)); + expect(find.text('Buy'), findsNWidgets(2)); + + await tester.tap(_cards.first); + await tester.pump(); + expect(tapped.single.id, '300252'); + await tester.tap(find.text('Buy').first); + await tester.pump(); + expect(added.single.id, '300252'); + expect(api.sources, isEmpty); + }); +} diff --git a/test/ui/personalization_request_cache_test.dart b/test/ui/personalization_request_cache_test.dart new file mode 100644 index 0000000..6440874 --- /dev/null +++ b/test/ui/personalization_request_cache_test.dart @@ -0,0 +1,306 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/widgets/personalization_request_cache.dart'; + +/// The answer to one [PersonalizationRequestCache.fetch] as a future. +Future get( + PersonalizationRequestCache cache, + String key, + Future Function() load, { + bool force = false, +}) { + final answer = Completer(); + cache.fetch( + key, + load, + onValue: answer.complete, + onError: answer.completeError, + force: force, + ); + return answer.future; +} + +void main() { + late Duration now; + late PersonalizationRequestCache cache; + + setUp(() { + now = Duration.zero; + cache = PersonalizationRequestCache(clock: () => now); + }); + + /// A loader that counts its calls and answers [value]. + ({Future Function() load, int Function() calls}) loader( + String value, + ) { + var calls = 0; + return ( + load: () async { + calls++; + return value; + }, + calls: () => calls, + ); + } + + test('the key holds the shop, the kind and the sorted parameters', () { + String key(String? shop, String kind, Map params) => + PersonalizationRequestCache.keyOf(shop, kind, params); + + final base = key('shop', 'recommend', {'b': 2, 'a': 'x'}); + expect(key('shop', 'recommend', {'a': 'x', 'b': 2}), base); + expect(key('shop', 'recommend', {'a': 'x', 'b': 2, 'none': null}), base); + expect(key('other', 'recommend', {'a': 'x', 'b': 2}), isNot(base)); + expect(key('shop', 'search', {'a': 'x', 'b': 2}), isNot(base)); + expect(key('shop', 'recommend', {'a': 'x', 'b': '2'}), isNot(base)); + }); + + test('values are encoded, not glued together', () { + expect( + PersonalizationRequestCache.keyOf('shop', 'search', { + 'query': 'tv&sort=price', + }), + isNot( + PersonalizationRequestCache.keyOf('shop', 'search', { + 'query': 'tv', + 'sort': 'price', + }), + ), + ); + expect( + PersonalizationRequestCache.keyOf('a|b', 'c'), + isNot(PersonalizationRequestCache.keyOf('a', 'b|c')), + ); + }); + + test('a fresh answer comes from the cache', () async { + final source = loader('v1'); + expect(await get(cache, 'k', source.load), 'v1'); + now += const Duration(minutes: 9, seconds: 59); + expect(await get(cache, 'k', source.load), 'v1'); + expect(source.calls(), 1); + }); + + test('after ten minutes the request goes out again', () async { + final source = loader('v1'); + await get(cache, 'k', source.load); + now += const Duration(minutes: 10); + await get(cache, 'k', source.load); + expect(source.calls(), 2); + }); + + test('past 32 entries the oldest goes', () async { + for (var i = 0; i < 33; i++) { + await get(cache, 'k$i', loader('v$i').load); + } + expect(cache.length, 32); + + final first = loader('again'); + expect(await get(cache, 'k0', first.load), 'again'); + expect(first.calls(), 1); + final second = loader('again'); + expect(await get(cache, 'k2', second.load), 'v2'); + expect(second.calls(), 0); + }); + + test('a refreshed entry counts as the newest', () async { + final small = PersonalizationRequestCache(capacity: 2, clock: () => now); + await get(small, 'a', loader('a1').load); + await get(small, 'b', loader('b1').load); + now += const Duration(minutes: 11); + await get(small, 'a', loader('a2').load); + await get(small, 'c', loader('c1').load); + + expect(await get(small, 'a', loader('a3').load), 'a2'); + final b = loader('b2'); + expect(await get(small, 'b', b.load), 'b2'); + expect(b.calls(), 1); + }); + + test('the same request in flight goes out once', () async { + final gate = Completer(); + var calls = 0; + Future load() { + calls++; + return gate.future; + } + + final one = get(cache, 'k', load); + final two = get(cache, 'k', load); + final other = get(cache, 'other', load); + gate.complete('v'); + + expect(await one, 'v'); + expect(await two, 'v'); + expect(await other, 'v'); + expect(calls, 2); + }); + + test('an error reaches every waiter and is not cached', () async { + final gate = Completer(); + final one = get(cache, 'k', () => gate.future); + final two = get(cache, 'k', () async => 'never'); + // Both waiters listen before the error arrives, as callers awaiting them do. + final failures = Future.wait(>[ + expectLater(one, throwsStateError), + expectLater(two, throwsStateError), + ]); + gate.completeError(StateError('offline')); + await failures; + expect(cache.length, 0); + + final retry = loader('v'); + expect(await get(cache, 'k', retry.load), 'v'); + expect(retry.calls(), 1); + }); + + test('clear forgets every answer', () async { + await get(cache, 'k', loader('v1').load); + cache.clear(); + final source = loader('v2'); + expect(await get(cache, 'k', source.load), 'v2'); + expect(source.calls(), 1); + }); + + test( + 'a request hanging past 30 seconds takes no one: a new one goes out', + () async { + final hung = Completer(); + var calls = 0; + final first = get(cache, 'k', () { + calls++; + return hung.future; + }); + now += const Duration(seconds: 29); + final joined = get(cache, 'k', () async => 'never'); + now += const Duration(seconds: 2); + final fresh = get(cache, 'k', () async { + calls++; + return 'new'; + }); + + expect(await fresh, 'new'); + expect(calls, 2); + + // The old generation answers its own waiters and does not overwrite the cache. + hung.complete('old'); + expect(await first, 'old'); + expect(await joined, 'old'); + expect(await get(cache, 'k', () async => 'never'), 'new'); + }, + ); + + test('once every waiter leaves, the same key loads again', () async { + final gate = Completer(); + var called = false; + final subscription = cache.fetch( + 'k', + () => gate.future, + onValue: (_) => called = true, + ); + subscription.cancel(); + + final again = loader('v2'); + final second = get(cache, 'k', again.load); + gate.complete('v1'); + expect(await second, 'v2'); + expect(again.calls(), 1); + await pumpEventQueue(); + expect(called, isFalse); + }); + + test('a waiter that leaves is not called back, the rest are', () async { + final gate = Completer(); + var left = false; + final leaving = cache.fetch( + 'k', + () => gate.future, + onValue: (_) => left = true, + ); + final stayed = get(cache, 'k', () async => 'never'); + // One of two waiters leaves: the request stays in flight for the other. + leaving.cancel(); + gate.complete('v'); + expect(await stayed, 'v'); + expect(left, isFalse); + }); + + test('clear during a request keeps its answer out of the cache', () async { + final gate = Completer(); + final pending = get(cache, 'k', () => gate.future); + cache.clear(); + gate.complete('v1'); + expect(await pending, 'v1'); + expect(cache.length, 0); + + final again = loader('v2'); + expect(await get(cache, 'k', again.load), 'v2'); + expect(again.calls(), 1); + }); + + test('force goes past the cached answer and the request in flight', () async { + await get(cache, 'k', loader('v1').load); + final forced = loader('v2'); + expect(await get(cache, 'k', forced.load, force: true), 'v2'); + expect(forced.calls(), 1); + expect(await get(cache, 'k', loader('never').load), 'v2'); + + final gate = Completer(); + final slow = get(cache, 'other', () => gate.future); + final retry = loader('fresh'); + expect(await get(cache, 'other', retry.load, force: true), 'fresh'); + gate.complete('stale'); + expect(await slow, 'stale'); + expect(await get(cache, 'other', loader('never').load), 'fresh'); + }); + + test( + 'a throwing callback does not keep the answer from the others', + () async { + final reported = []; + final previous = FlutterError.onError; + FlutterError.onError = reported.add; + addTearDown(() => FlutterError.onError = previous); + + final gate = Completer(); + cache.fetch( + 'k', + () => gate.future, + onValue: (_) => throw StateError('broken widget'), + ); + final other = get(cache, 'k', () async => 'never'); + gate.complete('v'); + + expect(await other, 'v'); + expect(reported, hasLength(1)); + expect(reported.single.exception, isStateError); + }, + ); + + test('a cached answer comes later, and not after cancel', () async { + await get(cache, 'k', loader('v').load); + var calls = 0; + cache + .fetch('k', loader('never').load, onValue: (_) => calls++) + .cancel(); + cache.fetch('k', loader('never').load, onValue: (_) => calls++); + expect(calls, 0); + await pumpEventQueue(); + expect(calls, 1); + }); + + test('peek gives a fresh answer at once, nothing for a stale one', () async { + expect(cache.peek('k'), isNull); + final gate = Completer(); + final answer = get(cache, 'k', () => gate.future); + // In flight is not an answer yet. + expect(cache.peek('k'), isNull); + gate.complete('v'); + await answer; + expect(cache.peek('k'), 'v'); + now = const Duration(minutes: 10); + expect(cache.peek('k'), isNull); + }); +} diff --git a/test/ui/personalization_results_facets_test.dart b/test/ui/personalization_results_facets_test.dart new file mode 100644 index 0000000..c7bb86b --- /dev/null +++ b/test/ui/personalization_results_facets_test.dart @@ -0,0 +1,150 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/ui/widgets/personalization_results_screen_base.dart' + show visibleFacets; + +/// Facet `f` carried by `i` products, with two values; `single` has one value and +/// the most products. +Map _facets(int count) => { + for (int i = 1; i <= count; i++) + 'f$i': SearchFilter(count: i, values: const {'a': 1, 'b': 1}), + 'single': const SearchFilter(count: 1000, values: {'a': 1000}), +}; + +/// Full search with [facets] count of facets shaped as [_facets]. +class _FakeHostApi extends pigeon.PersonalizationHostApi { + _FakeHostApi(this.facets); + + final int facets; + + @override + Future searchFull( + String query, + String? paramsJson, + String? shopId, + ) async => jsonEncode({ + 'products': [ + {'id': '1', 'name': 'Item', 'price': 1}, + ], + 'products_total': 1, + 'filters': { + for (final entry in _facets(facets).entries) + entry.key: { + 'count': entry.value.count, + 'values': entry.value.values, + }, + }, + }); + + @override + Future trackSearch( + String query, + List? results, + String? shopId, + ) async {} +} + +void main() { + group('visibleFacets', () { + test( + 'facets with more than one value, commonest first, ten by default', + () { + expect(visibleFacets(_facets(12), maxFacets: 10), [ + for (int i = 12; i >= 3; i--) 'f$i', + ]); + }, + ); + + test('null or zero maxFacets shows all of them', () { + final all = [for (int i = 12; i >= 1; i--) 'f$i']; + expect(visibleFacets(_facets(12)), all); + expect(visibleFacets(_facets(12), maxFacets: 0), all); + }); + + test('equal counts go by name', () { + const two = SearchFilter(count: 5, values: {'a': 1, 'b': 1}); + expect( + visibleFacets(const {'b': two, 'a': two}), + ['a', 'b'], + ); + }); + + test('the host list wins, in its order, without the limit', () { + expect( + visibleFacets( + _facets(12), + wanted: {'f1', 'single', 'missing', 'f7'}, + maxFacets: 2, + ), + ['f1', 'single', 'f7'], + ); + }); + + test('a facet with checked values stays, after the chosen ones', () { + expect( + visibleFacets( + _facets(12), + maxFacets: 2, + checked: {'f1', 'f12'}, + ), + ['f12', 'f11', 'f1'], + ); + }); + }); + + testWidgets('the search filters screen shows the ten commonest facets', ( + tester, + ) async { + Future> sectionIds(Widget screen) async { + await tester.pumpWidget( + MaterialApp(home: SizedBox(width: 400, height: 600, child: screen)), + ); + await tester.pump(); + tester + .widget( + find.byType(PersonalizationSearchResultsTitle), + ) + .onFilters!(); + await tester.pump(); + return tester + .widget(find.byType(PersonalizationFilters)) + .sections + .map((section) => section.id) + .toList(); + } + + final sdk = PersonalizationSdk(api: _FakeHostApi(30)); + expect( + await sectionIds( + PersonalizationSearchResultsScreen(sdk: sdk, query: 'q'), + ), + [for (int i = 30; i >= 21; i--) 'facet:f$i'], + ); + expect( + await sectionIds( + PersonalizationSearchResultsScreen( + key: const ValueKey('all'), + sdk: sdk, + query: 'q', + maxFacets: null, + ), + ), + hasLength(30), + ); + expect( + await sectionIds( + PersonalizationSearchResultsScreen( + key: const ValueKey('host'), + sdk: sdk, + query: 'q', + facets: const {'f2', 'f1'}, + ), + ), + ['facet:f2', 'facet:f1'], + ); + }); +} diff --git a/test/ui/personalization_search_results_screen_test.dart b/test/ui/personalization_search_results_screen_test.dart index a91c43c..37c8ab1 100644 --- a/test/ui/personalization_search_results_screen_test.dart +++ b/test/ui/personalization_search_results_screen_test.dart @@ -5,7 +5,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; -import 'package:rees46_sdk/src/ui/personalization_ui.dart'; /// Host API that answers `searchFull` from memory: [total] products, a page of the /// requested limit at a time. While [hold] is set, answers wait for it. @@ -16,6 +15,12 @@ class _FakeHostApi extends pigeon.PersonalizationHostApi { final List pages = []; Completer? hold; + /// Pages that fail while listed here. + final Set failing = {}; + + /// `search` events tracked. + int searches = 0; + @override Future searchFull( String query, @@ -27,6 +32,7 @@ class _FakeHostApi extends pigeon.PersonalizationHostApi { final limit = params['limit'] as int; pages.add(page); await hold?.future; + if (failing.contains(page)) throw StateError('offline'); final from = (page - 1) * limit; return jsonEncode({ 'products': >[ @@ -42,7 +48,9 @@ class _FakeHostApi extends pigeon.PersonalizationHostApi { String query, List? results, String? shopId, - ) async {} + ) async { + searches++; + } } Widget _host(Widget screen) => MaterialApp( @@ -79,6 +87,8 @@ int _cards() => find .evaluate() .length; +const int _total = _FakeHostApi.total; + void main() { late _FakeHostApi api; late PersonalizationSdk sdk; @@ -179,4 +189,221 @@ void main() { expect(_position(tester).pixels, 0); expect(api.pages, [1, 1]); }); + + testWidgets('cards go without a rating unless asked for', (tester) async { + bool showRating() => tester + .widget(find.byType(PersonalizationCatalog)) + .showRating; + + await tester.pumpWidget( + _host(PersonalizationSearchResultsScreen(sdk: sdk, query: 'jacket')), + ); + await tester.pump(); + expect(showRating(), isFalse); + + await tester.pumpWidget( + _host( + PersonalizationSearchResultsScreen( + sdk: sdk, + query: 'jacket', + showRating: true, + ), + ), + ); + await tester.pump(); + expect(showRating(), isTrue); + }); + + testWidgets('a failed first page shows the error and retries it', ( + tester, + ) async { + final errors = []; + api.failing.add(1); + await tester.pumpWidget( + _host( + PersonalizationSearchResultsScreen( + sdk: sdk, + query: 'jacket', + onError: errors.add, + ), + ), + ); + await tester.pump(); + + const errorText = + 'Something went wrong. Check your connection and try again.'; + expect(find.text(errorText), findsOneWidget); + expect(find.text('No results for your request.'), findsNothing); + expect(find.widgetWithText(PersonalizationButton, 'Retry'), findsOneWidget); + expect(errors, hasLength(1)); + expect(_cards(), 0); + // No "Found 0 products" above the error. + expect(find.text('Found'), findsNothing); + + api.failing.clear(); + await tester.tap(find.text('Retry')); + await tester.pump(); + expect(find.text('Found'), findsOneWidget); + + expect(api.pages, [1, 1]); + expect(find.text(errorText), findsNothing); + expect(find.text('Retry'), findsNothing); + expect(find.text('Item 0'), findsOneWidget); + expect(errors, hasLength(1)); + // A retry asks for the page again, it is not a new search. + expect(api.searches, 1); + }); + + testWidgets('the found count waits for the first page of each request', ( + tester, + ) async { + api.hold = Completer(); + Widget screen(String? sortBy) => _host( + PersonalizationSearchResultsScreen( + sdk: sdk, + query: 'jacket', + sortBy: sortBy, + ), + ); + await tester.pumpWidget(screen(null)); + await tester.pump(); + // Loading: the filter button is there, "Found 0 products" is not. + expect(find.text('Found'), findsNothing); + expect(find.byType(PersonalizationButton), findsWidgets); + + api.hold!.complete(); + api.hold = null; + await tester.pump(); + expect(find.text('Found'), findsOneWidget); + expect(find.text('$_total'), findsOneWidget); + + api.hold = Completer(); + await tester.pumpWidget(screen('price')); + await tester.pump(); + expect(find.text('Found'), findsNothing); + + api.hold!.complete(); + api.hold = null; + await tester.pump(); + expect(find.text('Found'), findsOneWidget); + }); + + testWidgets('a failed next page turns load more into retry', (tester) async { + final errors = []; + await tester.pumpWidget( + _host( + PersonalizationSearchResultsScreen( + sdk: sdk, + query: 'jacket', + errorText: 'Oops', + retryText: 'Again', + onError: errors.add, + ), + ), + ); + await tester.pump(); + PersonalizationCatalog catalog() => tester.widget( + find.byType(PersonalizationCatalog), + ); + expect(catalog().loadMoreText, 'Load more'); + + api.failing.add(2); + catalog().onLoadMore!(); + await tester.pump(); + + expect(api.pages, [1, 2]); + expect(errors, hasLength(1)); + expect(catalog().loadMoreText, 'Again'); + expect(catalog().loading, isFalse); + // The loaded page stays, and the error text is for a failed first page only. + expect(find.text('Item 0'), findsOneWidget); + expect(catalog().emptyText, isNot('Oops')); + expect(find.text('Oops'), findsNothing); + + api.failing.clear(); + catalog().onLoadMore!(); + await tester.pump(); + + expect(api.pages, [1, 2, 2]); + expect(catalog().loadMoreText, 'Load more'); + expect(catalog().count!.shown, 40); + expect(api.searches, 1); + }); + + testWidgets('infinite scroll stops at a failed page until it is retried', ( + tester, + ) async { + await tester.pumpWidget( + _host( + PersonalizationSearchResultsScreen( + sdk: sdk, + query: 'jacket', + infiniteScroll: true, + ), + ), + ); + await tester.pump(); + + api.failing.add(2); + final position = _position(tester); + position.jumpTo(position.maxScrollExtent); + await tester.pump(); + expect(api.pages, [1, 2]); + + position.jumpTo(position.maxScrollExtent - 1); + await tester.pump(); + position.jumpTo(position.maxScrollExtent); + await tester.pump(); + expect(api.pages, [1, 2]); + + final catalog = tester.widget( + find.byType(PersonalizationCatalog), + ); + expect(catalog.loadMoreText, 'Retry'); + api.failing.clear(); + catalog.onLoadMore!(); + await tester.pump(); + expect(api.pages, [1, 2, 2]); + }); + + testWidgets('empty error and retry texts fall back to the defaults', ( + tester, + ) async { + api.failing.add(1); + await tester.pumpWidget( + _host( + PersonalizationSearchResultsScreen( + sdk: sdk, + query: 'jacket', + errorText: null, + retryText: '', + ), + ), + ); + await tester.pump(); + + expect( + find.text(PersonalizationSearchResultsScreen.defaultErrorText), + findsOneWidget, + ); + expect(find.widgetWithText(PersonalizationButton, 'Retry'), findsOneWidget); + + api.failing + ..clear() + ..add(2); + await tester.tap(find.text('Retry')); + await tester.pump(); + final catalog = tester.widget( + find.byType(PersonalizationCatalog), + ); + catalog.onLoadMore!(); + await tester.pump(); + expect(api.pages, [1, 1, 2]); + expect( + tester + .widget(find.byType(PersonalizationCatalog)) + .loadMoreText, + 'Retry', + ); + }); } diff --git a/test/ui/personalization_stories_test.dart b/test/ui/personalization_stories_test.dart index 6752b6e..8d741fc 100644 --- a/test/ui/personalization_stories_test.dart +++ b/test/ui/personalization_stories_test.dart @@ -7,7 +7,6 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; -import 'package:rees46_sdk/src/ui/personalization_ui.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_gif_player.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_image.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; diff --git a/test/ui/personalization_wrap_row_test.dart b/test/ui/personalization_wrap_row_test.dart new file mode 100644 index 0000000..d33f526 --- /dev/null +++ b/test/ui/personalization_wrap_row_test.dart @@ -0,0 +1,240 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/components/personalization_wrap_row.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +const Key _first = ValueKey('first'); +const Key _second = ValueKey('second'); + +/// Two fixed boxes in a row of [width], top-left in a vertical scroll view. +Widget _row({ + required double width, + bool pinEnd = false, + bool withSecond = true, +}) => _host( + width, + PersonalizationWrapRow( + horizontalGap: 8, + verticalGap: 4, + pinEnd: pinEnd, + children: [ + const SizedBox(key: _first, width: 100, height: 40), + if (withSecond) const SizedBox(key: _second, width: 80, height: 20), + ], + ), +); + +Widget _host(double width, Widget child) => MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: width, child: child), + ), + ), + ), +); + +RenderPersonalizationWrapRow _render(WidgetTester tester) => + tester.renderObject( + find.byType(PersonalizationWrapRow).first, + ); + +void main() { + testWidgets( + 'boxes that fit share the line, the pinned one at the right edge', + (tester) async { + await tester.pumpWidget(_row(width: 300, pinEnd: true)); + + expect(_render(tester).isWrapped, isFalse); + expect(tester.getSize(find.byType(PersonalizationWrapRow)).height, 40); + expect(tester.getTopLeft(find.byKey(_second)), const Offset(220, 10)); + }, + ); + + testWidgets( + 'without the pin the second box follows the first after the gap', + (tester) async { + await tester.pumpWidget(_row(width: 300)); + + expect(tester.getTopLeft(find.byKey(_second)).dx, 108); + }, + ); + + testWidgets('boxes that do not fit wrap, the pinned one to the right', ( + tester, + ) async { + await tester.pumpWidget(_row(width: 180, pinEnd: true)); + + expect(_render(tester).isWrapped, isTrue); + expect(tester.getSize(find.byType(PersonalizationWrapRow)).height, 64); + expect(tester.getTopLeft(find.byKey(_second)), const Offset(100, 44)); + }); + + testWidgets('a wrapped box without the pin starts at the left edge', ( + tester, + ) async { + await tester.pumpWidget(_row(width: 150)); + + expect(tester.getTopLeft(find.byKey(_second)), const Offset(0, 44)); + }); + + testWidgets('a single box stays alone on its line', (tester) async { + await tester.pumpWidget(_row(width: 120, pinEnd: true, withSecond: false)); + + expect(_render(tester).isWrapped, isFalse); + expect(tester.getSize(find.byType(PersonalizationWrapRow)).height, 40); + }); + + testWidgets('intrinsic height follows the wrap', (tester) async { + await tester.pumpWidget( + _host( + 180, + const IntrinsicHeight( + child: PersonalizationWrapRow( + horizontalGap: 8, + verticalGap: 4, + children: [ + SizedBox(width: 100, height: 40), + SizedBox(width: 80, height: 20), + ], + ), + ), + ), + ); + + expect(tester.getSize(find.byType(IntrinsicHeight)).height, 64); + }); + + testWidgets('wrapping above puts the second box over the first', ( + tester, + ) async { + await tester.pumpWidget( + _host( + 150, + const PersonalizationWrapRow( + horizontalGap: 8, + verticalGap: 4, + wrapAbove: true, + children: [ + SizedBox(key: _first, width: 100, height: 30), + SizedBox(key: _second, width: 80, height: 20), + ], + ), + ), + ); + + expect(tester.getTopLeft(find.byKey(_second)), const Offset(0, 0)); + expect(tester.getTopLeft(find.byKey(_first)), const Offset(0, 24)); + }); + + testWidgets('bottom alignment lines the boxes up by their bottoms', ( + tester, + ) async { + await tester.pumpWidget( + _host( + 300, + const PersonalizationWrapRow( + horizontalGap: 8, + verticalGap: 4, + alignBottom: true, + children: [ + SizedBox(key: _first, width: 100, height: 30), + SizedBox(key: _second, width: 80, height: 20), + ], + ), + ), + ); + + expect( + tester.getBottomLeft(find.byKey(_second)).dy, + tester.getBottomLeft(find.byKey(_first)).dy, + ); + }); + + group('grid product card', () { + Widget card(double width) => _host( + width, + const PersonalizationProductCard( + type: PersonalizationProductCardType.grid, + brand: 'Bang & Olufsen', + name: 'Телевизор Bang & Olufsen 40" BeoVision Horizon', + price: '799 990 ₽', + oldPrice: '1 574 990 ₽', + discount: '-49%', + actionText: 'Add to cart', + ), + ); + + testWidgets('long prices put the old price above the price, unbroken', ( + tester, + ) async { + await tester.pumpWidget(card(240)); + + expect(tester.takeException(), isNull); + expect( + tester.getBottomLeft(find.text('1 574 990 ₽')).dy, + lessThanOrEqualTo(tester.getTopLeft(find.text('799 990 ₽')).dy), + ); + expect(tester.widget(find.text('1 574 990 ₽')).maxLines, 1); + }); + + testWidgets('prices that fit stay on one line', (tester) async { + await tester.pumpWidget(card(600)); + + expect( + tester.getTopLeft(find.text('1 574 990 ₽')).dy, + greaterThan(tester.getTopLeft(find.text('799 990 ₽')).dy - 1), + ); + expect( + tester.getTopLeft(find.text('1 574 990 ₽')).dx, + greaterThan(tester.getTopRight(find.text('799 990 ₽')).dx), + ); + }); + }); + + group('list product card', () { + Widget card(double width) => _host( + width, + const PersonalizationProductCard( + type: PersonalizationProductCardType.list, + brand: 'HP', + name: 'Мышка игровая проводная HP OMEN 600', + price: '7 990 ₽', + oldPrice: '9 990 ₽', + discount: '-20%', + actionText: 'Add to cart', + ), + ); + + RenderPersonalizationWrapRow bottomRow(WidgetTester tester) => + tester.renderObject( + find.byType(PersonalizationWrapRow).first, + ); + + testWidgets('a wide card keeps the price and the button on one line', ( + tester, + ) async { + await tester.pumpWidget(card(600)); + + expect(tester.takeException(), isNull); + expect(bottomRow(tester).isWrapped, isFalse); + }); + + testWidgets( + 'a narrow card moves the button under the price, nothing overflows', + (tester) async { + await tester.pumpWidget(card(330)); + + expect(tester.takeException(), isNull); + expect(bottomRow(tester).isWrapped, isTrue); + expect( + tester.getTopLeft(find.text('Add to cart')).dy, + greaterThan(tester.getBottomLeft(find.text('9 990 ₽')).dy), + ); + final Text badge = tester.widget(find.text('-20%')); + expect(badge.maxLines, 1); + }, + ); + }); +} diff --git a/test/ui/product_mapping_test.dart b/test/ui/product_mapping_test.dart new file mode 100644 index 0000000..79f51ed --- /dev/null +++ b/test/ui/product_mapping_test.dart @@ -0,0 +1,235 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/ui/widgets/product_mapping.dart'; + +Map _fixture(String name) => + jsonDecode(File('test/fixtures/$name.json').readAsStringSync()) + as Map; + +SearchProduct _search(Map json) => SearchProduct.fromJson( + {'id': '1', 'name': 'Item', ...json}, +); + +String? _imageUrl(ImageProvider? image) => (image as NetworkImage?)?.url; + +void main() { + tearDown(() => debugDefaultTargetPlatformOverride = null); + + group('price', () { + test('the formatted price, else price and currency', () { + expect( + productFromSearch( + _search({'price': 10, 'price_formatted': r'$10'}), + ).price, + r'$10', + ); + expect( + productFromSearch( + _search({'price': 10, 'currency': 'USD'}), + ).price, + '10.0 USD', + ); + }); + }); + + group('old price and discount', () { + test('an old price above the price, with the formatted discount', () { + final card = productFromSearch( + _search({ + 'price': 90, + 'oldprice': 100, + 'oldprice_formatted': '100 ₽', + 'discount': 10, + 'discount_formatted': '10%', + }), + ); + expect(card.oldPrice, '100 ₽'); + expect(card.discount, '-10%'); + }); + + test('without a formatted discount the number goes with a percent', () { + final card = productFromSearch( + _search({ + 'price': 90, + 'oldprice': 100, + 'oldprice_formatted': '100 ₽', + 'discount': 10, + }), + ); + expect(card.discount, '-10%'); + }); + + test('a discount that already has its sign keeps exactly one', () { + PersonalizationProduct card(String formatted) => productFromSearch( + _search({ + 'price': 90, + 'oldprice': 100, + 'oldprice_formatted': '100 ₽', + 'discount': 10, + 'discount_formatted': formatted, + }), + ); + expect(card('-10%').discount, '-10%'); + expect(card('--10%').discount, '-10%'); + }); + + // Old price shown, the discount itself decides the badge. + Map discounted(Map discount) => + { + 'price': 90, + 'oldprice': 100, + 'oldprice_formatted': '100 ₽', + ...discount, + }; + + test('a zero discount shows no badge, even formatted', () { + final card = productFromSearch( + _search( + discounted({ + 'discount': 0, + 'discount_formatted': '0%', + }), + ), + ); + expect(card.oldPrice, '100 ₽'); + expect(card.discount, isNull); + }); + + test('a discount of true or garbage is no discount', () { + for (final value in [true, false, 'abc']) { + final card = productFromSearch( + _search(discounted({'discount': value})), + ); + expect(card.discount, isNull, reason: '$value'); + } + }); + + test('discount_percent stands in for a missing discount', () { + final card = productFromSearch( + _search(discounted({'discount_percent': '5'})), + ); + expect(card.discount, '-5%'); + }); + + test('a discount_percent badge ignores discount_formatted of a zero ' + 'discount', () { + final card = productFromSearch( + _search( + discounted({ + 'discount': 0, + 'discount_formatted': '0%', + 'discount_percent': 5, + }), + ), + ); + expect(card.discount, '-5%'); + }); + + test('a number in a string counts', () { + final card = productFromCatalog( + Product.fromJson({ + 'id': '1', + 'name': 'Item', + ...discounted({'discount': '7'}), + }), + ); + expect(card.discount, '-7%'); + }); + + test('no old price at or below the price, and then no discount', () { + final card = productFromSearch( + _search({ + 'price': 100, + 'oldprice': 100, + 'oldprice_formatted': '100 ₽', + 'discount_formatted': '10%', + }), + ); + expect(card.oldPrice, isNull); + expect(card.discount, isNull); + }); + }); + + group('picture, brand, links', () { + test('the resized picture, else the original, else none', () { + expect( + _imageUrl( + productFromSearch( + _search({'picture': 'p', 'image_url': 'i'}), + ).image, + ), + 'p', + ); + expect( + _imageUrl( + productFromSearch(_search({'image_url': 'i'})).image, + ), + 'i', + ); + expect(productFromSearch(_search({})).image, isNull); + }); + + test('an empty brand and url read as none', () { + final card = productFromSearch(_search({})); + expect(card.brand, isNull); + expect(card.url, isNull); + expect(card.rating, isNull); + }); + + test('the deeplink of the running platform', () { + final product = _search({ + 'url': 'https://shop/p/1', + 'deeplink_android': 'android://p/1', + 'deeplink_ios': 'ios://p/1', + }); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + expect(productFromSearch(product).deeplink, 'android://p/1'); + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + expect(productFromSearch(product).deeplink, 'ios://p/1'); + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + expect(productFromSearch(product).deeplink, isNull); + expect(productFromSearch(product).url, 'https://shop/p/1'); + }); + }); + + group('every product model maps the same way', () { + test('a discounted recommendation', () { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + final product = RecommendationResponse.fromJson( + _fixture('recommend_extended'), + ).products.first; + final card = productFromRecommendation(product, actionText: 'Buy'); + expect(card.id, '52173'); + expect(card.brand, 'Beko'); + expect(card.price, '164 990 ₽'); + expect(card.oldPrice, '174 990 ₽'); + expect(card.discount, '-6%'); + expect(_imageUrl(card.image), contains('/resize-images/180/')); + expect( + card.deeplink, + 'https://www.technodom.kz/p/holodilnik-beko-rdsk-mw-52173', + ); + expect(card.url, startsWith('https://www.technodom.kz/p/holodilnik')); + expect(card.actionText, 'Buy'); + }); + + test('catalog products, with and without a discount', () { + final products = ProductsListResponse.fromJson( + _fixture('products'), + ).products; + final plain = productFromCatalog(products[0]); + final discounted = productFromCatalog(products[1]); + expect(plain.price, '15 990 ₽'); + expect(plain.oldPrice, isNull); + expect(plain.discount, isNull); + expect(discounted.oldPrice, '174 990 ₽'); + expect(discounted.discount, '-6%'); + expect(_imageUrl(discounted.image), contains('/resize-images/180/')); + }); + }); +} diff --git a/test/ui/stories_poll_test.dart b/test/ui/stories_poll_test.dart new file mode 100644 index 0000000..5479f42 --- /dev/null +++ b/test/ui/stories_poll_test.dart @@ -0,0 +1,920 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/stories/stories_response.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_playback.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_poll.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_polls_api.dart'; + +/// A transport answering by hand: each request waits in [pending]. +class _Transport implements StoryPollsTransport { + final List<(String, Object, Map)> calls = + <(String, Object, Map)>[]; + final List> pending = >[]; + + Future _wait() { + final completer = Completer(); + pending.add(completer); + return completer.future; + } + + @override + Future answerMiniPoll(String code, Map body) { + calls.add(('answerMiniPoll', code, body)); + return _wait(); + } + + @override + Future review(StoryPollType kind, Map body) { + calls.add(('review', kind, body)); + return _wait(); + } +} + +/// A mini poll like the web fixtures: «Кому выбираете подарок?» with three options. +StoryPollElement _mini( + StoryMiniPollKind kind, { + bool allowReanswer = false, + StoryPollAnswer? answer, + StoryPollResults? results, + String submitLabel = 'Отправить', + StoryPollLabels labels = const StoryPollLabels(), + String code = 'gift_recipient', +}) => StoryPollElement( + pollType: StoryPollType.miniPoll, + kind: kind, + code: code, + yOffset: 40, + allowReanswer: allowReanswer, + question: 'Кому выбираете подарок?', + placeholder: kind == StoryMiniPollKind.text ? 'Название или автор' : '', + maxLength: kind == StoryMiniPollKind.text ? 10 : null, + submitLabel: submitLabel, + thanksText: 'Спасибо!', + showResults: true, + options: const [ + StoryPollOption(id: 1, label: 'Себе'), + StoryPollOption(id: 2, label: 'Маме'), + StoryPollOption(id: 3, label: 'Папе'), + ], + answer: answer, + results: results, + labels: labels, +); + +StoryPollElement _scale( + StoryPollType type, { + bool allowReanswer = false, + StoryPollAnswer? answer, + String channel = 'stories', + List? bands, + int? rateMin, + int? rateMax, +}) => StoryPollElement( + pollType: type, + code: 'delivery', + yOffset: 50, + allowReanswer: allowReanswer, + channel: channel, + question: 'Как вам доставка?', + rateMin: rateMin, + rateMax: rateMax, + bands: + bands ?? + const [ + StoryPollBand(from: 0, to: 6, success: 'Спасибо, мы станем лучше'), + StoryPollBand(from: 7, to: 8, success: 'Спасибо!'), + StoryPollBand(from: 9, to: 10, success: 'Спасибо, рады стараться!'), + ], + answer: answer, +); + +const StoryPollAnswer _answered = StoryPollAnswer(optionIds: [2]); +const StoryPollResults _results = StoryPollResults( + total: 120, + options: <({int id, double percent})>[ + (id: 1, percent: 40), + (id: 2, percent: 60), + ], +); + +void main() { + late _Transport transport; + late List holds; + + setUp(() { + StoryPollStore.instance = StoryPollStore(); + transport = _Transport(); + holds = []; + }); + + StoryPollController mount( + StoryPollElement poll, { + StoryPollTexts texts = const StoryPollTexts(), + String shopId = 'shop', + }) => StoryPollController( + poll: poll, + storyId: '5', + slideId: '101', + transport: transport, + shopId: shopId, + texts: texts, + onHold: holds.add, + ); + + Future reply( + int index, [ + StoryPollReply value = const StoryPollReply(), + ]) async { + transport.pending[index].complete(value); + await pumpEventQueue(); + } + + Future fail(int index) async { + transport.pending[index].completeError(Exception('Too many requests')); + await pumpEventQueue(); + } + + group('single choice', () { + test('sends on tap, then thanks and results', () async { + final poll = mount(_mini(StoryMiniPollKind.singleChoice)); + expect(poll.answered, isFalse); + poll.choose(2); + expect(transport.calls.single.$1, 'answerMiniPoll'); + expect(transport.calls.single.$2, 'gift_recipient'); + expect(transport.calls.single.$3, { + 'option_ids': [2], + 'story_id': 5, + 'slide_id': '101', + }); + expect(poll.sending, isTrue); + expect(poll.selected, {2}); + await reply( + 0, + const StoryPollReply( + answer: StoryPollAnswer(id: 77, optionIds: [2]), + results: StoryPollResults( + total: 121, + options: <({int id, double percent})>[ + (id: 1, percent: 40), + (id: 2, percent: 60), + ], + ), + ), + ); + expect(poll.answered, isTrue); + expect(poll.sending, isFalse); + expect(poll.answer!.optionIds, [2]); + expect( + [ + for (final id in [1, 2, 3]) poll.results!.percentOf(id), + ], + [40, 60, 0], + ); + }); + + test('does not send twice while the request is pending', () { + final poll = mount(_mini(StoryMiniPollKind.singleChoice)); + poll + ..choose(1) + ..choose(1) + ..choose(3); + expect(transport.calls, hasLength(1)); + }); + + test('an error rolls the choice back and allows a retry', () async { + final poll = mount(_mini(StoryMiniPollKind.singleChoice)); + poll.choose(1); + await fail(0); + expect(poll.failed, isTrue); + expect(poll.sending, isFalse); + expect(poll.selected, isEmpty); + poll.choose(1); + expect(transport.calls, hasLength(2)); + expect(poll.failed, isFalse); + await reply( + 1, + const StoryPollReply(answer: StoryPollAnswer(optionIds: [1])), + ); + expect(poll.answered, isTrue); + expect(poll.results, isNull, reason: 'no percent without results'); + }); + + test('the sent answer when the server returns none', () async { + final poll = mount(_mini(StoryMiniPollKind.singleChoice)); + poll.choose(3); + await reply(0); + expect(poll.answer!.optionIds, [3]); + }); + + test('an answer of the reply without ids is still the answer', () async { + final poll = mount(_mini(StoryMiniPollKind.singleChoice))..choose(2); + await reply(0, const StoryPollReply(answer: StoryPollAnswer(id: 77))); + expect(poll.answered, isTrue, reason: 'answered after any success'); + expect(poll.answer!.id, 77); + expect(poll.answer!.optionIds, isNull, reason: 'not the sent one'); + }); + + test( + 'no code: the card works, the answer goes with an empty one', + () async { + final poll = mount(_mini(StoryMiniPollKind.singleChoice, code: '')); + poll.choose(2); + expect(transport.calls.single.$2, ''); + await fail(0); + expect(poll.failed, isTrue, reason: 'the server rejects it'); + poll.choose(2); + await reply(1); + expect( + mount(_mini(StoryMiniPollKind.singleChoice, code: '')).answered, + isTrue, + reason: 'stored under the empty code', + ); + }, + ); + + test('the card does not log a failed send: the transport does', () async { + final logs = []; + final print = debugPrint; + debugPrint = (message, {wrapWidth}) => logs.add(message ?? ''); + addTearDown(() => debugPrint = print); + final poll = mount(_mini(StoryMiniPollKind.singleChoice))..choose(1); + transport.pending.single.completeError( + StoriesV3Exception('HTTP 429: Too many requests', status: 429), + ); + await pumpEventQueue(); + expect(poll.failed, isTrue); + expect(logs, isEmpty); + }); + }); + + group('multiple choice', () { + test( + 'chips do not send; the button sends in the order of the options', + () async { + final poll = mount(_mini(StoryMiniPollKind.multipleChoice)); + expect(poll.canSubmit, isFalse); + poll + ..toggle(3) + ..toggle(1); + expect(poll.selected, {1, 3}); + expect(poll.canSubmit, isTrue); + expect(transport.calls, isEmpty, reason: 'chips do not send'); + poll + ..toggle(3) + ..toggle(3) + ..submitChoices(); + expect(transport.calls.single.$3, { + 'option_ids': [1, 3], + 'story_id': 5, + 'slide_id': '101', + }); + await reply( + 0, + const StoryPollReply(answer: StoryPollAnswer(optionIds: [1, 3])), + ); + expect(poll.answered, isTrue); + expect(poll.answer!.optionIds, [1, 3]); + }, + ); + + test('the button is off again when every chip is off', () { + final poll = mount(_mini(StoryMiniPollKind.multipleChoice)) + ..toggle(1) + ..toggle(1) + ..submitChoices(); + expect(poll.canSubmit, isFalse); + expect(transport.calls, isEmpty); + }); + }); + + group('text', () { + test('sends the trimmed text; blank does not send', () async { + final poll = mount(_mini(StoryMiniPollKind.text)); + expect(poll.showsField, isTrue); + poll.text = ' '; + expect(poll.canSubmit, isFalse); + poll.submitText(); + expect(transport.calls, isEmpty); + poll + ..text = ' Мастер и ' + ..submitText(); + expect(transport.calls.single.$3, { + 'text': 'Мастер и', + 'story_id': 5, + 'slide_id': '101', + }); + expect(poll.canSubmit, isFalse, reason: 'off while sending'); + await reply( + 0, + const StoryPollReply(answer: StoryPollAnswer(id: 1, text: 'Мастер и')), + ); + expect(poll.answered, isTrue); + expect(poll.showsField, isFalse); + expect(poll.answer!.text, 'Мастер и'); + }); + }); + + group('scales', () { + test('NPS 0..10 sends the rate on tap with its category', () async { + final poll = mount(_scale(StoryPollType.nps)); + expect(storyPollScaleRange(poll.poll), [ + for (var i = 0; i <= 10; i++) i, + ]); + poll.rate(9); + expect(transport.calls.single.$1, 'review'); + expect(transport.calls.single.$2, StoryPollType.nps); + expect(transport.calls.single.$3, { + 'channel': 'stories', + 'category': 'delivery', + 'rate': 9, + }); + await reply(0); + expect(poll.answered, isTrue); + expect(poll.rateValue, 9); + expect( + storyPollBandText(poll.poll, poll.answer!.rate), + 'Спасибо, рады стараться!', + ); + }); + + test( + 'CSAT 1..5 and CES 1..7 with campaign; no channel — stories', + () async { + final csat = mount( + _scale( + StoryPollType.csat, + bands: const [ + StoryPollBand(from: 1, to: 3, success: 'Жаль'), + StoryPollBand(from: 4, to: 5, success: 'Ура'), + ], + ), + ); + expect(storyPollScaleRange(csat.poll), [1, 2, 3, 4, 5]); + csat.rate(1); + expect(transport.calls.single.$3, { + 'channel': 'stories', + 'campaign': 'delivery', + 'rate': 1, + }); + await reply(0); + expect(storyPollBandText(csat.poll, csat.answer!.rate), 'Жаль'); + + final ces = mount(_scale(StoryPollType.ces, channel: '')); + expect(storyPollScaleRange(ces.poll), [1, 2, 3, 4, 5, 6, 7]); + ces.rate(7); + expect(transport.calls.last.$3, { + 'channel': 'stories', + 'campaign': 'delivery', + 'rate': 7, + }); + }, + ); + + test('ranges: defaults, own bounds, no more than 21 values', () { + expect(storyPollScaleRange(_scale(StoryPollType.csat)), [ + 1, + 2, + 3, + 4, + 5, + ]); + expect(storyPollScaleRange(_scale(StoryPollType.nps)), hasLength(11)); + expect( + storyPollScaleRange(_scale(StoryPollType.ces, rateMin: 2, rateMax: 4)), + [2, 3, 4], + ); + final long = storyPollScaleRange( + _scale(StoryPollType.nps, rateMin: 0, rateMax: 100), + ); + expect(long, hasLength(21)); + expect(long.last, 20); + expect( + storyPollScaleRange(_scale(StoryPollType.nps, rateMin: 5, rateMax: 1)), + isEmpty, + ); + }); + + test('a fractional rate: answered, no cell lit, its own band', () { + final poll = mount( + _scale(StoryPollType.nps, answer: const StoryPollAnswer(rate: 9.5)), + ); + expect(poll.answered, isTrue); + expect(storyPollScaleRange(poll.poll).contains(poll.rateValue), isFalse); + expect(storyPollBandText(poll.poll, 9.5), 'Спасибо, рады стараться!'); + expect( + storyPollBandText(poll.poll, 6.5), + isNull, + reason: 'between bands', + ); + }); + + test('blank texts of the host and labels override; trim only for text', () { + final texts = const StoryPollTexts(reanswer: ' ', error: ' ').forPoll( + _mini( + StoryMiniPollKind.text, + labels: const StoryPollLabels(submit: ' '), + ), + ); + expect((texts.reanswer, texts.error, texts.submit), (' ', ' ', ' ')); + final poll = mount(_mini(StoryMiniPollKind.text))..text = ' '; + expect(poll.canSubmit, isFalse); + }); + + test('bands: inclusive bounds, a miss is null', () { + final poll = _scale( + StoryPollType.nps, + bands: const [ + StoryPollBand(from: 0, to: 6, success: 'A'), + ], + ); + expect(storyPollBandText(poll, 0), 'A'); + expect(storyPollBandText(poll, 6), 'A'); + expect(storyPollBandText(poll, 7), isNull); + expect(storyPollBandText(poll, null), isNull); + }); + + test('colours: NPS by groups, the rest by thirds', () { + Color nps(int value) => + storyPollScaleColor(StoryPollType.nps, value, 0, 10); + expect( + [for (var i = 0; i <= 10; i++) nps(i)], + const [ + Color(0xFFFCA5A5), Color(0xFFFCA5A5), Color(0xFFFCA5A5), // + Color(0xFFFDBA74), Color(0xFFFDBA74), Color(0xFFFDBA74), // + Color(0xFFFCD34D), Color(0xFFFDE68A), Color(0xFFFDE68A), // + Color(0xFF86EFAC), Color(0xFF86EFAC), + ], + ); + Color csat(int value) => + storyPollScaleColor(StoryPollType.csat, value, 1, 5); + expect( + [for (var i = 1; i <= 5; i++) csat(i)], + const [ + Color(0xFFFCA5A5), Color(0xFFFCA5A5), Color(0xFFFDE68A), // + Color(0xFF86EFAC), Color(0xFF86EFAC), + ], + ); + expect( + storyPollScaleColor(StoryPollType.nps, 3, 1, 5), + const Color(0xFFFDE68A), + reason: 'NPS on its own range — by thirds', + ); + expect( + storyPollScaleColor(StoryPollType.ces, 4, 4, 4), + const Color(0xFF86EFAC), + ); + }); + + test('a scale keeps only its rate, whatever the reply has', () async { + final poll = mount(_scale(StoryPollType.csat))..rate(4); + await reply( + 0, + const StoryPollReply( + answer: StoryPollAnswer(rate: 1, optionIds: [1]), + results: _results, + ), + ); + expect(poll.answer!.rate, 4); + expect(poll.answer!.optionIds, isNull); + expect(poll.results, isNull); + }); + + test('ranges of parsed bounds: not whole — the defaults', () { + List range(Object? min, Object? max) => storyPollScaleRange( + StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'ces', + 'poll': { + 'code': 'x', + 'rate_min': min, + 'rate_max': max, + }, + })!, + ); + expect(range(1.5, 3.5), [1, 2, 3, 4, 5, 6, 7]); + expect(range('2', '4'), [2, 3, 4]); + expect(range(9, null), isEmpty, reason: 'min over the default max'); + }); + + test('an answered scale from the feed does not send', () { + final poll = mount( + _scale(StoryPollType.nps, answer: const StoryPollAnswer(rate: 3)), + ); + expect(poll.answered, isTrue); + expect(poll.rateValue, 3); + expect(storyPollBandText(poll.poll, 3), 'Спасибо, мы станем лучше'); + poll.rate(5); + expect(transport.calls, isEmpty); + }); + }); + + group('an answer from the feed', () { + test('answered, no re-answer without allow_reanswer', () { + final poll = mount( + _mini( + StoryMiniPollKind.singleChoice, + answer: _answered, + results: _results, + ), + ); + expect(poll.answered, isTrue); + expect(poll.results!.percentOf(1), 40); + poll + ..reanswer() + ..choose(1); + expect(poll.answered, isTrue); + expect(transport.calls, isEmpty); + }); + + test( + 're-answer: the form with the previous choice, then answered again', + () async { + final poll = mount( + _mini( + StoryMiniPollKind.singleChoice, + allowReanswer: true, + answer: _answered, + results: _results, + ), + ); + poll.reanswer(); + expect(poll.answered, isFalse); + expect(poll.selected, { + 2, + }, reason: 'previous answer is highlighted'); + poll.choose(1); + expect(poll.selected, {1}, reason: 'only the new option'); + await reply( + 0, + const StoryPollReply(answer: StoryPollAnswer(optionIds: [1])), + ); + expect(poll.answered, isTrue); + }, + ); + + test('a failed re-answer restores the previous choice', () async { + final poll = mount( + _mini( + StoryMiniPollKind.singleChoice, + allowReanswer: true, + answer: _answered, + ), + )..reanswer(); + poll.choose(3); + await fail(0); + expect(poll.selected, {2}); + }); + + test('multiple choice starts from the previous options', () { + final poll = mount( + _mini( + StoryMiniPollKind.multipleChoice, + allowReanswer: true, + answer: const StoryPollAnswer(optionIds: [1, 3]), + ), + )..reanswer(); + expect(poll.selected, {1, 3}); + expect(poll.canSubmit, isTrue); + poll + ..toggle(1) + ..submitChoices(); + expect(transport.calls.single.$3['option_ids'], [3]); + }); + + test( + 'a scale keeps the previous rate lit until a new one is sent', + () async { + final poll = mount( + _scale( + StoryPollType.nps, + allowReanswer: true, + answer: const StoryPollAnswer(rate: 3), + ), + )..reanswer(); + expect(poll.answered, isFalse); + expect(poll.rateValue, 3); + poll.rate(8); + expect(poll.rateValue, 8); + await fail(0); + expect(poll.rateValue, 3, reason: 'restored after an error'); + }, + ); + + test('a re-answer: the reply results replace those of the feed', () async { + final poll = mount( + _mini( + StoryMiniPollKind.singleChoice, + allowReanswer: true, + answer: _answered, + results: _results, + ), + )..reanswer(); + poll.choose(1); + await reply( + 0, + const StoryPollReply(answer: StoryPollAnswer(optionIds: [1])), + ); + expect(poll.answer!.optionIds, [1]); + expect(poll.results, isNull, reason: 'no results in the reply'); + }); + + test('text: an empty field again', () { + final poll = mount( + _mini( + StoryMiniPollKind.text, + allowReanswer: true, + answer: const StoryPollAnswer(text: 'Букварь'), + ), + ); + expect(poll.answer!.text, 'Букварь'); + poll.reanswer(); + expect(poll.showsField, isTrue); + expect(poll.text, isEmpty); + }); + }); + + group('texts', () { + test('labels of the element > texts of the host > defaults', () { + const host = StoryPollTexts( + reanswer: 'Answer again', + error: 'Ошибка', + submit: '', + ); + final texts = host.forPoll( + _mini( + StoryMiniPollKind.singleChoice, + labels: const StoryPollLabels(reanswer: 'Ещё раз'), + ), + ); + expect(texts.reanswer, 'Ещё раз'); + expect(texts.error, 'Ошибка'); + expect(texts.submit, 'Send', reason: 'an empty host text — the default'); + final defaults = const StoryPollTexts().forPoll( + _scale(StoryPollType.nps), + ); + expect(defaults.reanswer, 'Answer again'); + expect(defaults.error, 'Failed to send the answer. Please try again'); + expect(defaults.submit, 'Send'); + expect( + mount(_mini(StoryMiniPollKind.text), texts: host).texts.error, + 'Ошибка', + ); + }); + + test('labels: submit too; null or not an object — the host texts', () { + StoryPollTexts parse(Object? labels) => + const StoryPollTexts( + reanswer: 'Again', + error: 'Oops', + submit: 'Go', + ).forPoll( + StoryPollElement.tryParse({ + 'type': 'poll', + 'poll_type': 'mini_poll', + 'labels': labels, + 'poll': {'code': 'x', 'kind': 'multiple_choice'}, + })!, + ); + final labelled = parse({ + 'reanswer': 'Ответить заново', + 'error': '', + 'submit': 'Отправить', + }); + expect( + (labelled.reanswer, labelled.error, labelled.submit), + ('Ответить заново', 'Oops', 'Отправить'), + ); + for (final labels in [null, 'x', []]) { + final texts = parse(labels); + expect( + (texts.reanswer, texts.error, texts.submit), + ('Again', 'Oops', 'Go'), + ); + } + }); + + test('results texts by the language: ru for ru, English for the rest', () { + expect(StoryPollResultTexts.of('ru'), StoryPollResultTexts.ru); + for (final language in ['en', 'de', 'uk', '']) { + expect(StoryPollResultTexts.of(language), StoryPollResultTexts.en); + } + const ru = StoryPollResultTexts.ru; + const en = StoryPollResultTexts.en; + expect( + (ru.results, ru.thanks, ru.counted), + ('Результаты', 'Спасибо!', 'Голос учтён'), + ); + expect( + (en.results, en.thanks, en.counted), + ('Results', 'Thank you!', 'Vote counted'), + ); + }); + + test('votes: Russian plural forms, English vote/votes, digit groups', () { + const ru = { + 1: '1 голос', + 2: '2 голоса', + 4: '4 голоса', + 5: '5 голосов', + 11: '11 голосов', + 12: '12 голосов', + 14: '14 голосов', + 21: '21 голос', + 22: '22 голоса', + 25: '25 голосов', + 101: '101 голос', + 111: '111 голосов', + 112: '112 голосов', + 122: '122 голоса', + 1000: '1 000 голосов', + 1248: '1 248 голосов', + 1000001: '1 000 001 голос', + }; + ru.forEach( + (count, text) => expect( + StoryPollResultTexts.ru.votes(count), + text, + reason: '$count', + ), + ); + const en = { + 1: '1 vote', + 2: '2 votes', + 11: '11 votes', + 21: '21 votes', + 999: '999 votes', + 1248: '1,248 votes', + 1234567: '1,234,567 votes', + }; + en.forEach( + (count, text) => expect( + StoryPollResultTexts.en.votes(count), + text, + reason: '$count', + ), + ); + }); + }); + + group('session store', () { + test('a stored answer is answered even if it lights nothing', () { + StoryPollStore.instance.write( + 'shop', + _mini(StoryMiniPollKind.singleChoice), + (answer: const StoryPollAnswer(id: 77), results: null), + ); + final poll = mount(_mini(StoryMiniPollKind.singleChoice)); + expect(poll.answered, isTrue); + expect(poll.answer!.optionIds, isNull); + expect( + mount( + _mini(StoryMiniPollKind.singleChoice, answer: StoryPollAnswer(id: 1)), + shopId: 'other', + ).answered, + isFalse, + reason: 'such an answer of the feed is no answer', + ); + }); + + test( + 'a sent answer is remembered by shop, kind and code over the feed', + () async { + mount(_mini(StoryMiniPollKind.singleChoice)).choose(2); + await reply(0, const StoryPollReply(results: _results)); + final again = mount(_mini(StoryMiniPollKind.singleChoice)); + expect(again.answered, isTrue); + expect(again.answer!.optionIds, [2]); + expect(again.results!.percentOf(2), 60); + expect( + mount( + _mini(StoryMiniPollKind.singleChoice), + shopId: 'other', + ).answered, + isFalse, + ); + expect( + mount(_mini(StoryMiniPollKind.singleChoice, code: 'other')).answered, + isFalse, + ); + // A re-answer replaces it, also over the answer of the feed. + final feed = mount( + _mini( + StoryMiniPollKind.singleChoice, + allowReanswer: true, + answer: _answered, + ), + ); + expect(feed.answer!.optionIds, [2]); + }, + ); + + test( + 'a reply after the card is gone: only the store, no hold change', + () async { + final poll = mount(_mini(StoryMiniPollKind.singleChoice)); + var notified = 0; + poll + ..addListener(() => notified++) + ..choose(1); + expect(holds, [true]); + poll.dispose(); + expect(holds, [true, false], reason: 'a gone card does not hold'); + notified = 0; + await reply(0); + expect(notified, 0); + expect(holds, [true, false]); + expect(mount(_mini(StoryMiniPollKind.singleChoice)).answered, isTrue); + }, + ); + }); + + group('hold', () { + test('while pressed', () { + final poll = mount(_mini(StoryMiniPollKind.multipleChoice)) + ..pressed = true; + poll.pressed = true; + expect(holds, [true]); + poll.pressed = false; + expect(holds, [true, false]); + }); + + test('while the field is focused, pressing does not resume', () { + final poll = mount(_mini(StoryMiniPollKind.text))..focused = true; + expect(holds, [true]); + poll + ..text = 'a' + ..pressed = true + ..pressed = false; + expect(holds, [true], reason: 'still focused'); + poll.focused = false; + expect(holds, [true, false]); + }); + + test('while sending, then resumes', () async { + final poll = mount(_scale(StoryPollType.nps))..rate(10); + expect(holds, [true]); + await reply(0); + expect(holds, [true, false]); + expect(poll.holding, isFalse); + }); + + test('a sent text resumes: the field is gone with its focus', () async { + final poll = mount(_mini(StoryMiniPollKind.text)) + ..focused = true + ..text = 'Книга' + ..submitText(); + expect(holds, [true]); + await reply(0); + expect(poll.showsField, isFalse); + expect(holds, [true, false]); + }); + + test('a failed send lets go when the focus left while sending', () async { + final poll = mount(_mini(StoryMiniPollKind.text)) + ..focused = true + ..text = 'Книга' + ..submitText() + ..focused = false; + expect(holds, [true], reason: 'still sending'); + await fail(0); + expect(poll.showsField, isTrue); + expect(holds, [true, false]); + }); + + test('only on a live slide', () { + final poll = StoryPollController( + poll: _mini(StoryMiniPollKind.singleChoice), + storyId: '5', + slideId: '101', + transport: transport, + onHold: holds.add, + active: false, + )..pressed = true; + expect(holds, isEmpty); + poll.active = true; + expect(holds, [true]); + poll.active = false; + expect(holds, [true, false]); + }); + }); + + test('the poll pause goes away with the slide', () { + final slides = [ + for (final id in ['1', '2']) + StorySlide(id: id, type: StorySlideType.image), + ]; + final playback = StoriesPlayback( + stories: [Story(id: 's', name: 's', avatar: '', slides: slides)], + )..settle(0); + playback + ..mediaReady(playback.generation) + ..pause(StoriesPauseReason.poll); + expect(playback.running, isFalse); + expect(playback.next(), StoriesStep.slide); + expect(playback.pausedBy(StoriesPauseReason.poll), isFalse); + }); +} diff --git a/test/ui/stories_poll_widget_test.dart b/test/ui/stories_poll_widget_test.dart new file mode 100644 index 0000000..5f12b8e --- /dev/null +++ b/test/ui/stories_poll_widget_test.dart @@ -0,0 +1,1269 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/ui/components/personalization_story_poll.dart'; +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_poll.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; + +/// A transport answering by hand: each request waits in [pending]. +class _Transport implements StoryPollsTransport { + final List> bodies = >[]; + final List> pending = >[]; + + Future _wait(Map body) { + bodies.add(body); + final completer = Completer(); + pending.add(completer); + return completer.future; + } + + @override + Future answerMiniPoll( + String code, + Map body, + ) => _wait(body); + + @override + Future review(StoryPollType kind, Map body) => + _wait(body); +} + +const List> _options = >[ + {'id': 1, 'label': 'Себе'}, + {'id': 2, 'label': 'Маме'}, + {'id': 3, 'label': 'Папе'}, +]; + +Map _poll( + String type, { + String? kind, + Object? yOffset = 50, + bool allowReanswer = false, + Map? answer, + Map? results, + Map? labels, + int? maxLength, + Map fields = const {}, +}) => { + 'type': 'poll', + 'poll_type': type, + 'y_offset': yOffset, + 'allow_reanswer': allowReanswer, + 'labels': labels, + 'poll': { + 'code': 'code_$type${kind ?? ''}', + 'kind': kind, + 'question': 'Q $type ${kind ?? ''}'.trim(), + 'max_length': maxLength, + 'thanks_text': 'Спасибо!', + 'show_results': true, + 'options': _options, + 'bands': >[ + {'from': 0, 'to': 10, 'success': 'Band thanks'}, + ], + ...fields, + }, + 'answer': answer, + 'results': results, +}; + +/// A slide without media (it runs at once) with a text block naming it. +Map _slide( + String id, [ + List> elements = const >[], +]) => { + 'id': id, + 'type': 'image', + 'background': '', + 'duration': 1, + 'elements': >[ + { + 'type': 'text_block', + 'text_input': 'Slide $id', + 'y_offset': 20, + }, + ...elements, + ], +}; + +List _stories(List>> stories) => + StoriesBlock.fromJson({ + 'id': 1, + 'stories': >[ + for (final (index, slides) in stories.indexed) + { + 'id': index + 1, + 'name': 'Story ${index + 1}', + 'avatar': '', + 'slides': slides, + }, + ], + }).stories; + +Widget _icon(BuildContext context, String asset, double size, Color color) => + SizedBox.square(key: ValueKey(asset), dimension: size); + +/// Lets [time] pass in 100 ms frames. +Future _wait(WidgetTester tester, Duration time) async { + const frame = Duration(milliseconds: 100); + for (var left = time; left > Duration.zero; left -= frame) { + await tester.pump(left < frame ? left : frame); + } +} + +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pump(); +} + +/// A reply reaches the card: its future, then the frame. +Future _replied(WidgetTester tester) async { + await tester.pump(); + await tester.pump(); +} + +/// The phone: 402 × 874. +const Size _screen = Size(402, 874); + +void main() { + late _Transport transport; + late StreamController requests; + + setUp(() { + StoryPollStore.instance = StoryPollStore(); + transport = _Transport(); + requests = StreamController.broadcast(); + }); + + tearDown(() => requests.close()); + + /// Opens the viewer over a route without Scaffold (no Material), like the SDK does; + /// [own] — with the test transport. + Future open( + WidgetTester tester, + List stories, { + String? apiV3Domain = 'app.example', + bool own = true, + }) async { + tester.view + ..physicalSize = _screen * 3 + ..devicePixelRatio = 3; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => Center( + child: GestureDetector( + onTap: () => Navigator.of(context).push( + PersonalizationStoryViewer.route( + PersonalizationStoriesV3( + apiV3Domain: apiV3Domain, + pollsTransport: own ? transport : null, + pollErrorText: 'Ошибка', + child: PersonalizationStoryViewer( + stories: stories, + storyRequests: requests.stream, + iconBuilder: _icon, + ), + ), + ), + ), + child: const Text('open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await _settle(tester); + } + + Future close(WidgetTester tester) async { + Navigator.of(tester.element(find.text('open'))).pop(); + await _settle(tester); + } + + final Finder card = find.byType(PersonalizationStoryPoll); + + final single = _poll('mini_poll', kind: 'single_choice'); + + testWidgets('the viewer: its own transport draws the card also without API ' + 'v3, no transport and no SDK — none; no Material needed', (tester) async { + final stories = _stories(>>[ + >[ + _slide('1', >[single]), + ], + ]); + await open(tester, stories, own: false); + expect(find.text('Slide 1'), findsOneWidget); + expect(card, findsNothing, reason: 'API v3 without an SDK: no HTTP'); + await close(tester); + await open(tester, stories, apiV3Domain: ''); + expect(card, findsOneWidget, reason: 'its own transport'); + await close(tester); + await open(tester, stories); + expect(card, findsOneWidget); + expect(find.text('Q mini_poll single_choice'), findsOneWidget); + // y_offset 50 of the slide, 12 from the edges, centred. + final rect = tester.getRect(card); + expect(rect.top, _screen.height / 2); + expect((rect.left, rect.right), (12, _screen.width - 12)); + }); + + testWidgets('taps, holds and swipes on the card stay on it', (tester) async { + await open( + tester, + _stories(>>[ + >[ + _slide('1', >[single]), + _slide('2'), + ], + >[_slide('3')], + ]), + ); + final question = find.text('Q mini_poll single_choice'); + // The right third over the card does not go forward. + await tester.tapAt( + Offset(_screen.width - 30, tester.getCenter(question).dy), + ); + await tester.pump(); + expect(find.text('Slide 1'), findsOneWidget); + // Swipes neither turn the story nor close the viewer. + await tester.dragFrom(tester.getCenter(question), const Offset(-300, 0)); + await _settle(tester); + expect(find.text('Slide 1'), findsOneWidget); + await tester.dragFrom(tester.getCenter(question), const Offset(0, 400)); + await _settle(tester); + expect(find.text('Slide 1'), findsOneWidget); + // A hold pauses the slide; a long press on an option is still a press. + final gesture = await tester.startGesture( + tester.getCenter(find.text('Маме')), + ); + await _wait(tester, const Duration(milliseconds: 1500)); + expect(find.text('Slide 1'), findsOneWidget); + await gesture.up(); + await tester.pump(); + expect(transport.bodies.single['option_ids'], [2]); + // Sending holds it too. + await _wait(tester, const Duration(milliseconds: 1500)); + expect(find.text('Slide 1'), findsOneWidget); + transport.pending.single.complete(const StoryPollReply()); + await _replied(tester); + expect(find.text('Спасибо!'), findsOneWidget); + await _wait(tester, const Duration(milliseconds: 1100)); + expect(find.text('Slide 2'), findsOneWidget, reason: 'goes on after'); + // Outside the card the right third goes forward. + await tester.tapAt(Offset(_screen.width - 30, 150)); + await _settle(tester); + expect(find.text('Slide 3'), findsOneWidget); + }); + + testWidgets( + 'the poll pause goes away with the campaign; a late reply is kept', + (tester) async { + final stories = _stories(>>[ + >[ + _slide('1', >[single]), + ], + >[_slide('3'), _slide('4')], + ]); + await open(tester, stories); + await tester.tap(find.text('Себе')); + await tester.pump(); + expect( + transport.pending, + hasLength(1), + reason: 'sending holds the slide', + ); + requests.add(1); + await tester.pump(); + await _settle(tester); + await tester.pump(const Duration(milliseconds: 100)); + expect(find.text('Slide 3'), findsOneWidget); + await _wait(tester, const Duration(milliseconds: 1100)); + expect( + find.text('Slide 4'), + findsOneWidget, + reason: 'not held by the poll', + ); + transport.pending.single.complete( + const StoryPollReply(answer: StoryPollAnswer(optionIds: [1])), + ); + await tester.pump(); + await close(tester); + await open(tester, stories); + expect( + find.text('Спасибо!'), + findsOneWidget, + reason: 'the store kept it', + ); + expect(transport.bodies, hasLength(1)); + }, + ); + + group('text', () { + final text = _poll('mini_poll', kind: 'text', maxLength: 10); + final stories = _stories(>>[ + >[ + _slide('1', >[text]), + _slide('2'), + ], + ]); + const keyboard = 336.0; + + Future showKeyboard(WidgetTester tester) async { + tester.view.viewInsets = const FakeViewPadding(bottom: keyboard * 3); + addTearDown(tester.view.resetViewInsets); + await tester.pump(); + } + + testWidgets( + 'keyboard: the card above it, the slide stays; limit, error, retry', + (tester) async { + await open(tester, stories); + final slideText = tester.getRect(find.text('Slide 1')); + final down = tester.getRect(card); + await tester.tap(find.byType(TextField)); + await tester.pump(); + await showKeyboard(tester); + final up = tester.getRect(card); + expect(up.bottom, _screen.height - keyboard - 16); + expect(up.size, down.size); + expect( + tester.getRect(find.text('Slide 1')), + slideText, + reason: 'not resized', + ); + // Focused — the slide waits. + await _wait(tester, const Duration(milliseconds: 1500)); + expect(find.text('Slide 1'), findsOneWidget); + + expect(find.text('0/10'), findsOneWidget); + await tester.enterText(find.byType(TextField), ' Мастер и Маргарита '); + await tester.pump(); + expect(find.text('10/10'), findsOneWidget); + expect(find.text(' Мастер и '), findsOneWidget); + await tester.tap(find.text('Send')); + await tester.pump(); + expect(transport.bodies.single['text'], 'Мастер и'); + + transport.pending.single.completeError(Exception('HTTP 429')); + await _replied(tester); + expect(find.text('Ошибка'), findsOneWidget); + expect(find.byType(TextField), findsOneWidget); + await tester.tap(find.text('Send')); + await tester.pump(); + expect(transport.bodies, hasLength(2)); + expect(find.text('Ошибка'), findsNothing); + transport.pending.last.complete( + const StoryPollReply(answer: StoryPollAnswer(text: 'Мастер и')), + ); + await _replied(tester); + expect(find.text('Спасибо!'), findsOneWidget); + expect(find.text('Мастер и'), findsOneWidget); + expect(find.byType(TextField), findsNothing); + tester.view.resetViewInsets(); + await tester.pump(); + expect(tester.getRect(card).top, down.top, reason: 'back in place'); + await _wait(tester, const Duration(milliseconds: 1100)); + expect(find.text('Slide 2'), findsOneWidget, reason: 'goes on'); + }, + ); + + testWidgets('a tap past the card with the keyboard only hides it', ( + tester, + ) async { + await open(tester, stories); + await tester.tap(find.byType(TextField)); + await tester.pump(); + await showKeyboard(tester); + expect(FocusManager.instance.primaryFocus?.debugLabel, 'story poll'); + await tester.tapAt(Offset(_screen.width - 30, 150)); + await tester.pump(); + expect(find.text('Slide 1'), findsOneWidget, reason: 'no step forward'); + expect( + FocusManager.instance.primaryFocus?.debugLabel, + isNot('story poll'), + ); + tester.view.resetViewInsets(); + await tester.pump(); + await _wait(tester, const Duration(milliseconds: 1100)); + expect(find.text('Slide 2'), findsOneWidget, reason: 'resumed'); + }); + }); + + testWidgets( + 'the system hides the keyboard (back): the field lets go, the slide goes on', + (tester) async { + await open( + tester, + _stories(>>[ + >[ + _slide('1', >[ + _poll('mini_poll', kind: 'text', maxLength: 10), + ]), + _slide('2'), + ], + ]), + ); + await tester.tap(find.byType(TextField)); + await tester.pump(); + tester.view.viewInsets = const FakeViewPadding(bottom: 336 * 3); + addTearDown(tester.view.resetViewInsets); + await tester.pump(); + expect(FocusManager.instance.primaryFocus?.debugLabel, 'story poll'); + // «Назад» прячет клавиатуру мимо приложения: остаётся только отступ 0. + tester.view.resetViewInsets(); + await tester.pump(); + await tester.pump(); + expect( + FocusManager.instance.primaryFocus?.debugLabel, + isNot('story poll'), + ); + expect(find.text('Slide 1'), findsOneWidget); + await _wait(tester, const Duration(milliseconds: 1100)); + expect(find.text('Slide 2'), findsOneWidget, reason: 'not held'); + }, + ); + + testWidgets('a hardware keyboard (no inset) keeps the focus', (tester) async { + await open( + tester, + _stories(>>[ + >[ + _slide('1', >[ + _poll('mini_poll', kind: 'text', maxLength: 10), + ]), + _slide('2'), + ], + ]), + ); + await tester.tap(find.byType(TextField)); + await tester.pump(); + await _wait(tester, const Duration(milliseconds: 1500)); + expect(FocusManager.instance.primaryFocus?.debugLabel, 'story poll'); + expect(find.text('Slide 1'), findsOneWidget, reason: 'held while focused'); + }); + + testWidgets('answered from the feed: bars, percents, re-answer from labels', ( + tester, + ) async { + await open( + tester, + _stories(>>[ + >[ + _slide('1', >[ + _poll( + 'mini_poll', + kind: 'single_choice', + allowReanswer: true, + labels: {'reanswer': 'Ответить заново'}, + answer: { + 'option_ids': [2], + }, + results: { + 'total': 120, + 'options': >[ + {'id': 1, 'percent': 40}, + {'id': 2, 'percent': 60}, + ], + }, + ), + ]), + ], + ]), + ); + await tester.pump(const Duration(milliseconds: 700)); + expect(find.text('40%'), findsOneWidget); + expect(find.text('60%'), findsOneWidget); + expect(find.text('0%'), findsOneWidget); + expect(find.text('Спасибо!'), findsOneWidget); + await tester.tap(find.text('Ответить заново')); + await tester.pump(); + expect(find.text('60%'), findsNothing); + expect(find.text('Ответить заново'), findsNothing); + await tester.tap(find.text('Себе')); + await tester.pump(); + expect(transport.bodies.single['option_ids'], [1]); + }); + + testWidgets( + 'a product slide has its card; NPS sends a rate, shows its band', + (tester) async { + await open( + tester, + _stories(>>[ + >[ + { + 'id': '39_0', + 'type': '', + 'duration': 1, + 'elements': >[ + { + 'type': 'product', + 'item': { + 'id': 'p1', + 'name': 'Product 1', + 'price': 1, + }, + }, + _poll('nps', yOffset: '30'), + ], + }, + ], + ]), + ); + expect(find.text('Product 1'), findsOneWidget); + expect(find.text('Q nps'), findsOneWidget); + for (var rate = 0; rate <= 10; rate++) { + expect( + find.descendant(of: card, matching: find.text('$rate')), + findsOneWidget, + ); + } + await tester.tap(find.descendant(of: card, matching: find.text('9'))); + await tester.pump(); + expect(transport.bodies.single, { + 'channel': 'stories', + 'category': 'code_nps', + 'rate': 9, + }); + transport.pending.single.complete(const StoryPollReply()); + await _replied(tester); + expect(find.text('Band thanks'), findsOneWidget); + }, + ); + + testWidgets('RTL: the scale and the result bars mirror', (tester) async { + Widget poll(Map json) => MaterialApp( + home: Directionality( + textDirection: TextDirection.rtl, + child: Center( + child: SizedBox( + width: 370, + child: PersonalizationStoryPoll( + key: ValueKey(json['poll_type']), + poll: StoryPollElement.tryParse(json)!, + storyId: '1', + slideId: '1', + transport: transport, + ), + ), + ), + ), + ); + await tester.pumpWidget(poll(_poll('nps'))); + expect( + tester.getCenter(find.text('0')).dx, + greaterThan(tester.getCenter(find.text('10')).dx), + ); + await tester.pumpWidget( + poll( + _poll( + 'mini_poll', + kind: 'single_choice', + answer: { + 'option_ids': [1], + }, + results: { + 'options': >[ + {'id': 1, 'percent': 50}, + ], + }, + ), + ), + ); + await tester.pumpAndSettle(); + final row = tester.getRect( + find.ancestor(of: find.text('Себе'), matching: find.byType(Stack)).first, + ); + final bar = tester.getRect( + find + .descendant( + of: find + .ancestor(of: find.text('Себе'), matching: find.byType(Stack)) + .first, + matching: find.byType(ColoredBox), + ) + .first, + ); + expect( + bar.right, + row.right, + reason: 'grows from the start — the right in RTL', + ); + expect(bar.width, closeTo(row.width / 2, 1)); + expect( + tester.getCenter(find.text('50%')).dx, + lessThan(tester.getCenter(find.text('Себе')).dx), + ); + }); + + /// The card alone, as wide as on a phone slide. + Widget alone( + Map json, { + StoryPollTexts texts = const StoryPollTexts(), + }) => MaterialApp( + home: Center( + child: SizedBox( + width: 370, + child: PersonalizationStoryPoll( + key: UniqueKey(), + poll: StoryPollElement.tryParse(json)!, + storyId: '1', + slideId: '1', + transport: transport, + texts: texts, + ), + ), + ), + ); + + testWidgets('the submit label: submit_label > labels.submit > host > Send', ( + tester, + ) async { + await tester.pumpWidget(alone(_poll('mini_poll', kind: 'multiple_choice'))); + await tester.tap(find.text('Send')); + await tester.pump(); + expect(transport.bodies, isEmpty, reason: 'off while nothing is chosen'); + await tester.tap(find.text('Папе')); + await tester.tap(find.text('Себе')); + await tester.pump(); + await tester.tap(find.text('Send')); + await tester.pump(); + expect(transport.bodies.single['option_ids'], [1, 3]); + + const host = StoryPollTexts(submit: 'Go'); + await tester.pumpWidget( + alone(_poll('mini_poll', kind: 'multiple_choice'), texts: host), + ); + expect(find.text('Go'), findsOneWidget); + await tester.pumpWidget( + alone( + _poll( + 'mini_poll', + kind: 'multiple_choice', + labels: {'submit': 'Отправить'}, + ), + texts: host, + ), + ); + expect(find.text('Отправить'), findsOneWidget); + await tester.pumpWidget( + alone( + _poll( + 'mini_poll', + kind: 'text', + labels: {'submit': 'Отправить'}, + fields: {'submit_label': 'Готово'}, + ), + texts: host, + ), + ); + expect(find.text('Готово'), findsOneWidget); + }); + + testWidgets( + 'text without max_length: no counter, no limit; the placeholder', + (tester) async { + await tester.pumpWidget( + alone( + _poll( + 'mini_poll', + kind: 'text', + fields: {'placeholder': 'Ваш ответ'}, + ), + ), + ); + expect(find.text('Ваш ответ'), findsOneWidget); + expect(find.textContaining('/'), findsNothing); + final long = 'а' * 300; + await tester.enterText(find.byType(TextField), long); + await tester.pump(); + expect( + tester.widget(find.byType(TextField)).controller!.text, + long, + ); + expect(find.textContaining('/'), findsNothing); + }, + ); + + testWidgets('answered: percents rounded; no options array — no percents', ( + tester, + ) async { + Map answered(Object? options) => _poll( + 'mini_poll', + kind: 'single_choice', + answer: { + 'option_ids': [2], + }, + results: {'total': 3, 'options': options}, + ); + await tester.pumpWidget( + alone( + answered(>[ + {'id': 1, 'percent': 40.5}, + {'id': 2, 'percent': '59.4'}, + ]), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('41%'), findsOneWidget); + expect(find.text('59%'), findsOneWidget); + expect(find.text('0%'), findsOneWidget, reason: 'not in the results'); + await tester.pumpWidget(alone(answered(null))); + await tester.pumpAndSettle(); + expect(find.textContaining('%'), findsNothing); + expect(find.text('Спасибо!'), findsOneWidget); + }); + + group('the view', () { + Map answered({ + String thanks = '', + int total = 1248, + String kind = 'single_choice', + }) => _poll( + 'mini_poll', + kind: kind, + answer: { + 'option_ids': [2], + }, + results: { + 'total': total, + 'options': >[ + {'id': 1, 'percent': 52}, + {'id': 2, 'percent': 31}, + {'id': 3, 'percent': 17}, + ], + }, + fields: {'thanks_text': thanks}, + ); + + testWidgets('an answered choice: the results header, my answer checked, ' + '«Thank you! Vote counted» and the votes', (tester) async { + await tester.pumpWidget(alone(answered())); + await tester.pumpAndSettle(); + expect(find.text('RESULTS'), findsOneWidget); + expect(find.text('A'), findsOneWidget); + expect(find.text('B'), findsNothing, reason: 'a check instead'); + expect(find.text('C'), findsOneWidget); + expect(find.text('Thank you! Vote counted'), findsOneWidget); + expect(find.text('1,248 votes'), findsOneWidget); + // The header is above the question, the votes on the right of the thanks. + final question = tester.getRect(find.text('Q mini_poll single_choice')); + expect( + tester.getRect(find.text('RESULTS')).bottom, + lessThan(question.top), + ); + expect( + tester.getRect(find.text('1,248 votes')).right, + tester.getRect(card).right - 20, + ); + + // Its own thanks replaces the pair; no total — no votes. + await tester.pumpWidget( + alone(answered(thanks: 'Спасибо за ответ!', total: 0)), + ); + await tester.pumpAndSettle(); + expect(find.text('Спасибо за ответ!'), findsOneWidget); + expect(find.text('Thank you! Vote counted'), findsNothing); + expect(find.textContaining('vote'), findsNothing); + + await tester.pumpWidget(alone(answered(kind: 'multiple_choice'))); + await tester.pumpAndSettle(); + expect(find.text('RESULTS'), findsOneWidget); + }); + + testWidgets('the results texts follow the device language', (tester) async { + tester.platformDispatcher.localeTestValue = const Locale('ru', 'RU'); + addTearDown(tester.platformDispatcher.clearLocaleTestValue); + await tester.pumpWidget(alone(answered(total: 21))); + await tester.pumpAndSettle(); + expect(find.text('РЕЗУЛЬТАТЫ'), findsOneWidget); + expect(find.text('Спасибо! Голос учтён'), findsOneWidget); + expect(find.text('21 голос'), findsOneWidget); + }); + + testWidgets('no results header in a form, on a scale or a text', ( + tester, + ) async { + for (final json in >[ + _poll('mini_poll', kind: 'single_choice'), + _poll('mini_poll', kind: 'multiple_choice'), + _poll('nps', answer: {'rate': 9}), + _poll( + 'mini_poll', + kind: 'text', + answer: {'text': 'x'}, + ), + ]) { + await tester.pumpWidget(alone(json)); + await tester.pumpAndSettle(); + expect(find.text('RESULTS'), findsNothing, reason: '$json'); + expect(find.textContaining('Vote counted'), findsNothing); + } + await tester.pumpWidget(alone(_poll('mini_poll', kind: 'single_choice'))); + expect( + ['A', 'B', 'C'].map((letter) => find.text(letter)), + everyElement(findsOneWidget), + ); + }); + + testWidgets('sizes: left-aligned text, rows 56 and 8 apart, the track, ' + 'the field and the button 52', (tester) async { + await tester.pumpWidget(alone(_poll('mini_poll', kind: 'single_choice'))); + final box = tester.getRect(card); + expect( + tester.getRect(find.text('Q mini_poll single_choice')).left, + box.left + 20, + ); + Rect row(String label) => tester.getRect( + find + .ancestor(of: find.text(label), matching: find.byType(Container)) + .first, + ); + expect(row('Себе').height, 56); + expect(row('Маме').top - row('Себе').bottom, 8); + expect( + tester.getRect(find.text('Себе')).left, + box.left + 20 + 12 + 32 + 12, + reason: 'the letter square and its gaps', + ); + + await tester.pumpWidget(alone(_poll('nps'))); + final track = find + .ancestor(of: find.text('0'), matching: find.byType(Container)) + .first; + expect(tester.getSize(track).height, 52); + expect(tester.getRect(track).width, box.width - 40); + + await tester.pumpWidget(alone(_poll('mini_poll', kind: 'text'))); + expect( + tester + .getSize( + find + .ancestor( + of: find.byType(TextField), + matching: find.byType(Container), + ) + .first, + ) + .height, + greaterThanOrEqualTo(52), + ); + expect( + tester + .getSize( + find + .ancestor( + of: find.text('Send'), + matching: find.byType(Container), + ) + .first, + ) + .height, + 52, + ); + }); + + testWidgets('a chosen row is filled only before sending; my answer in the ' + 'results keeps the usual background, the accent border and bar; text ' + 'on the accent by contrast', (tester) async { + const accent = Color(0xFF22C55E); + Container row(String label) => tester.widget( + find + .ancestor(of: find.text(label), matching: find.byType(Container)) + .first, + ); + Color? fill(String label) => + (row(label).decoration! as BoxDecoration).color; + Color? border(String label) => + ((row(label).foregroundDecoration as BoxDecoration?)?.border + as Border?) + ?.top + .color; + + await tester.pumpWidget( + alone(_poll('mini_poll', kind: 'multiple_choice')), + ); + await tester.tap(find.text('Маме')); + await tester.pump(); + expect((fill('Маме'), border('Маме')), (const Color(0x3322C55E), accent)); + expect((fill('Себе'), border('Себе')), (const Color(0x0F000000), null)); + expect( + tester.widget(find.text('Send')).style!.color, + const Color(0xFF000000), + reason: 'dark is the contrast on the accent', + ); + + await tester.pumpWidget(alone(answered())); + await tester.pumpAndSettle(); + expect((fill('Маме'), border('Маме')), (const Color(0x0F000000), accent)); + expect((fill('Себе'), border('Себе')), (const Color(0x0F000000), null)); + Color bar(String label) => tester + .widget( + find.descendant( + of: find + .ancestor(of: find.text(label), matching: find.byType(Stack)) + .first, + matching: find.byType(ColoredBox), + ), + ) + .color; + expect(bar('Маме'), const Color(0x4022C55E)); + expect(bar('Себе'), const Color(0x14000000)); + }); + + testWidgets('the scale: the chosen digit in a capsule of its band colour, ' + 'the accent without bands; the rest dimmed once answered', ( + tester, + ) async { + Color? capsule(String digit) { + final decoration = + tester + .widget( + find + .ancestor( + of: find.text(digit), + matching: find.byType(DecoratedBox), + ) + .first, + ) + .decoration + as BoxDecoration; + return decoration.color; + } + + double opacity(String digit) => tester + .widget( + find + .ancestor(of: find.text(digit), matching: find.byType(Opacity)) + .first, + ) + .opacity; + + await tester.pumpWidget( + alone(_poll('nps', answer: {'rate': 9})), + ); + expect(capsule('9'), storyPollScaleColor(StoryPollType.nps, 9, 0, 10)); + expect(capsule('5'), isNull); + expect((opacity('9'), opacity('5')), (1.0, 0.55)); + expect( + tester.widget(find.text('9')).style!.color, + const Color(0xFF000000), + reason: 'dark is the contrast on a light green', + ); + + await tester.pumpWidget( + alone( + _poll( + 'csat', + answer: {'rate': 3}, + fields: {'bands': []}, + ), + ), + ); + expect(capsule('3'), const Color(0xFF22C55E)); + }); + }); + + testWidgets('text re-answer: an empty field in focus, the slide held', ( + tester, + ) async { + await open( + tester, + _stories(>>[ + >[ + _slide('1', >[ + _poll( + 'mini_poll', + kind: 'text', + maxLength: 10, + allowReanswer: true, + ), + ]), + _slide('2'), + ], + ]), + ); + await tester.enterText(find.byType(TextField), 'Книга'); + await tester.pump(); + await tester.tap(find.text('Send')); + await tester.pump(); + transport.pending.single.complete(const StoryPollReply()); + await _replied(tester); + expect(find.byType(TextField), findsNothing); + expect(find.text('Книга'), findsOneWidget, reason: 'the answer'); + await tester.tap(find.text('Answer again')); + await tester.pump(); + await tester.pump(); + expect( + tester.widget(find.byType(TextField)).controller!.text, + isEmpty, + reason: 'the previous text is not put back', + ); + expect(find.text('0/10'), findsOneWidget); + expect(FocusManager.instance.primaryFocus?.debugLabel, 'story poll'); + await _wait(tester, const Duration(milliseconds: 1500)); + expect(find.text('Slide 1'), findsOneWidget, reason: 'held while focused'); + }); + + testWidgets('y_offset is a share of the whole slide, system bars included', ( + tester, + ) async { + tester.view + ..padding = const FakeViewPadding(top: 50 * 3, bottom: 34 * 3) + ..viewPadding = const FakeViewPadding(top: 50 * 3, bottom: 34 * 3); + await open( + tester, + _stories(>>[ + >[ + _slide('1', >[_poll('nps', yOffset: 50)]), + ], + >[ + _slide('2', >[_poll('nps', yOffset: 0)]), + ], + ]), + ); + expect(tester.getRect(card).top, _screen.height / 2); + requests.add(1); + await tester.pump(); + await _settle(tester); + expect(find.text('Slide 2'), findsOneWidget); + expect( + tester.getRect(card).top, + greaterThan(50 + 16), + reason: 'moved under the header', + ); + }); + + testWidgets('y_offset: none, below 0 or not a number — right under the ' + 'header; over 100 — down to the bottom', (tester) async { + final offsets = [0, null, -20, 'NaN', 100, 150]; + await open( + tester, + _stories(>>[ + for (final offset in offsets) + >[ + _slide('$offset', >[ + _poll('nps', yOffset: offset), + ]), + ], + ]), + ); + final rects = []; + for (var index = 0; index < offsets.length; index++) { + if (index > 0) { + requests.add(index); + await tester.pump(); + await _settle(tester); + } + expect(find.text('Slide ${offsets[index]}'), findsOneWidget); + rects.add(tester.getRect(card)); + } + expect(rects.first.top, greaterThan(16), reason: 'under the header'); + expect( + rects.sublist(1, 4).map((rect) => rect.top), + everyElement(rects.first.top), + ); + expect(rects[4].bottom, _screen.height - 16); + expect(rects[5], rects[4]); + }); + + group('PersonalizationStories', () { + late _HostApi api; + late PersonalizationSdk sdk; + late List calls; + late List> posts; + final payload = { + 'id': 35, + 'stories': >[ + { + 'id': 1, + 'name': 'Polls', + 'avatar': '', + 'slides': >[ + _slide('1', >[single]), + _slide('2'), + ], + }, + ], + }; + + setUp(() { + StoriesSeenStore.instance = StoriesSeenStore(); + api = _HostApi()..bridgeFeed = jsonEncode(payload); + sdk = PersonalizationSdk(api: api, shopId: 'shop'); + calls = []; + posts = >[]; + StoriesApiV3.send = (method, uri, body) async { + calls.add('$method ${uri.host}${uri.path}'); + if (method == 'GET') { + return ( + status: 200, + body: jsonEncode({ + 'status': 'success', + 'payload': payload, + }), + ); + } + posts.add(jsonDecode(body!) as Map); + return (status: 200, body: '{"status":"success"}'); + }; + }); + + Future openBlock( + WidgetTester tester, { + required String apiV3Domain, + bool own = true, + }) async { + tester.view + ..physicalSize = _screen * 3 + ..devicePixelRatio = 3; + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: PersonalizationStoriesV3( + apiV3Domain: apiV3Domain, + pollsTransport: own ? transport : null, + child: PersonalizationStories( + key: UniqueKey(), + code: 'block', + sdk: sdk, + iconBuilder: _icon, + ), + ), + ), + ), + ), + ), + ); + await tester.pump(); + await tester.pump(); + await tester.tap(find.text('Polls')); + await _settle(tester); + } + + Future closeViewer(WidgetTester tester) async { + Navigator.of( + tester.element(find.byType(PersonalizationStoryViewer)), + ).pop(); + await _settle(tester); + } + + testWidgets('a transport only with API v3; polls send no events', ( + tester, + ) async { + await openBlock(tester, apiV3Domain: ''); + expect(find.text('Slide 1'), findsOneWidget); + expect( + card, + findsNothing, + reason: 'the old API: its own transport does not turn polls on', + ); + expect(calls, isEmpty); + await closeViewer(tester); + + // Slide 1 is seen now: the viewer would start from slide 2. + StoriesSeenStore.instance = StoriesSeenStore(); + + await openBlock(tester, apiV3Domain: 'app.example'); + expect(card, findsOneWidget); + await tester.tap(find.text('Маме')); + await tester.pump(); + expect(transport.bodies.single['option_ids'], [2]); + transport.pending.single.complete(const StoryPollReply()); + await _replied(tester); + expect(find.text('Спасибо!'), findsOneWidget); + expect(calls.where((call) => call.contains('/polls/')), isEmpty); + expect(posts.map((post) => post['event']).toSet(), { + 'view', + }, reason: 'no events for polls'); + await closeViewer(tester); + }); + + testWidgets('without its own transport — HTTP to the host of the block', ( + tester, + ) async { + await openBlock(tester, apiV3Domain: 'app.example', own: false); + await tester.tap(find.text('Маме')); + for (var i = 0; i < 5; i++) { + await tester.pump(); + } + expect( + calls.last, + 'POST app.example/api/v3/polls/mini_polls/code_mini_pollsingle_choice/answers', + ); + expect(posts.last, { + 'shop_id': 'shop', + 'did': 'did-1', + 'sid': 'sid-1', + 'option_ids': [2], + 'story_id': 1, + 'slide_id': '1', + }); + expect(find.text('Спасибо!'), findsOneWidget); + await closeViewer(tester); + }); + }); +} + +/// The SDK bridge for a block: the old feed, seen slides and tracking do nothing. +class _HostApi extends pigeon.PersonalizationHostApi { + /// What the old-API feed through the bridge answers. + String bridgeFeed = ''; + + @override + Future getDid(String? shopId) async => 'did-1'; + + @override + Future getSid(String? shopId) async => 'sid-1'; + + @override + Future getStories(String code, String? shopId) async => bridgeFeed; + + @override + Future>> getStoriesSeen(String shop) async => + >{}; + + @override + Future setStorySlideSeen( + String shop, + String story, + String slide, + ) async {} + + @override + Future trackStoryView( + String storyId, + String slideId, + String? code, + String? shopId, + ) async {} + + @override + Future trackStoryClick( + String storyId, + String slideId, + String? code, + String? shopId, + ) async {} + + @override + Future trackSetSource( + pigeon.TrackingSourceWire source, + String? shopId, + ) async {} +} diff --git a/test/ui/stories_polls_api_test.dart b/test/ui/stories_polls_api_test.dart new file mode 100644 index 0000000..0c7f5cb --- /dev/null +++ b/test/ui/stories_polls_api_test.dart @@ -0,0 +1,357 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/stories/stories_response.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_polls_api.dart'; + +class _FakeHostApi extends pigeon.PersonalizationHostApi { + String sid = 'sid-1'; + String? did = 'did-1'; + + /// `getSid` throws: no session yet. + bool noSession = false; + + @override + Future getDid(String? shopId) async => did; + + @override + Future getSid(String? shopId) async => + noSession ? throw StateError('no session') : sid; +} + +/// One request: method, URL and the JSON body. +typedef _Request = ({String method, Uri uri, Map body}); + +StoryPollElement _poll(StoryPollType type, {String channel = ''}) => + StoryPollElement(pollType: type, code: 'delivery', channel: channel); + +void main() { + late _FakeHostApi api; + late PersonalizationSdk sdk; + late StoriesPollsApi polls; + late List<_Request> requests; + late FutureOr Function() reply; + + setUp(() { + api = _FakeHostApi(); + sdk = PersonalizationSdk(api: api, shopId: 'shop'); + polls = StoriesPollsApi(sdk, 'app.example'); + requests = <_Request>[]; + reply = () => (status: 200, body: '{"status":"success"}'); + StoriesApiV3.send = (method, uri, body) async { + requests.add(( + method: method, + uri: uri, + body: jsonDecode(body!) as Map, + )); + return reply(); + }; + }); + + group('bodies', () { + test( + 'a mini poll: the campaign as a number, the slide always a string', + () { + expect( + storyPollAnswerBody( + optionIds: [2], + storyId: '5', + slideId: '101', + ), + { + 'option_ids': [2], + 'story_id': 5, + 'slide_id': '101', + }, + ); + expect( + storyPollAnswerBody(text: 'Мастер', storyId: '39', slideId: '39_0'), + { + 'text': 'Мастер', + 'story_id': 39, + 'slide_id': '39_0', + }, + ); + }, + ); + + test('no code and a blank channel go as they are', () { + expect( + storyPollReviewBody( + StoryPollElement(pollType: StoryPollType.nps, code: ''), + 5, + ), + {'channel': 'stories', 'category': '', 'rate': 5}, + ); + expect( + storyPollReviewBody( + StoryPollElement(pollType: StoryPollType.ces, code: '', channel: ' '), + 5, + ), + {'channel': ' ', 'campaign': '', 'rate': 5}, + ); + }); + + test('a scale: category for NPS, campaign for CSAT and CES', () { + expect(storyPollReviewBody(_poll(StoryPollType.nps), 9), { + 'channel': 'stories', + 'category': 'delivery', + 'rate': 9, + }); + expect( + storyPollReviewBody(_poll(StoryPollType.csat, channel: 'web'), 1), + {'channel': 'web', 'campaign': 'delivery', 'rate': 1}, + ); + expect(storyPollReviewBody(_poll(StoryPollType.ces), 7), { + 'channel': 'stories', + 'campaign': 'delivery', + 'rate': 7, + }); + }); + }); + + test( + 'a mini poll answer goes to /mini_polls/{code}/answers with the ids', + () async { + reply = () => ( + status: 200, + body: jsonEncode({ + 'status': 'success', + 'payload': { + 'answer': { + 'id': 77, + 'option_ids': [2], + 'text': null, + }, + 'results': { + 'total': 121, + 'options': >[ + {'id': 1, 'percent': 40}, + {'id': 2, 'percent': 60}, + ], + }, + }, + }), + ); + final result = await polls.answerMiniPoll( + 'gift recipient/1', + storyPollAnswerBody(optionIds: [2], storyId: '5', slideId: '101'), + ); + final request = requests.single; + expect(request.method, 'POST'); + expect( + request.uri.toString(), + 'https://app.example/api/v3/polls/mini_polls/gift%20recipient%2F1/answers', + ); + expect(request.body, { + 'shop_id': 'shop', + 'did': 'did-1', + 'sid': 'sid-1', + 'option_ids': [2], + 'story_id': 5, + 'slide_id': '101', + }); + expect(result.answer!.id, 77); + expect(result.answer!.optionIds, [2]); + expect(result.results!.percentOf(2), 60); + }, + ); + + test( + '200 without an answer; sid always goes, empty without a session', + () async { + api.sid = ''; + final result = await polls.answerMiniPoll( + 'x', + storyPollAnswerBody(text: 'ok', storyId: '5', slideId: '7'), + ); + expect(result.answer, isNull); + expect(result.results, isNull); + expect(requests.single.body['sid'], ''); + api.noSession = true; + await polls.review(StoryPollType.csat, {'rate': 4}); + expect(requests.last.body['sid'], ''); + }, + ); + + test('no code: the request still goes, the server answers', () async { + reply = () => + (status: 404, body: '{"status":"fail","message":"Poll not found"}'); + await expectLater( + polls.answerMiniPoll('', {'text': 'a'}), + throwsA(isA()), + ); + expect(requests.single.uri.path, '/api/v3/polls/mini_polls//answers'); + }); + + testWidgets('did is awaited like the feed; none in time — an error', ( + tester, + ) async { + api.did = null; + Object? error; + unawaited( + polls + .review(StoryPollType.nps, {'rate': 1}) + .then((_) {}, onError: (Object e) => error = e), + ); + await tester.pump(const Duration(seconds: 1)); + expect(requests, isEmpty, reason: 'waits for the did'); + api.did = 'did-2'; + await tester.pump(StoriesApiV3.didPoll); + await tester.pump(); + expect(requests.single.body['did'], 'did-2'); + expect(error, isNull); + + api.did = null; + unawaited( + polls + .review(StoryPollType.nps, {'rate': 1}) + .then((_) {}, onError: (Object e) => error = e), + ); + await tester.pump(StoriesApiV3.didTimeout + StoriesApiV3.didPoll); + await tester.pump(StoriesApiV3.didPoll); + expect(error, isA()); + expect(requests, hasLength(1)); + }); + + test( + 'any answer object of the reply is the answer, even without ids', + () async { + reply = () => ( + status: 200, + body: + '{"status":"success","payload":{"answer":{"id":77},"results":null}}', + ); + final result = await polls.answerMiniPoll('x', { + 'option_ids': [1], + }); + expect(result.answer!.id, 77); + expect(result.answer!.optionIds, isNull); + expect(result.results, isNull); + }, + ); + + test('reviews go to /polls/{kind}/reviews', () async { + for (final kind in [ + StoryPollType.nps, + StoryPollType.csat, + StoryPollType.ces, + ]) { + await polls.review(kind, storyPollReviewBody(_poll(kind), 3)); + } + expect(requests.map((request) => request.uri.path), [ + '/api/v3/polls/nps/reviews', + '/api/v3/polls/csat/reviews', + '/api/v3/polls/ces/reviews', + ]); + expect(requests.first.body, { + 'shop_id': 'shop', + 'did': 'did-1', + 'sid': 'sid-1', + 'channel': 'stories', + 'category': 'delivery', + 'rate': 3, + }); + }); + + group('errors', () { + for (final status in [400, 402, 403, 404, 429, 500, 503]) { + test('HTTP $status, with its code and message', () async { + reply = () => ( + status: status, + body: '{"status":"fail","message":"Payment required"}', + ); + final error = await polls + .review(StoryPollType.nps, {'rate': 1}) + .then((_) => null, onError: (Object error) => error); + expect(error, isA()); + error as StoriesV3Exception; + expect(error.status, status); + expect(error.message, 'HTTP $status: Payment required'); + }); + } + + test('fail or error with 200', () async { + reply = () => (status: 200, body: '{"status":"fail","message":"Nope"}'); + await expectLater( + polls.answerMiniPoll('x', {'text': 'a'}), + throwsA(isA()), + ); + reply = () => (status: 200, body: '{"status":"error"}'); + await expectLater( + polls.review(StoryPollType.ces, {'rate': 1}), + throwsA(isA()), + ); + }); + + test('only 2xx is a success: a redirect is an error', () async { + reply = () => (status: 302, body: '{"status":"success"}'); + await expectLater( + polls.review(StoryPollType.nps, {'rate': 1}), + throwsA(isA()), + ); + }); + + test( + 'the transport logs a failure with its HTTP code and message', + () async { + final logs = []; + final print = debugPrint; + debugPrint = (message, {wrapWidth}) => logs.add(message ?? ''); + addTearDown(() => debugPrint = print); + reply = () => ( + status: 429, + body: '{"status":"fail","message":"Too many requests"}', + ); + await polls + .answerMiniPoll('gift', {'text': 'a'}) + .then((_) {}, onError: (Object _) {}); + await polls + .review(StoryPollType.csat, {'campaign': 'support'}) + .then((_) {}, onError: (Object _) {}); + expect(logs, hasLength(2)); + expect(logs.first, contains('"gift"')); + expect(logs.last, contains('csat "support"')); + expect(logs, everyElement(contains('HTTP 429: Too many requests'))); + }, + ); + + test('not JSON', () async { + reply = () => (status: 200, body: ''); + await expectLater( + polls.answerMiniPoll('x', {'text': 'a'}), + throwsA(isA()), + ); + }); + + test('no network', () async { + reply = () => throw const SocketException('offline'); + await expectLater( + polls.answerMiniPoll('x', {'text': 'a'}), + throwsA(isA()), + ); + }); + + testWidgets('no answer in time', (tester) async { + reply = () => Completer().future; + Object? error; + unawaited( + polls + .review(StoryPollType.nps, {'rate': 1}) + .then((_) {}, onError: (Object e) => error = e), + ); + await tester.pump( + StoriesApiV3.requestTimeout - const Duration(seconds: 1), + ); + expect(error, isNull); + await tester.pump(const Duration(seconds: 2)); + expect(error, isA()); + }); + }); +} diff --git a/test/ui/stories_runtime_test.dart b/test/ui/stories_runtime_test.dart index 8bf6bb8..66e7f30 100644 --- a/test/ui/stories_runtime_test.dart +++ b/test/ui/stories_runtime_test.dart @@ -1,6 +1,8 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/personalization_sdk.dart' + show PersonalizationStoryViewerBridge; import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; import 'package:rees46_sdk/src/ui/widgets/stories_sound.dart'; @@ -35,6 +37,17 @@ class _FakeHostApi extends pigeon.PersonalizationHostApi { @override Future endStoriesAudio() async => audio.add('end'); + + final List shares = []; + + @override + Future shareUrl( + String url, + double anchorX, + double anchorY, + double anchorWidth, + double anchorHeight, + ) async => shares.add('$url $anchorX,$anchorY $anchorWidth×$anchorHeight'); } void main() { @@ -88,4 +101,16 @@ void main() { expect(api.audio, ['begin', 'muted', 'sound', 'muted', 'end']); expect(sound.muted.value, isTrue, reason: 'the choice outlives a viewer'); }); + + test('share hands the link and the button frame to the platform', () async { + final api = _FakeHostApi(); + final sdk = PersonalizationSdk(api: api, shopId: 'shop-a'); + await sdk.shareUrl( + 'https://shop.test/?r46_story=5', + const Rect.fromLTWH(320, 60, 32, 32), + ); + expect(api.shares, [ + 'https://shop.test/?r46_story=5 320.0,60.0 32.0×32.0', + ]); + }); } diff --git a/test/ui/stories_share_test.dart b/test/ui/stories_share_test.dart new file mode 100644 index 0000000..0dbfbd2 --- /dev/null +++ b/test/ui/stories_share_test.dart @@ -0,0 +1,334 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_share.dart'; + +const String _code = 'block'; + +/// A product element of a v3 product slide. +Map _product(String id) => { + 'type': 'product', + 'item': {'id': id, 'name': 'Product $id', 'price': 1}, +}; + +/// A v3 product slide: `background` and `preview` are JSON `null`, no own link. +Map _productSlide(String id) => { + 'id': id, + 'type': '', + 'background': null, + 'preview': null, + 'duration': 1, + 'elements': >[_product(id)], +}; + +/// A v3 media-free slide with its own link. +Map _linkedSlide( + int id, { + int story = 40, +}) => { + 'id': id, + 'type': '', + 'duration': 1, + 'share_url': + 'https://shop.example/?r46_stories=$_code&r46_story=$story&r46_slide=$id', + 'elements': >[_product('$id')], +}; + +/// Campaign 39 — products `39_0`, `39_1`, a campaign link only; campaign 40 — slides 37, +/// 38 with own links; campaign 41 — sharing off. +Map _feed({ + int start40 = 0, + List? only, +}) => { + 'status': 'success', + 'payload': { + 'id': 35, + 'settings': {'avatar_size': 54}, + 'stories': >[ + { + 'id': 39, + 'name': 'Products', + 'avatar': '', + 'shareable': true, + 'share_url': 'https://shop.example/?r46_stories=$_code&r46_story=39', + 'slides': [_productSlide('39_0'), _productSlide('39_1')], + }, + { + 'id': 40, + 'name': 'Media', + 'avatar': '', + 'start_position': start40, + 'share_url': 'https://shop.example/?r46_stories=$_code&r46_story=40', + 'slides': [_linkedSlide(37), _linkedSlide(38)], + }, + { + 'id': 41, + 'name': 'Private', + 'avatar': '', + 'shareable': false, + 'share_url': 'https://shop.example/?r46_story=41', + 'slides': [_linkedSlide(50, story: 41)], + }, + ].where((story) => only == null || only.contains(story['id'])).toList(), + }, +}; + +void main() { + group('parseStoriesShareLink', () { + test('reads block, campaign and slide', () { + expect( + parseStoriesShareLink( + 'https://shop.test/?utm_source=tg&r46_stories=main&r46_story=5&r46_slide=10', + ), + const StoriesShareLink(code: 'main', storyId: '5', slideId: '10'), + ); + }); + + test('accepts links without a slide and virtual slides', () { + expect( + parseStoriesShareLink('?r46_stories=main&r46_story=5'), + const StoriesShareLink(code: 'main', storyId: '5'), + ); + expect( + parseStoriesShareLink( + 'https://shop.test/promo?r46_stories=main&r46_story=5&r46_slide=5_2', + )?.slideId, + '5_2', + ); + }); + + test('ignores other pages and broken links', () { + expect(parseStoriesShareLink(''), isNull); + expect(parseStoriesShareLink('https://shop.test/'), isNull); + expect(parseStoriesShareLink('?r46_story=5'), isNull); + expect(parseStoriesShareLink('?r46_stories=&r46_story=5'), isNull); + expect(parseStoriesShareLink('?r46_stories=main&r46_story=abc'), isNull); + expect( + parseStoriesShareLink('?r46_stories=main&r46_story=12345678901'), + isNull, + ); + expect(parseStoriesShareLink('?r46_stories=main&r46_story=%zz'), isNull); + final broken = parseStoriesShareLink( + '?r46_stories=main&r46_story=5&r46_slide=1;DROP', + ); + expect(broken?.storyId, '5', reason: 'the campaign still opens'); + expect(broken?.slideId, isNull); + }); + }); + + group('storySlideShareUrl', () { + final story = Story.fromJson({ + 'id': 5, + 'shareable': true, + 'share_url': 'https://shop.test/?r46_story=5', + 'slides': [ + { + 'id': 1, + 'share_url': 'https://shop.test/?r46_slide=1', + }, + {'id': '5_0'}, + ], + }); + + test('prefers the slide link, falls back to the campaign link with the ' + 'slide in it', () { + expect( + storySlideShareUrl(story, story.slides[0]), + 'https://shop.test/?r46_slide=1', + ); + expect( + storySlideShareUrl(story, story.slides[1]), + 'https://shop.test/?r46_story=5&r46_slide=5_0', + reason: 'a product slide has no link of its own', + ); + }); + + test( + 'the campaign link takes r46_slide once, the rest stays as it was', + () { + const campaign = 'https://shop.test/?r46_story=5'; + expect( + storyCampaignSlideUrl(campaign, '37'), + 'https://shop.test/?r46_story=5&r46_slide=37', + ); + expect( + storyCampaignSlideUrl( + 'https://shop.test/p?q=a%20b&r46_story=5#top', + '5_2', + ), + 'https://shop.test/p?q=a%20b&r46_story=5&r46_slide=5_2#top', + reason: 'before the fragment, nothing re-encoded', + ); + expect( + storyCampaignSlideUrl('https://shop.test/promo', '5_2'), + 'https://shop.test/promo?r46_slide=5_2', + ); + expect( + storyCampaignSlideUrl('https://shop.test/?', '7'), + 'https://shop.test/?r46_slide=7', + ); + expect( + storyCampaignSlideUrl('$campaign&r46_slide=7', '5_2'), + '$campaign&r46_slide=7', + reason: 'r46_slide is there already', + ); + for (final id in [ + 'x', + '', + '1_', + '12345678901', + '1_12345', + '1;2', + ]) { + expect( + storyCampaignSlideUrl(campaign, id), + campaign, + reason: 'a link does not carry "$id"', + ); + } + expect(storyCampaignSlideUrl('', '37'), ''); + }, + ); + + test('nothing when sharing is off or the link is not http(s)', () { + Story make(Map json) => Story.fromJson({ + ...json, + 'slides': [ + {'id': 1}, + ], + }); + final off = make({ + 'shareable': false, + 'share_url': 'https://shop.test/', + }); + expect(storySlideShareUrl(off, off.slides.single), isNull); + final none = make({}); + expect(storySlideShareUrl(none, none.slides.single), isNull); + final script = make({ + 'share_url': 'javascript:alert(1)', + }); + expect(storySlideShareUrl(script, script.slides.single), isNull); + final upper = make({'share_url': 'HTTPS://shop.test/'}); + expect( + storySlideShareUrl(upper, upper.slides.single), + 'HTTPS://shop.test/?r46_slide=1', + ); + }); + }); + + group('StoriesApiV3', () { + tearDown(() => StoriesApiV3.domain = null); + + test('reads the payload of the wrapper like the old feed', () { + final block = StoriesApiV3.parseResponse(( + status: 200, + body: jsonEncode(_feed()), + )); + expect(block.id, '35'); + expect(block.stories.map((story) => story.id), [ + '39', + '40', + '41', + ]); + final products = block.stories.first; + expect(products.shareable, isTrue); + expect(products.shareUrl, contains('r46_story=39')); + final slide = products.slides.first; + expect(slide.id, '39_0'); + expect(slide.background, '', reason: 'JSON null is empty, not "null"'); + expect(slide.preview, ''); + expect(slide.shareUrl, ''); + expect(block.stories[1].shareable, isTrue, reason: 'missing — allowed'); + expect(block.stories[1].slides.first.shareUrl, contains('r46_slide=37')); + expect(block.stories[2].shareable, isFalse); + }); + + test('a failure, an HTTP error or HTML is a load error', () { + expect( + () => StoriesApiV3.parseResponse(( + status: 200, + body: '{"status":"fail","message":"Client not found"}', + )), + throwsA(isA()), + ); + expect( + () => StoriesApiV3.parseResponse(( + status: 404, + body: '{"status":"fail","message":"Resource not found"}', + )), + throwsA(isA()), + ); + expect( + () => StoriesApiV3.parseResponse(( + status: 404, + body: 'Not found', + )), + throwsA(isA()), + ); + expect( + () => StoriesApiV3.parseResponse((status: 200, body: '')), + throwsA(isA()), + ); + }); + + test('the event: the campaign id a number, the slide id a string', () { + expect( + StoriesApiV3.eventBody( + shopId: 'shop', + did: 'did', + event: StoriesV3Event.sharedOpen, + storyId: '40', + slideId: '37', + ), + { + 'shop_id': 'shop', + 'did': 'did', + 'event': 'shared_open', + 'story_id': 40, + 'slide_id': '37', + }, + ); + final virtual = StoriesApiV3.eventBody( + shopId: 'shop', + did: 'did', + event: StoriesV3Event.view, + storyId: '39', + slideId: '39_0', + ); + expect(virtual['story_id'], 39); + expect(virtual['slide_id'], '39_0'); + }); + + test('addresses go to the v3 host, the scheme is optional', () { + expect( + StoriesApiV3.uri( + 'app.rees46.ru', + ['a b', 'story', '40'], + {'shop_id': 's', 'did': 'd', 'slide_id': '37'}, + ).toString(), + 'https://app.rees46.ru/api/v3/storefront/stories/a%20b/story/40' + '?shop_id=s&did=d&slide_id=37', + ); + expect( + StoriesApiV3.uri(StoriesApiV3.host('https://app.rees46.ru/')!, [ + 'b', + 'events', + ], const {}).toString(), + 'https://app.rees46.ru/api/v3/storefront/stories/b/events', + ); + }); + + test('the own host wins over the global one, empty turns v3 off', () { + expect(StoriesApiV3.host(null), isNull); + expect(StoriesApiV3.host('own.example'), 'own.example'); + StoriesApiV3.domain = 'global.example'; + expect(StoriesApiV3.host(null), 'global.example'); + expect(StoriesApiV3.host('own.example'), 'own.example'); + expect(StoriesApiV3.host(''), isNull); + expect(StoriesApiV3.host(' '), isNull); + }); + }); +} diff --git a/test/ui/stories_share_widget_test.dart b/test/ui/stories_share_widget_test.dart new file mode 100644 index 0000000..e8cde77 --- /dev/null +++ b/test/ui/stories_share_widget_test.dart @@ -0,0 +1,615 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_api_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; + +const String _code = 'block'; + +Map _slide( + String id, { + bool link = false, +}) => { + 'id': id, + 'type': '', + 'background': null, + 'preview': null, + 'duration': 1, + if (link) 'share_url': 'https://shop.example/?r46_story=40&r46_slide=$id', + 'elements': >[ + { + 'type': 'product', + 'item': {'id': id, 'name': 'Product $id', 'price': 1}, + }, + ], +}; + +const String _link39 = 'https://shop.example/?r46_story=39'; + +/// Campaign 39 — product slides with a campaign link; 40 — slides 37, 38 with own links, +/// [start40] is the slide of a link; 41 — sharing off. +String _feed({ + int start40 = 0, + List? only, +}) => jsonEncode({ + 'status': 'success', + 'payload': { + 'id': 35, + 'stories': + >[ + { + 'id': 39, + 'name': 'Products', + 'avatar': '', + 'share_url': _link39, + 'slides': [_slide('39_0'), _slide('39_1')], + }, + { + 'id': 40, + 'name': 'Media', + 'avatar': '', + 'start_position': start40, + 'slides': [_slide('37', link: true), _slide('38', link: true)], + }, + { + 'id': 41, + 'name': 'Private', + 'avatar': '', + 'shareable': false, + 'share_url': 'https://shop.example/?r46_story=41', + 'slides': [_slide('50', link: true)], + }, + ] + .where((story) => only == null || only.contains('${story['id']}')) + .toList(), + }, +}); + +class _FakeHostApi extends pigeon.PersonalizationHostApi { + final List bridge = []; + final List sources = []; + final List shared = []; + final List anchors = []; + + /// The open share sheet: completing it closes the sheet. + Completer? sheet; + + /// What the old-API feed through the bridge answers; `null` — it must not be asked. + String? bridgeFeed; + + @override + Future getDid(String? shopId) async => 'did-1'; + + @override + Future getStories(String code, String? shopId) async => + bridgeFeed ?? (throw StateError('the bridge feed is off with API v3')); + + @override + Future>> getStoriesSeen(String shop) async => + >{}; + + @override + Future setStorySlideSeen( + String shop, + String story, + String slide, + ) async {} + + @override + Future trackStoryView( + String storyId, + String slideId, + String? code, + String? shopId, + ) async => bridge.add('view $storyId/$slideId'); + + @override + Future trackStoryClick( + String storyId, + String slideId, + String? code, + String? shopId, + ) async => bridge.add('click $storyId/$slideId'); + + @override + Future trackSetSource( + pigeon.TrackingSourceWire source, + String? shopId, + ) async => sources.add('${source.type}/${source.code}'); + + @override + Future shareUrl( + String url, + double anchorX, + double anchorY, + double anchorWidth, + double anchorHeight, + ) { + shared.add(url); + anchors.add(Rect.fromLTWH(anchorX, anchorY, anchorWidth, anchorHeight)); + return (sheet = Completer()).future; + } +} + +/// API v3 in memory: GET answers [answer], POST is an event. +class _Server { + _Server(this.answer); + + StoriesV3Response Function(Uri uri) answer; + final List gets = []; + final List events = []; + + /// Hosts of all requests, in order. + final List hosts = []; + + Future send(String method, Uri uri, String? body) async { + hosts.add(uri.host); + if (method == 'POST') { + final event = jsonDecode(body!) as Map; + expect(uri.path, '/api/v3/storefront/stories/$_code/events'); + expect(event['shop_id'], 'shop'); + expect(event['did'], 'did-1'); + events.add('${event['event']} ${event['story_id']}/${event['slide_id']}'); + return (status: 200, body: '{"status":"success"}'); + } + gets.add('${uri.path}?${uri.query}'); + return answer(uri); + } +} + +Widget _icon(BuildContext context, String asset, double size, Color color) => + SizedBox.square(key: ValueKey(asset), dimension: size); + +final Finder _share = find.byKey( + const ValueKey(PersonalizationIcons.share), +); +final Finder _cross = find.byKey( + const ValueKey(PersonalizationIcons.cross), +); + +Widget _host(Widget child) => MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, child: child), + ), + ), +); + +/// Lets [time] pass in 100 ms frames. +Future _wait(WidgetTester tester, Duration time) async { + const frame = Duration(milliseconds: 100); + for (var left = time; left > Duration.zero; left -= frame) { + await tester.pump(left < frame ? left : frame); + } +} + +/// Lets a viewer route come in or go away. +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pump(); +} + +void main() { + late _FakeHostApi api; + late _Server server; + late PersonalizationSdk sdk; + + setUp(() { + StoriesSeenStore.instance = StoriesSeenStore(); + api = _FakeHostApi(); + server = _Server((_) => (status: 200, body: _feed())); + sdk = PersonalizationSdk(api: api, shopId: 'shop'); + StoriesApiV3.domain = 'app.example'; + StoriesApiV3.send = server.send; + }); + + tearDown(() => StoriesApiV3.domain = null); + + Future bar(WidgetTester tester) async { + await tester.pumpWidget( + _host(PersonalizationStories(code: _code, sdk: sdk, iconBuilder: _icon)), + ); + await tester.pump(); + await tester.pump(); + } + + Future open(WidgetTester tester, String label) async { + await tester.tap(find.text(label)); + await _settle(tester); + } + + testWidgets('the feed and the events go to v3, also for product slides', ( + tester, + ) async { + await bar(tester); + expect(server.gets, [ + '/api/v3/storefront/stories/$_code?shop_id=shop&did=did-1', + ]); + await open(tester, 'Products'); + expect(find.text('Product 39_0'), findsOneWidget); + expect(server.events, ['view 39/39_0']); + expect(api.bridge, isEmpty, reason: 'nothing through the old tracking'); + expect(api.sources, ['stories/$_code']); + }); + + testWidgets('share: the campaign link, a pause until the sheet closes', ( + tester, + ) async { + await bar(tester); + await open(tester, 'Products'); + // Left of the cross, 8 apart, the same 32 box. + final share = tester.getRect(_share); + final cross = tester.getRect(_cross); + expect(share.size, const Size(32, 32)); + expect(cross.left - share.right, 8); + expect(share.top, cross.top); + + await tester.tap(_share); + await tester.pump(); + expect(api.shared, ['$_link39&r46_slide=39_0']); + expect(api.anchors.single, share); + expect(server.events, ['view 39/39_0', 'share 39/39_0']); + await tester.tap(_share); + expect(api.shared, hasLength(1), reason: 'one sheet at a time'); + + await _wait(tester, const Duration(seconds: 3)); + expect(find.text('Product 39_0'), findsOneWidget, reason: 'paused'); + api.sheet!.complete(); + await _wait(tester, const Duration(milliseconds: 1100)); + expect(find.text('Product 39_1'), findsOneWidget, reason: 'goes on'); + }); + + testWidgets('shareUrlTransform changes the shared link, not the event', ( + tester, + ) async { + await tester.pumpWidget( + _host( + PersonalizationStoriesV3( + shareUrlTransform: (url) => + url.replaceFirst('https://', 'demoapp://'), + child: PersonalizationStories( + code: _code, + sdk: sdk, + iconBuilder: _icon, + ), + ), + ), + ); + await tester.pump(); + await tester.pump(); + await open(tester, 'Products'); + await tester.tap(_share); + await tester.pump(); + expect(api.shared, [ + 'demoapp://shop.example/?r46_story=39&r46_slide=39_0', + ]); + expect(server.events, ['view 39/39_0', 'share 39/39_0']); + }); + + testWidgets('a hold on the button does not hold the slide', (tester) async { + await bar(tester); + await open(tester, 'Products'); + final gesture = await tester.startGesture(tester.getCenter(_share)); + await _wait(tester, const Duration(milliseconds: 1500)); + expect(find.text('Product 39_1'), findsOneWidget, reason: 'no hold pause'); + await gesture.up(); + await tester.pump(); + expect(api.shared, [ + '$_link39&r46_slide=39_1', + ], reason: 'a long press is a press, on the slide it is on'); + }); + + testWidgets('own slide links; no button when sharing is off', (tester) async { + await bar(tester); + await open(tester, 'Private'); + expect(find.text('Product 50'), findsOneWidget); + expect(_share, findsNothing); + expect(_cross, findsOneWidget); + Navigator.of(tester.element(_cross)).pop(); + await _settle(tester); + + await open(tester, 'Media'); + await tester.tap(_share); + await tester.pump(); + expect(api.shared, [ + 'https://shop.example/?r46_story=40&r46_slide=37', + ]); + }); + + testWidgets('the own value wins over the global one', (tester) async { + StoriesApiV3.domain = 'global.example'; + await tester.pumpWidget( + _host( + PersonalizationStoriesV3( + apiV3Domain: 'own.example', + child: PersonalizationStories( + code: _code, + sdk: sdk, + iconBuilder: _icon, + ), + ), + ), + ); + await tester.pump(); + await tester.pump(); + await open(tester, 'Products'); + await tester.tap(_share); + await tester.pump(); + expect(server.events, ['view 39/39_0', 'share 39/39_0']); + expect(server.hosts.toSet(), {'own.example'}); + }); + + testWidgets('a block without a value takes the old API next to a v3 one', ( + tester, + ) async { + StoriesApiV3.domain = null; + // The old feed with links: the old API never sends them, and still no button. + api.bridgeFeed = jsonEncode( + (jsonDecode(_feed(only: ['40'])) as Map)['payload'], + ); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 400, + child: Column( + children: [ + PersonalizationStories( + code: _code, + sdk: sdk, + iconBuilder: _icon, + ), + PersonalizationStoriesV3( + apiV3Domain: 'own.example', + child: PersonalizationStories( + code: _code, + sdk: sdk, + iconBuilder: _icon, + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pump(); + await tester.pump(); + expect(server.gets, hasLength(1), reason: 'only the second block'); + expect(find.text('Media'), findsNWidgets(2)); + expect(find.text('Products'), findsOneWidget); + + await tester.tap(find.text('Media').first); + await _settle(tester); + expect(find.text('Product 37'), findsOneWidget); + expect(_share, findsNothing, reason: 'the old API has no sharing'); + expect(api.bridge, ['view 40/37']); + expect(server.events, isEmpty); + Navigator.of(tester.element(_cross)).pop(); + await _settle(tester); + + await tester.tap(find.text('Products')); + await _settle(tester); + expect(_share, findsOneWidget); + expect(server.events, ['view 39/39_0']); + expect(api.bridge, ['view 40/37']); + }); + + group('handleLink', () { + const link = + 'https://demo.example/promo?utm=1&r46_stories=$_code' + '&r46_story=40&r46_slide=38'; + + BuildContext placeholder(WidgetTester tester) => + tester.element(find.byType(Placeholder)); + + testWidgets('false for other links and without apiV3Domain', ( + tester, + ) async { + await tester.pumpWidget(_host(const Placeholder())); + final context = placeholder(tester); + expect( + PersonalizationStoriesV3.handleLink( + context, + 'https://shop.example/', + sdk: sdk, + ), + isFalse, + ); + expect( + PersonalizationStoriesV3.handleLink( + context, + '?r46_stories=$_code', + sdk: sdk, + ), + isFalse, + ); + StoriesApiV3.domain = null; + expect( + PersonalizationStoriesV3.handleLink(context, link, sdk: sdk), + isFalse, + ); + await tester.pump(); + expect(server.gets, isEmpty); + }); + + testWidgets('its own apiV3Domain without the global one', (tester) async { + StoriesApiV3.domain = null; + server.answer = (_) => + (status: 200, body: _feed(start40: 1, only: ['40'])); + await tester.pumpWidget(_host(const Placeholder())); + expect( + PersonalizationStoriesV3.handleLink( + placeholder(tester), + link, + sdk: sdk, + apiV3Domain: 'own.example', + iconBuilder: _icon, + shareUrlTransform: (url) => + url.replaceFirst('https://', 'demoapp://'), + ), + isTrue, + ); + await _settle(tester); + expect(find.text('Product 38'), findsOneWidget); + expect(server.events, ['view 40/38', 'shared_open 40/38']); + expect(server.hosts.toSet(), {'own.example'}); + // handleLink hands its transform to the viewer. + await tester.tap(_share); + await tester.pump(); + expect(api.shared, [ + 'demoapp://shop.example/?r46_story=40&r46_slide=38', + ]); + Navigator.of( + tester.element(find.byType(PersonalizationStoryViewer)), + ).pop(); + await _settle(tester); + }); + + testWidgets('opens the campaign at the link slide, shared_open once', ( + tester, + ) async { + server.answer = (_) => + (status: 200, body: _feed(start40: 1, only: ['40'])); + await tester.pumpWidget(_host(const Placeholder())); + final context = placeholder(tester); + expect( + PersonalizationStoriesV3.handleLink( + context, + link, + sdk: sdk, + iconBuilder: _icon, + ), + isTrue, + ); + await _settle(tester); + expect(server.gets, [ + '/api/v3/storefront/stories/$_code/story/40' + '?shop_id=shop&did=did-1&slide_id=38', + ]); + expect(find.text('Product 38'), findsOneWidget, reason: 'start_position'); + expect(server.events, ['view 40/38', 'shared_open 40/38']); + + // The same link while its viewer is open: nothing new. + expect( + PersonalizationStoriesV3.handleLink(context, link, sdk: sdk), + isTrue, + ); + await _settle(tester); + expect(server.gets, hasLength(1)); + + await _wait(tester, const Duration(milliseconds: 1100)); + await _settle(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect( + server.events.where((e) => e.startsWith('shared_open')), + hasLength(1), + ); + + expect( + PersonalizationStoriesV3.handleLink(context, link, sdk: sdk), + isTrue, + ); + await _settle(tester); + expect(server.gets, hasLength(2), reason: 'closed: the link opens again'); + }); + + testWidgets('a product campaign opens at the link slide, though the server ' + 'starts at the first', (tester) async { + // The server does not know virtual slides: `slide_id=39_1` still answers + // `start_position: 0`. + server.answer = (_) => (status: 200, body: _feed(only: ['39'])); + await tester.pumpWidget(_host(const Placeholder())); + expect( + PersonalizationStoriesV3.handleLink( + placeholder(tester), + 'demoapp://demo.example/?r46_stories=$_code&r46_story=39' + '&r46_slide=39_1', + sdk: sdk, + iconBuilder: _icon, + ), + isTrue, + ); + await _settle(tester); + expect(find.text('Product 39_1'), findsOneWidget); + expect(server.events, ['view 39/39_1', 'shared_open 39/39_1']); + // Its "Share" carries the slide again. + await tester.tap(_share); + await tester.pump(); + expect(api.shared, ['$_link39&r46_slide=39_1']); + }); + + testWidgets('a link slide missing from the answer — start_position', ( + tester, + ) async { + server.answer = (_) => + (status: 200, body: _feed(start40: 1, only: ['40'])); + await tester.pumpWidget(_host(const Placeholder())); + expect( + PersonalizationStoriesV3.handleLink( + placeholder(tester), + 'https://demo.example/?r46_stories=$_code&r46_story=40&r46_slide=99', + sdk: sdk, + iconBuilder: _icon, + ), + isTrue, + ); + await _settle(tester); + expect(find.text('Product 38'), findsOneWidget); + expect(server.events, ['view 40/38', 'shared_open 40/38']); + }); + + testWidgets('a failed load reaches onError and shows nothing', ( + tester, + ) async { + server.answer = (_) => ( + status: 404, + body: '{"status":"fail","message":"Resource not found"}', + ); + await tester.pumpWidget(_host(const Placeholder())); + final errors = []; + expect( + PersonalizationStoriesV3.handleLink( + placeholder(tester), + link, + sdk: sdk, + onError: errors.add, + ), + isTrue, + ); + await _settle(tester); + expect(errors.single, isA()); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(server.events, isEmpty); + }); + + testWidgets('closes the open viewer before showing its campaign', ( + tester, + ) async { + await bar(tester); + await open(tester, 'Products'); + expect(find.text('Product 39_0'), findsOneWidget); + server.answer = (_) => + (status: 200, body: _feed(start40: 1, only: ['40'])); + expect( + PersonalizationStoriesV3.handleLink( + tester.element(find.byType(PersonalizationStories)), + link, + sdk: sdk, + ), + isTrue, + ); + await _settle(tester); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + expect(find.text('Product 38'), findsOneWidget); + expect(find.text('Product 39_0'), findsNothing); + }); + }); +} diff --git a/test/ui/stories_text_block_position_test.dart b/test/ui/stories_text_block_position_test.dart new file mode 100644 index 0000000..43b237c --- /dev/null +++ b/test/ui/stories_text_block_position_test.dart @@ -0,0 +1,177 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/components/personalization_story_poll.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; +import 'package:rees46_sdk/src/v3/personalization_v3.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_poll.dart'; + +/// A transport that never answers: the card only has to be drawn. +class _Transport implements StoryPollsTransport { + @override + Future answerMiniPoll( + String code, + Map body, + ) => Completer().future; + + @override + Future review(StoryPollType kind, Map body) => + Completer().future; +} + +Map _text(String text, Object? yOffset) => { + 'type': 'text_block', + 'text_input': text, + 'y_offset': yOffset, +}; + +Map _poll(Object? yOffset) => { + 'type': 'poll', + 'poll_type': 'nps', + 'y_offset': yOffset, + 'poll': {'code': 'nps', 'question': 'How likely?'}, +}; + +/// One story of one slide without media. +List _stories(List> elements) => + StoriesBlock.fromJson({ + 'id': 1, + 'stories': >[ + { + 'id': 40, + 'name': 'Story', + 'avatar': '', + 'slides': >[ + { + 'id': '38', + 'type': 'image', + 'background': '', + 'duration': 10, + 'elements': elements, + }, + ], + }, + ], + }).stories; + +Widget _icon(BuildContext context, String asset, double size, Color color) => + SizedBox.square(key: ValueKey(asset), dimension: size); + +/// The phone: 402 × 874, status bar 50, home indicator 34. +const Size _screen = Size(402, 874); +const double _statusBar = 50; +const double _homeIndicator = 34; + +/// Top of the place for slide blocks: the status bar, then the header at 16 and 8 below. +const double _areaTop = + _statusBar + 16 + PersonalizationStoryNavigation.height + 8; + +/// Bottom of that place on a slide without buttons and products: 16 above the bar. +const double _areaBottom = 874 - _homeIndicator - 16; + +Future _open(WidgetTester tester, List stories) async { + tester.view + ..physicalSize = _screen * 3 + ..devicePixelRatio = 3 + ..padding = const FakeViewPadding( + top: _statusBar * 3, + bottom: _homeIndicator * 3, + ) + ..viewPadding = const FakeViewPadding( + top: _statusBar * 3, + bottom: _homeIndicator * 3, + ); + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => Center( + child: GestureDetector( + onTap: () => Navigator.of(context).push( + PersonalizationStoryViewer.route( + PersonalizationStoriesV3( + apiV3Domain: 'app.example', + pollsTransport: _Transport(), + child: PersonalizationStoryViewer( + stories: stories, + iconBuilder: _icon, + ), + ), + ), + ), + child: const Text('open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pump(); +} + +Rect _block(WidgetTester tester, String text) => tester.getRect( + find.ancestor( + of: find.text(text), + matching: find.byType(PersonalizationStoryTextBlock), + ), +); + +void main() { + setUp(() => StoryPollStore.instance = StoryPollStore()); + + testWidgets('text block: y_offset of the whole slide, then inside the place ' + 'between the header and the bottom', (tester) async { + await _open( + tester, + _stories(>[ + _text('none', null), + _text('not a number', 'NaN'), + _text('five', 5), + _text('half', 50), + _text('ninety-five', '95'), + ]), + ); + final header = tester.getRect(find.byType(PersonalizationStoryNavigation)); + + // None or not a number — 0: at the top of the place, under the header. + expect(_block(tester, 'none').top, _areaTop); + expect(_block(tester, 'not a number').top, _areaTop); + + // 5% of the slide is under the status bar and the header: moved down to the place. + final five = _block(tester, 'five'); + expect(_screen.height * 0.05, lessThan(header.bottom)); + expect(five.top, _areaTop); + expect(five.top, greaterThan(header.bottom), reason: 'not on the header'); + + // 50% of the whole slide, system bars included. + expect(_block(tester, 'half').top, _screen.height / 2); + + // 95% does not fit: the bottom stays at the bottom of the place. + final last = _block(tester, 'ninety-five'); + expect(last.bottom, _areaBottom); + expect(last.top, lessThan(_screen.height * 0.95)); + + // Sides stay as they were. + expect((last.left, last.right), (16, _screen.width - 16)); + }); + + testWidgets('a text block and a poll with one y_offset stand at one height', ( + tester, + ) async { + for (final offset in [5, 30, 50]) { + await _open( + tester, + _stories(>[_text('text', offset), _poll(offset)]), + ); + final card = tester.getRect(find.byType(PersonalizationStoryPoll)); + expect(_block(tester, 'text').top, card.top, reason: 'y_offset $offset'); + Navigator.of(tester.element(find.text('open'))).pop(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pump(); + } + }); +} diff --git a/test/v3_gate_test.dart b/test/v3_gate_test.dart new file mode 100644 index 0000000..ae20edf --- /dev/null +++ b/test/v3_gate_test.dart @@ -0,0 +1,255 @@ +// The v3 gate: popups of the new builder and stories over API v3 are reachable only +// through `src/v3/personalization_v3.dart` — not from the package barrel and not from +// the kit barrel it exports. +// +// Dart has no reflection in Flutter tests, so the export namespaces are read from the +// sources: export directives with their show/hide, parts, and the public top-level +// declarations of each file (dart format puts those at column 0). + +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +const String _root = 'lib/rees46_sdk.dart'; +const String _kit = 'lib/src/ui/personalization_ui.dart'; +const String _v3 = 'lib/src/v3/personalization_v3.dart'; + +/// What the v3 gate gives the demo. +const Set _v3Names = { + 'PopupsV3', + 'PersonalizationPopupsV3', + 'PersonalizationScreenObserver', + 'PersonalizationStoriesV3', + 'StoryShareV3', + 'StorySlideShareV3', + 'StoryPollType', + 'StoryMiniPollKind', + 'StoryPollOption', + 'StoryPollBand', + 'StoryPollAnswer', + 'StoryPollResults', + 'StoryPollLabels', + 'StoryPollElement', + 'StoryPollsTransport', + 'StoryPollReply', +}; + +/// v3 internals no barrel exports. +const Set _internal = { + 'StoriesV3Scope', + 'StoriesV3Options', + 'StoriesApiV3', + 'StoriesPollsApi', + 'PopupsV3Engine', + 'PopupsV3Hooks', +}; + +/// Members and parameters of v3 that kit classes must not carry. +const Set _v3Members = { + 'apiV3Domain', + 'ownApiV3Domain', + 'pollsTransport', + 'shareUrlTransform', + 'handleLink', + 'pollReanswerText', + 'pollSubmitText', + 'pollErrorText', + 'shareLabel', + 'shareUrl', + 'shareable', + 'popups', +}; + +final RegExp _export = RegExp(r"^export\s+'([^']+)'([^;]*);", multiLine: true); +final RegExp _part = RegExp(r"^part\s+'([^']+)';", multiLine: true); +final RegExp _combinator = RegExp( + r'\b(show|hide)\b([^]*?)(?=\b(?:show|hide)\b|$)', +); +final RegExp _type = RegExp( + r'^(?:(?:abstract|sealed|final|base|interface|mixin)\s+)*' + r'(?:class|enum|mixin|typedef|extension(?:\s+type)?)\s+([A-Za-z]\w*)', + multiLine: true, +); +final RegExp _function = RegExp( + r'^(?!(?:import|export|part|library|class|enum|mixin|typedef|extension|abstract|' + r'sealed|final|base|interface)\b)[A-Za-z][\w<>?, ]*[ \t]+(?:get[ \t]+)?' + r'([A-Za-z]\w*)[ \t]*[(=]', + multiLine: true, +); +final RegExp _variable = RegExp( + r'^(?:const|final|var|late)[ \t]+(?:[\w<>?, ]+[ \t]+)?([A-Za-z]\w*)[ \t]*[=;]', + multiLine: true, +); + +String _resolve(String from, String uri) { + if (uri.startsWith('package:rees46_sdk/')) { + return 'lib/${uri.substring('package:rees46_sdk/'.length)}'; + } + return File(from).parent.uri + .resolve(uri) + .toFilePath() + .replaceFirst('${Directory.current.path}/', ''); +} + +/// Public top-level names [file] and its parts declare. +Set _declared(String file) { + final source = File(file).readAsStringSync(); + return { + for (final pattern in [_type, _function, _variable]) + for (final match in pattern.allMatches(source)) match.group(1)!, + for (final part in _part.allMatches(source)) + ..._declared(_resolve(file, part.group(1)!)), + }; +} + +/// The export namespace of the library [file]. +Set _namespace(String file) { + final source = File(file).readAsStringSync(); + final names = _declared(file); + for (final export in _export.allMatches(source)) { + final uri = export.group(1)!; + if (uri.startsWith('dart:') || + (uri.startsWith('package:') && + !uri.startsWith('package:rees46_sdk/'))) { + continue; + } + var exported = _namespace(_resolve(file, uri)); + for (final combinator in _combinator.allMatches(export.group(2)!)) { + final listed = combinator + .group(2)! + .split(',') + .map((name) => name.trim()) + .where((name) => name.isNotEmpty) + .toSet(); + exported = combinator.group(1) == 'show' + ? exported.intersection(listed) + : exported.difference(listed); + } + names.addAll(exported); + } + return names; +} + +/// Files reachable through the export directives of [file]. +Set _exportedFiles(String file) { + final source = File(file).readAsStringSync(); + return { + file, + for (final export in _export.allMatches(source)) + if (!export.group(1)!.startsWith('dart:')) + ..._exportedFiles(_resolve(file, export.group(1)!)), + }; +} + +/// Names the top-level class [name] in [file] declares: its members (two spaces in) +/// and the parameters of their signatures (four spaces in, one per line), comments and +/// bodies left out. +Set _declaredIn(String file, String name) { + final source = File(file).readAsStringSync(); + final start = RegExp( + r'^(?:(?:abstract|sealed|final|base|interface)\s+)*class\s+' + name + r'\b', + multiLine: true, + ).firstMatch(source); + expect(start, isNotNull, reason: '$name in $file'); + final body = source.substring( + start!.start, + source.indexOf('\n}\n', start.start), + ); + final member = RegExp( + r'^ (?:(?:static|final|const|late|factory)\s+)*(?:[\w<>?, ()]*?\s)?' + r'(?:get\s+|set\s+)?(\w+)\s*(?:=>|=|;|\(|\{)', + ); + final parameter = RegExp( + r'^ (?:required\s+)?(?:(?:this|super)\.(\w+)|[A-Za-z][\w<>?, ()]*\s(\w+))' + r'(?:\s*=\s*[^,]+)?,$', + ); + return { + for (final line in body.split('\n')) + if (!line.trimLeft().startsWith('//')) + for (final pattern in [member, parameter]) + for (final match in pattern.allMatches(line)) + match.group(1) ?? match.group(2)!, + }; +} + +void main() { + test('the reader sees the kit, the root and the gate', () { + final kit = _namespace(_kit); + expect( + kit, + containsAll([ + 'PersonalizationStories', + 'PersonalizationStoriesController', + 'PersonalizationStoryViewer', + 'Story', + 'StorySlide', + 'StoryElement', + 'PersonalizationButton', + ]), + ); + expect( + _namespace(_root), + containsAll(['REES46', 'PersonalizationSdk']), + ); + }); + + test('neither the package barrel nor the kit barrel exports v3', () { + for (final barrel in [_root, _kit]) { + final names = _namespace(barrel); + expect(names.intersection(_v3Names), isEmpty, reason: barrel); + expect(names.intersection(_internal), isEmpty, reason: barrel); + expect( + names.where((name) => name.contains('V3')), + isEmpty, + reason: barrel, + ); + expect( + _exportedFiles(barrel).where((file) => file.contains('popups_v3')), + isEmpty, + reason: barrel, + ); + } + }); + + test('the v3 gate exports v3 and no internals', () { + final names = _namespace(_v3); + expect(names, containsAll(_v3Names)); + expect(names.intersection(_internal), isEmpty); + }); + + test('kit classes carry no v3 members', () { + const classes = <(String, String)>[ + ( + 'lib/src/ui/widgets/personalization_stories.dart', + 'PersonalizationStories', + ), + ( + 'lib/src/ui/widgets/personalization_story_viewer.dart', + 'PersonalizationStoryViewer', + ), + ('lib/src/stories/stories_response.dart', 'Story'), + ('lib/src/stories/stories_response.dart', 'StorySlide'), + ('lib/src/personalization_sdk.dart', 'PersonalizationSdk'), + ]; + for (final (file, name) in classes) { + final declared = _declaredIn(file, name); + expect(declared, isNotEmpty, reason: name); + expect(declared.intersection(_v3Members), isEmpty, reason: name); + } + }); + + test('the docs of the package barrel do not mention v3', () { + for (final file in _exportedFiles(_root)) { + final lines = File(file).readAsLinesSync(); + for (var i = 0; i < lines.length; i++) { + final line = lines[i].trimLeft(); + if (!line.startsWith('///')) continue; + expect( + RegExp(r'\bv3\b', caseSensitive: false).hasMatch(line), + isFalse, + reason: '$file:${i + 1}: $line', + ); + } + } + }); +}