diff --git a/android/build.gradle.kts b/android/build.gradle.kts index 3c7b000..727e76e 100644 --- a/android/build.gradle.kts +++ b/android/build.gradle.kts @@ -87,7 +87,7 @@ android { dependencies { // REES46 Android SDK. - val rees46AndroidSdkVersion = "v2.38.0" + val rees46AndroidSdkVersion = "v2.39.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 acd45ca..635cfec 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 @@ -1,7 +1,9 @@ package com.rees46.rees46_flutter_sdk +import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent +import android.net.Uri import android.os.Bundle import android.os.SystemClock import com.rees46.rees46_flutter_sdk.pigeon.FlutterError @@ -29,6 +31,7 @@ import com.personalization.api.models.tracking.TrackingSource import com.personalization.api.models.tracking.TrackingSourceType import com.personalization.api.params.ProfileParams import com.personalization.api.params.SearchParams as NativeSearchParams +import com.personalization.SearchParams as LegacySearchParams import com.personalization.sdk.data.models.dto.notification.NotificationData import com.rees46.rees46_flutter_sdk.push.Rees46PushNotifier import com.rees46.rees46_flutter_sdk.push.Rees46ShopStore @@ -142,6 +145,7 @@ class Rees46FlutterSdkPlugin : stream = config.stream, autoSendPushToken = config.autoSendPushToken, needReInitialization = config.needReInitialization, + enableAutoPopupPresentation = config.enableAutoPopupPresentation, ) // F3: initialize (and register) the instance through the multi-instance // `Rees46` facade so it is reachable by shopId via Rees46.getInstance. @@ -326,15 +330,31 @@ class Rees46FlutterSdkPlugin : return } try { - val params = buildSearchParams(paramsJson) - sdk(shopId).searchManager.searchFull( - query = query, - searchParams = params, - onSearchFull = { response -> - callback(Result.success(Gson().toJson(response))) - }, - onError = { code, message -> - callback(Result.failure(FlutterError("search_failed", message ?: "error $code", null))) + // The raw, deprecated SDK.search entry point rather than the typed + // searchManager.searchFull: up to android-sdk v2.38.0 the typed SearchFullResponse and + // Product had no `filters`, `industrial_filters`, `oldprice`, `oldprice_formatted`, + // `discount` or `discount_formatted`, so Gson dropped them before they reached Dart, + // and the results screen needs the facets and the old price. The raw entry point + // returns the server JSON as is. + // TODO: v2.39.0, which this plugin now pins, has those fields. Switch to + // sdk(shopId).searchManager.searchFull(query, NativeSearchParams, …) with + // Gson().toJson(response), as searchInstant does, and move the params builder to + // NativeSearchParams — after checking against a live shop that the typed response + // carries everything the results screen reads. + val params = buildLegacySearchParams(paramsJson) + @Suppress("DEPRECATION") + sdk(shopId).search( + query, + LegacySearchParams.TYPE.FULL, + params, + object : OnApiCallbackListener() { + override fun onSuccess(response: JSONObject?) { + callback(Result.success(response?.toString() ?: "{}")) + } + + override fun onError(code: Int, msg: String?) { + callback(Result.failure(FlutterError("search_failed", msg ?: "error $code", null))) + } }, ) } catch (t: Throwable) { @@ -475,6 +495,71 @@ class Rees46FlutterSdkPlugin : } } + override fun getStories(code: String, shopId: String?, callback: (Result) -> Unit) { + if (code.isBlank()) { + callback(Result.failure(FlutterError("bad_args", "code is required", null))) + return + } + try { + // The public raw entry point: the listener gets the server JSON as is, the same payload + // the iOS bridge hands over, so Dart parses one shape. The typed loader + // (storiesManager.loadStories) is internal to the SDK module. + sdk(shopId).stories( + code, + object : OnApiCallbackListener() { + override fun onSuccess(response: JSONObject?) { + callback(Result.success(response?.toString() ?: "{}")) + } + + override fun onError(code: Int, msg: String?) { + callback(Result.failure(FlutterError("get_stories_failed", msg ?: "error $code", null))) + } + }, + ) + } catch (t: Throwable) { + callback(Result.failure(FlutterError("get_stories_failed", t.message, null))) + } + } + + override fun openUrl(url: String, callback: (Result) -> Unit) { + val uri = Uri.parse(url) + if (url.isBlank() || uri.scheme.isNullOrEmpty()) { + callback(Result.success(false)) + return + } + // The activity when there is one: from the application context a new task is required. + val activity = activityBinding?.activity + val intent = Intent(Intent.ACTION_VIEW, uri) + if (activity == null) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + try { + (activity ?: applicationContext).startActivity(intent) + callback(Result.success(true)) + } catch (e: ActivityNotFoundException) { + callback(Result.success(false)) + } + } + + // region stories viewer (UI kit) + + override fun getStoriesSeen(shop: String): Map> = + StoriesSeenStore.read(applicationContext, shop) + + override fun setStorySlideSeen(shop: String, storyId: String, slideId: String) = + StoriesSeenStore.add(applicationContext, shop, storyId, slideId) + + override fun getCacheDirectory(): String = applicationContext.cacheDir.absolutePath + + // The audio session calls are iOS-only. On Android video_player plays with + // `mixWithOthers: true` and so never requests the audio focus: a muted video leaves the + // user's music alone, and there is no session to restore. + override fun beginStoriesAudio() = Unit + + override fun updateStoriesAudio(muted: Boolean) = Unit + + override fun endStoriesAudio() = Unit + + // endregion + override fun getSid(shopId: String?): String = sdk(shopId).getSid() override fun getDid(shopId: String?): String? = sdk(shopId).getDid() @@ -892,8 +977,14 @@ class Rees46FlutterSdkPlugin : } -private fun buildSearchParams(paramsJson: String?): NativeSearchParams { - val params = NativeSearchParams() +/** + * Search parameters from the bridge JSON, on the legacy params class the raw search entry point + * takes. Keys come from the current parameter enum — both classes implement the same interface — + * so the wire names stay identical. + */ +@Suppress("DEPRECATION") +private fun buildLegacySearchParams(paramsJson: String?): LegacySearchParams { + val params = LegacySearchParams() if (paramsJson.isNullOrBlank()) return params val json = JSONObject(paramsJson) json.optInt("limit").takeIf { it > 0 } @@ -924,6 +1015,17 @@ private fun buildSearchParams(paramsJson: String?): NativeSearchParams { ?.let { params.put(NativeSearchParams.Parameter.COLORS, it) } jsonArrayToStringArray(json.optJSONArray("fashion_sizes")) ?.let { params.put(NativeSearchParams.Parameter.FASHION_SIZES, it) } + json.optJSONObject("filters")?.let { facets -> + val searchFilters = NativeSearchParams.SearchFilters() + var any = false + facets.keys().forEach { name -> + jsonArrayToStringArray(facets.optJSONArray(name))?.let { + searchFilters.put(name, it) + any = true + } + } + if (any) params.put(NativeSearchParams.Parameter.FILTERS, searchFilters.toString()) + } return params } diff --git a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesSeenStore.kt b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesSeenStore.kt new file mode 100644 index 0000000..19a2d7b --- /dev/null +++ b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/StoriesSeenStore.kt @@ -0,0 +1,40 @@ +package com.rees46.rees46_flutter_sdk + +import android.content.Context +import android.content.SharedPreferences + +/** + * The slides of the UI kit's stories (V2) the user has seen, per shop: one preferences file + * per shop, a key per story id holding the set of seen slide ids. It survives app restarts, so a + * story reopens at its first unseen slide and its cover keeps the seen segments. + * + * The plugin's own store, not the native SDK's: the Flutter viewer is drawn in Dart, and the + * native SDK keeps no such state for it. + */ +internal object StoriesSeenStore { + + private const val PREFS_PREFIX = "rees46_flutter_stories_seen_" + + /** Seen slide ids by story id for [shop]; empty when nothing was seen yet. */ + fun read(context: Context, shop: String): Map> = + prefs(context, shop).all.mapNotNull { (storyId, value) -> + (value as? Set<*>)?.filterIsInstance()?.let { storyId to it.sorted() } + }.toMap() + + /** Adds [slideId] to the seen slides of [storyId] for [shop]. */ + fun add(context: Context, shop: String, storyId: String, slideId: String) { + val prefs = prefs(context, shop) + // The returned set must not be modified in place: copy it. + val seen = prefs.getStringSet(storyId, null).orEmpty() + if (slideId in seen) return + prefs.edit().putStringSet(storyId, seen + slideId).apply() + } + + // The shop id becomes part of a file name: anything but letters, digits, `-` and `_` is + // replaced. + private fun prefs(context: Context, shop: String): SharedPreferences = + context.getSharedPreferences( + PREFS_PREFIX + shop.replace(Regex("[^A-Za-z0-9_-]"), "_"), + Context.MODE_PRIVATE, + ) +} 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 9456937..b9d3f24 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 @@ -614,6 +614,51 @@ interface PersonalizationHostApi { * Dart layer parses the result into [CollectionResponse]. */ fun getCollection(collectionId: String, shopId: String?, callback: (Result) -> Unit) + /** + * Returns the stories block [code] (`stories/{code}`) as the server's JSON string, + * untouched: `{ "id": ..., "stories": [...], "settings": {...} }`. Both platforms hand + * over the same raw payload, so Dart parses one shape. + * Dart layer parses the result into [StoriesBlock]. + */ + fun getStories(code: String, shopId: String?, callback: (Result) -> Unit) + /** + * Opens [url] with the system handler (browser or the app that claims the link). + * Returns false when nothing could open it. + */ + fun openUrl(url: String, 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 + * survives app restarts. The inner lists are untyped on purpose: the channel + * hands nested lists over as `List`, and a typed `List` here + * generates a lazy cast that throws on the first read. + */ + fun getStoriesSeen(shop: String): Map> + /** Records [slideId] of story [storyId] as seen for [shop]. */ + fun setStorySlideSeen(shop: String, storyId: String, slideId: String) + /** + * The app's cache directory: Android `Context.cacheDir`, iOS `Library/Caches`. The + * stories viewer keeps its video cache under it. + */ + fun getCacheDirectory(): String + /** + * Remembers the app's audio session before the stories viewer plays its first video, + * so [endStoriesAudio] can put it back. iOS only; a no-op on Android, where a muted + * video never takes the audio focus (`mixWithOthers`). + */ + fun beginStoriesAudio() + /** + * While the viewer plays video: muted — the `ambient` category, which never + * interrupts other apps' audio; unmuted — `playback`. Also starts watching the + * hardware volume (see [PersonalizationStoriesFlutterApi.onStoriesVolumeUp]). iOS + * only; a no-op on Android. + */ + fun updateStoriesAudio(muted: Boolean) + /** + * The viewer closed: restores the session saved by [beginStoriesAudio] and stops + * watching the volume. iOS only; a no-op on Android. + */ + fun endStoriesAudio() /** * Routes a push to the shop it belongs to (payload `shop_id`) and tracks it * via the native `REES46.handlePush`. [event] is the index of the Dart @@ -1054,6 +1099,149 @@ interface PersonalizationHostApi { channel.setMessageHandler(null) } } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStories$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val codeArg = args[0] as String + val shopIdArg = args[1] as String? + api.getStories(codeArg, shopIdArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(PersonalizationApiPigeonUtils.wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openUrl$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val urlArg = args[0] as String + api.openUrl(urlArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(PersonalizationApiPigeonUtils.wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(PersonalizationApiPigeonUtils.wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStoriesSeen$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val shopArg = args[0] as String + val wrapped: List = try { + listOf(api.getStoriesSeen(shopArg)) + } catch (exception: Throwable) { + PersonalizationApiPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.setStorySlideSeen$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val shopArg = args[0] as String + val storyIdArg = args[1] as String + val slideIdArg = args[2] as String + val wrapped: List = try { + api.setStorySlideSeen(shopArg, storyIdArg, slideIdArg) + listOf(null) + } catch (exception: Throwable) { + PersonalizationApiPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCacheDirectory$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + val wrapped: List = try { + listOf(api.getCacheDirectory()) + } catch (exception: Throwable) { + PersonalizationApiPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.beginStoriesAudio$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + val wrapped: List = try { + api.beginStoriesAudio() + listOf(null) + } catch (exception: Throwable) { + PersonalizationApiPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.updateStoriesAudio$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val mutedArg = args[0] as Boolean + val wrapped: List = try { + api.updateStoriesAudio(mutedArg) + listOf(null) + } catch (exception: Throwable) { + PersonalizationApiPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.endStoriesAudio$separatedMessageChannelSuffix", codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + val wrapped: List = try { + api.endStoriesAudio() + listOf(null) + } catch (exception: Throwable) { + PersonalizationApiPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } run { val channel = BasicMessageChannel(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.handlePush$separatedMessageChannelSuffix", codec) if (api != null) { @@ -1421,3 +1609,38 @@ class PersonalizationFlutterApi(private val binaryMessenger: BinaryMessenger, pr } } } +/** + * Native events of the stories viewer. Separate from [PersonalizationFlutterApi]: the + * push dispatcher owns that channel, the UI kit owns this one. + * + * Generated class from Pigeon that represents Flutter messages that can be called from Kotlin. + */ +class PersonalizationStoriesFlutterApi(private val binaryMessenger: BinaryMessenger, private val messageChannelSuffix: String = "") { + companion object { + /** The codec used by PersonalizationStoriesFlutterApi. */ + val codec: MessageCodec by lazy { + PersonalizationApiPigeonCodec() + } + } + /** + * The hardware volume went up while the viewer plays video (iOS: the audio session's + * `outputVolume` grew). Android delivers the volume key to Flutter itself. + */ + fun onStoriesVolumeUp(callback: (Result) -> Unit) +{ + val separatedMessageChannelSuffix = if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" + val channelName = "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationStoriesFlutterApi.onStoriesVolumeUp$separatedMessageChannelSuffix" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(null) { + if (it is List<*>) { + if (it.size > 1) { + callback(Result.failure(FlutterError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(PersonalizationApiPigeonUtils.createConnectionError(channelName))) + } + } + } +} diff --git a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/push/Rees46ShopStore.kt b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/push/Rees46ShopStore.kt index 72e31ac..e5292d7 100644 --- a/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/push/Rees46ShopStore.kt +++ b/android/src/main/kotlin/com/rees46/rees46_flutter_sdk/push/Rees46ShopStore.kt @@ -35,7 +35,8 @@ internal object Rees46ShopStore { .put("apiDomain", c.apiDomain) .put("stream", c.stream) .put("autoSendPushToken", c.autoSendPushToken) - .put("needReInitialization", c.needReInitialization), + .put("needReInitialization", c.needReInitialization) + .put("enableAutoPopupPresentation", c.enableAutoPopupPresentation), ) } prefs(context).edit().putString(KEY_CONFIGS, array.toString()).apply() @@ -56,6 +57,7 @@ internal object Rees46ShopStore { stream = obj.optString("stream", "android"), autoSendPushToken = obj.optBoolean("autoSendPushToken", true), needReInitialization = obj.optBoolean("needReInitialization", false), + enableAutoPopupPresentation = obj.optBoolean("enableAutoPopupPresentation", true), ) } } catch (t: Throwable) { diff --git a/assets/icons/angle-down.svg b/assets/icons/angle-down.svg new file mode 100644 index 0000000..36e2716 --- /dev/null +++ b/assets/icons/angle-down.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/angle-large-right.svg b/assets/icons/angle-large-right.svg new file mode 100644 index 0000000..f60a1c3 --- /dev/null +++ b/assets/icons/angle-large-right.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/angle-up.svg b/assets/icons/angle-up.svg new file mode 100644 index 0000000..f1d3774 --- /dev/null +++ b/assets/icons/angle-up.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/arrow-left.svg b/assets/icons/arrow-left.svg new file mode 100644 index 0000000..032dc9d --- /dev/null +++ b/assets/icons/arrow-left.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/arrow-rotate-cw.svg b/assets/icons/arrow-rotate-cw.svg new file mode 100644 index 0000000..d328573 --- /dev/null +++ b/assets/icons/arrow-rotate-cw.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/arrows-up-down.svg b/assets/icons/arrows-up-down.svg new file mode 100644 index 0000000..ca31ef5 --- /dev/null +++ b/assets/icons/arrows-up-down.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/icons/check-rosette-fill.svg b/assets/icons/check-rosette-fill.svg new file mode 100644 index 0000000..53c7432 --- /dev/null +++ b/assets/icons/check-rosette-fill.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/copy.svg b/assets/icons/copy.svg new file mode 100644 index 0000000..2bd37d3 --- /dev/null +++ b/assets/icons/copy.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/icons/cross-large.svg b/assets/icons/cross-large.svg new file mode 100644 index 0000000..1d2398c --- /dev/null +++ b/assets/icons/cross-large.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/cross.svg b/assets/icons/cross.svg new file mode 100644 index 0000000..9a3faaa --- /dev/null +++ b/assets/icons/cross.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/equalizer-horizontal.svg b/assets/icons/equalizer-horizontal.svg new file mode 100644 index 0000000..30ecf8a --- /dev/null +++ b/assets/icons/equalizer-horizontal.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/icons/grid-2x2-fill.svg b/assets/icons/grid-2x2-fill.svg new file mode 100644 index 0000000..90c3a67 --- /dev/null +++ b/assets/icons/grid-2x2-fill.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/grid-2x2.svg b/assets/icons/grid-2x2.svg new file mode 100644 index 0000000..1b587b2 --- /dev/null +++ b/assets/icons/grid-2x2.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/list-fill.svg b/assets/icons/list-fill.svg new file mode 100644 index 0000000..74bc51c --- /dev/null +++ b/assets/icons/list-fill.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/icons/list.svg b/assets/icons/list.svg new file mode 100644 index 0000000..936f41e --- /dev/null +++ b/assets/icons/list.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/icons/magnifier.svg b/assets/icons/magnifier.svg new file mode 100644 index 0000000..0678b51 --- /dev/null +++ b/assets/icons/magnifier.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/rosette.svg b/assets/icons/rosette.svg new file mode 100644 index 0000000..d215eff --- /dev/null +++ b/assets/icons/rosette.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/spacing-md.svg b/assets/icons/spacing-md.svg new file mode 100644 index 0000000..06cf362 --- /dev/null +++ b/assets/icons/spacing-md.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/speaker-off.svg b/assets/icons/speaker-off.svg new file mode 100644 index 0000000..c5a44f3 --- /dev/null +++ b/assets/icons/speaker-off.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/icons/speaker.svg b/assets/icons/speaker.svg new file mode 100644 index 0000000..ce0e662 --- /dev/null +++ b/assets/icons/speaker.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/star-fill.svg b/assets/icons/star-fill.svg new file mode 100644 index 0000000..b40c135 --- /dev/null +++ b/assets/icons/star-fill.svg @@ -0,0 +1,3 @@ + + + diff --git a/example/assets/uikit/backpack.jpg b/example/assets/uikit/backpack.jpg new file mode 100644 index 0000000..53d42e4 Binary files /dev/null and b/example/assets/uikit/backpack.jpg differ diff --git a/example/assets/uikit/bottle.jpg b/example/assets/uikit/bottle.jpg new file mode 100644 index 0000000..6a9b98a Binary files /dev/null and b/example/assets/uikit/bottle.jpg differ diff --git a/example/assets/uikit/headphones.jpg b/example/assets/uikit/headphones.jpg new file mode 100644 index 0000000..87a2977 Binary files /dev/null and b/example/assets/uikit/headphones.jpg differ diff --git a/example/assets/uikit/jacket.jpg b/example/assets/uikit/jacket.jpg new file mode 100644 index 0000000..3e39817 Binary files /dev/null and b/example/assets/uikit/jacket.jpg differ diff --git a/example/assets/uikit/loyalty_emblem.png b/example/assets/uikit/loyalty_emblem.png new file mode 100644 index 0000000..0354c3c Binary files /dev/null and b/example/assets/uikit/loyalty_emblem.png differ diff --git a/example/assets/uikit/loyalty_logo.png b/example/assets/uikit/loyalty_logo.png new file mode 100644 index 0000000..61f9e61 Binary files /dev/null and b/example/assets/uikit/loyalty_logo.png differ diff --git a/example/assets/uikit/loyalty_stripe.jpg b/example/assets/uikit/loyalty_stripe.jpg new file mode 100644 index 0000000..5f500f7 Binary files /dev/null and b/example/assets/uikit/loyalty_stripe.jpg differ diff --git a/example/assets/uikit/pegasus.jpg b/example/assets/uikit/pegasus.jpg new file mode 100644 index 0000000..e03fc4b Binary files /dev/null and b/example/assets/uikit/pegasus.jpg differ diff --git a/example/assets/uikit/sneakers.jpg b/example/assets/uikit/sneakers.jpg new file mode 100644 index 0000000..506d6e0 Binary files /dev/null and b/example/assets/uikit/sneakers.jpg differ diff --git a/example/assets/uikit/story_clock.gif b/example/assets/uikit/story_clock.gif new file mode 100644 index 0000000..eb5888c Binary files /dev/null and b/example/assets/uikit/story_clock.gif differ diff --git a/example/assets/uikit/sunglasses.jpg b/example/assets/uikit/sunglasses.jpg new file mode 100644 index 0000000..2764eab Binary files /dev/null and b/example/assets/uikit/sunglasses.jpg differ diff --git a/example/assets/uikit/watch.jpg b/example/assets/uikit/watch.jpg new file mode 100644 index 0000000..ea9d340 Binary files /dev/null and b/example/assets/uikit/watch.jpg differ diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index c348614..1b01487 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -11,12 +11,20 @@ PODS: - rees46_sdk (0.0.1): - Flutter - REES46 (= 3.35.0) + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS + - video_player_avfoundation (0.0.1): + - Flutter + - FlutterMacOS DEPENDENCIES: - Flutter (from `Flutter`) - integration_test (from `.symlinks/plugins/integration_test/ios`) - patrol (from `.symlinks/plugins/patrol/darwin`) - rees46_sdk (from `.symlinks/plugins/rees46_sdk/ios`) + - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) + - video_player_avfoundation (from `.symlinks/plugins/video_player_avfoundation/darwin`) SPEC REPOS: trunk: @@ -32,6 +40,10 @@ EXTERNAL SOURCES: :path: ".symlinks/plugins/patrol/darwin" rees46_sdk: :path: ".symlinks/plugins/rees46_sdk/ios" + shared_preferences_foundation: + :path: ".symlinks/plugins/shared_preferences_foundation/darwin" + video_player_avfoundation: + :path: ".symlinks/plugins/video_player_avfoundation/darwin" SPEC CHECKSUMS: CocoaAsyncSocket: 065fd1e645c7abab64f7a6a2007a48038fdc6a99 @@ -40,6 +52,8 @@ SPEC CHECKSUMS: patrol: cea8074f183a2a4232d0ebd10569ae05149ada42 REES46: a96357df1dbbef9a73d92961069290702334136d rees46_sdk: 312ba7a8088eb9cd0f5476ae3d6dd9b45c46b8c4 + shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb + video_player_avfoundation: 3453f792138786248960ca029747fcd9f318ef52 PODFILE CHECKSUM: b6e248ac4c1eff5807c8b044b39b8bc326af3f5f diff --git a/example/lib/app_theme_mode.dart b/example/lib/app_theme_mode.dart new file mode 100644 index 0000000..36ad8e6 --- /dev/null +++ b/example/lib/app_theme_mode.dart @@ -0,0 +1,25 @@ +import 'package:flutter/material.dart'; + +/// Colour scheme the demo forces on itself, so the kit's dark set can be checked +/// without leaving for the system settings. +/// +/// A plain [ValueNotifier] rather than a state manager: the example has no +/// dependency injection and the kit does not ask for one either — [MaterialApp] +/// listens to this, and the UI Kit screen's switch writes to it. +final ValueNotifier appThemeMode = ValueNotifier( + ThemeMode.system, +); + +/// Cycles system -> light -> dark -> system. +ThemeMode nextThemeMode(ThemeMode mode) => switch (mode) { + ThemeMode.system => ThemeMode.light, + ThemeMode.light => ThemeMode.dark, + ThemeMode.dark => ThemeMode.system, +}; + +/// Label of the switch: the mode it is in now, not the one it would go to. +String themeModeLabel(ThemeMode mode) => switch (mode) { + ThemeMode.system => 'Auto', + ThemeMode.light => 'Light', + ThemeMode.dark => 'Dark', +}; diff --git a/example/lib/main.dart b/example/lib/main.dart index 0a28a95..db9483c 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -3,7 +3,13 @@ import 'package:flutter/services.dart'; import 'package:flutter/foundation.dart'; import 'package:rees46_sdk/rees46_sdk.dart'; +import 'app_theme_mode.dart'; import 'multi_instance_pane.dart'; +// The kit is private until release: the theme comes from the src barrel. +// ignore: implementation_imports +import 'package:rees46_sdk/src/ui/personalization_ui.dart' + show PersonalizationTheme; +import 'ui_kit_pane.dart'; void main() => runApp(const App()); @@ -12,12 +18,32 @@ class App extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp( - title: 'REES46 Flutter SDK', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), + // themeMode is driven by the switch on the UI Kit screen, 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', + // The kit's theme extension rides on ThemeData: light and dark sets + // switch together with the app's brightness. + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue), + extensions: const >[ + PersonalizationTheme.light, + ], + ), + darkTheme: ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: Colors.blue, + brightness: Brightness.dark, + ), + extensions: const >[ + PersonalizationTheme.dark, + ], + ), + themeMode: mode, + home: const InitPage(), ), - home: const InitPage(), ); } } @@ -724,6 +750,16 @@ 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)', @@ -762,6 +798,17 @@ 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/ui_kit_pane.dart b/example/lib/ui_kit_pane.dart new file mode 100644 index 0000000..c903a10 --- /dev/null +++ b/example/lib/ui_kit_pane.dart @@ -0,0 +1,2011 @@ +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_svg/flutter_svg.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'; + +/// "UI Kit" screen — 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); +/// "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. +/// Mirror of the Android `UiKitPane` / iOS `UIKitShowcaseViewController` / +/// React Native `UiKitPane`. +/// +/// The kit does not draw SVG itself: every icon comes back through an +/// `iconBuilder`, rendered here with flutter_svg. Product data is static and +/// images are plain [ImageProvider]s — the kit does not fetch or format +/// anything. +class UiKitPane extends StatelessWidget { + const UiKitPane({super.key, required this.shopId}); + + /// Shop the Search and Stories tabs' widgets resolve their SDK instance by. + final String shopId; + + @override + Widget build(BuildContext context) { + return DefaultTabController( + length: 4, + child: Scaffold( + appBar: AppBar( + title: const Text('UI Kit'), + actions: const [_AppearanceSwitch()], + bottom: const TabBar( + tabs: [ + Tab(text: 'Components'), + Tab(text: 'Blocks'), + Tab(text: 'Search'), + Tab(text: 'Stories'), + ], + ), + ), + body: TabBarView( + children: [ + _Showcase(exhibits: _componentExhibits), + _Showcase(exhibits: _blockExhibits), + _SearchFlow(shopId: shopId), + _Showcase(exhibits: _storyExhibits(shopId)), + ], + ), + ), + ); + } +} + +/// Switch cycling the app between the system scheme, light and dark. +/// +/// It writes to [appThemeMode], which [MaterialApp] listens to, so the whole +/// demo repaints — the kit's components included, since their palette comes +/// from the theme extension attached to each [ThemeData]. +class _AppearanceSwitch extends StatelessWidget { + const _AppearanceSwitch(); + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: appThemeMode, + builder: (context, mode, _) => TextButton( + onPressed: () => appThemeMode.value = nextThemeMode(mode), + child: Text(themeModeLabel(mode)), + ), + ); + } +} + +/// The search flow as a host would wire it: the instant search field resolves the SDK by +/// shopId and searches on its own; submitting a phrase swaps it for the results screen, +/// whose back button returns. Taps on products and categories only show a snackbar — +/// navigation is the host's. +class _SearchFlow extends StatefulWidget { + const _SearchFlow({required this.shopId}); + + final String shopId; + + @override + State<_SearchFlow> createState() => _SearchFlowState(); +} + +class _SearchFlowState extends State<_SearchFlow> { + String? _query; + String? _sortBy; + String? _sortDir; + + void _say(String message) => ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(message))); + + @override + Widget build(BuildContext context) { + final query = _query; + if (query == null) { + return SingleChildScrollView( + padding: const EdgeInsets.all(16), + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + child: PersonalizationInstantSearchField( + shopId: widget.shopId, + placeholder: 'Search', + cancelText: 'Cancel', + recentLabel: 'Recent searches', + clearText: 'Clear', + moreText: 'more', + categoriesLabel: 'Categories', + productsLabel: 'Products', + onSubmit: (text) => setState(() => _query = text), + onProductTap: (product) => _say('Product: ${product.name}'), + onCategoryTap: (category) => _say('Category: ${category.name}'), + onError: (error) => _say('Search error: $error'), + iconBuilder: _icon, + ), + ); + } + return PersonalizationSearchResultsScreen( + shopId: widget.shopId, + query: query, + sortBy: _sortBy, + sortDir: _sortDir, + productActionText: 'Add to cart', + onBack: () => setState(() => _query = null), + onProductTap: (product) => _say('Product: ${product.name}'), + onProductAction: (product) => _say('Add to cart: ${product.name}'), + // No sort picker in the design file: cycle relevance → price ↑ → price ↓ on tap. + onSortTap: () => setState(() { + if (_sortBy == null) { + _sortBy = 'price'; + _sortDir = 'asc'; + } else if (_sortDir == 'asc') { + _sortDir = 'desc'; + } else { + _sortBy = null; + _sortDir = null; + } + }), + onError: (error) => _say('Search error: $error'), + iconBuilder: _icon, + ); + } +} + +class _Exhibit { + const _Exhibit(this.title, this.build); + + final String title; + final WidgetBuilder build; +} + +class _Showcase extends StatelessWidget { + const _Showcase({required this.exhibits}); + + final List<_Exhibit> exhibits; + + @override + Widget build(BuildContext context) { + final caption = Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ); + return ListView.separated( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 40), + itemCount: exhibits.length, + separatorBuilder: (_, _) => const SizedBox(height: 24), + itemBuilder: (context, index) { + final exhibit = exhibits[index]; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(exhibit.title, style: caption), + const SizedBox(height: 8), + exhibit.build(context), + ], + ); + }, + ); + } +} + +// --- Exhibits --------------------------------------------------------------- + +final List<_Exhibit> _componentExhibits = [ + _Exhibit('Button — LG / MD / SM, primary · secondary · ghost', (context) { + return _Column( + children: [ + for (final size in PersonalizationButtonSize.values) + _ScrollRow( + children: [ + PersonalizationButton( + label: 'Primary', + size: size, + view: PersonalizationButtonView.primary, + onPressed: () {}, + ), + PersonalizationButton( + label: 'Secondary', + size: size, + view: PersonalizationButtonView.secondary, + onPressed: () {}, + ), + PersonalizationButton( + label: 'Ghost', + size: size, + view: PersonalizationButtonView.ghost, + onPressed: () {}, + ), + ], + ), + ], + ); + }), + _Exhibit('Button — icons and disabled', (context) { + return _ScrollRow( + children: [ + PersonalizationButton( + label: 'Filters', + size: PersonalizationButtonSize.md, + iconStart: PersonalizationIcons.equalizerHorizontal, + iconBuilder: _icon, + onPressed: () {}, + ), + PersonalizationButton( + label: 'Sort', + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.secondary, + iconEnd: PersonalizationIcons.arrowsUpDown, + iconBuilder: _icon, + onPressed: () {}, + ), + PersonalizationButton( + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.ghost, + iconStart: PersonalizationIcons.copy, + iconBuilder: _icon, + onPressed: () {}, + ), + const PersonalizationButton( + label: 'Disabled', + size: PersonalizationButtonSize.md, + ), + ], + ); + }), + _Exhibit('Button Group — MD and SM', (context) { + return const _Row( + children: [ + _ButtonGroupExhibit(size: PersonalizationButtonGroupSize.md), + _ButtonGroupExhibit(size: PersonalizationButtonGroupSize.sm), + ], + ); + }), + _Exhibit('Input Field — search LG, input MD, select SM, disabled', (context) { + return _Column( + children: [ + PersonalizationInputField( + size: PersonalizationInputFieldSize.lg, + type: PersonalizationInputFieldType.search, + placeholder: 'Search', + iconBuilder: _icon, + ), + PersonalizationInputField( + size: PersonalizationInputFieldSize.md, + type: PersonalizationInputFieldType.input, + controller: TextEditingController(text: 'Running shoes'), + iconBuilder: _icon, + ), + PersonalizationInputField( + size: PersonalizationInputFieldSize.sm, + type: PersonalizationInputFieldType.select, + controller: TextEditingController(text: 'Size 42'), + iconBuilder: _icon, + onSelectTap: () {}, + ), + PersonalizationInputField( + size: PersonalizationInputFieldSize.md, + type: PersonalizationInputFieldType.input, + placeholder: 'Disabled', + enabled: false, + iconBuilder: _icon, + ), + ], + ); + }), + _Exhibit('Title — plain, with trailing action, with leading back', (context) { + return _Column( + children: [ + const PersonalizationTitle(title: 'Recommended for you'), + PersonalizationTitle( + title: 'Recently viewed', + trailing: PersonalizationButton( + label: 'Show all', + size: PersonalizationButtonSize.sm, + view: PersonalizationButtonView.ghost, + iconEnd: PersonalizationIcons.angleLargeRight, + iconBuilder: _icon, + onPressed: () {}, + ), + ), + PersonalizationTitle( + title: 'Sneakers', + leading: PersonalizationButton( + size: PersonalizationButtonSize.sm, + view: PersonalizationButtonView.ghost, + iconStart: PersonalizationIcons.arrowLeft, + iconBuilder: _icon, + onPressed: () {}, + ), + ), + ], + ); + }), + _Exhibit('Link — text action next to a field or a label', (context) { + return _Row( + children: [ + PersonalizationLink(label: 'Cancel', onTap: () {}), + PersonalizationLink(label: 'Clear', onTap: () {}), + ], + ); + }), + _Exhibit( + 'Search Results Title', + (context) => const _SearchResultsTitleExhibit(), + ), + _Exhibit('Accordion — collapsed with count, expanded', (context) { + return _Column( + children: [ + PersonalizationAccordion(label: 'Brand', count: 12, iconBuilder: _icon), + PersonalizationAccordion( + label: 'Size', + expanded: true, + iconBuilder: _icon, + ), + ], + ); + }), + _Exhibit( + 'List Label', + (context) => const PersonalizationListLabel(label: 'Popular categories'), + ), + _Exhibit('Badge — warning LG / MD / SM, danger', (context) { + return const _Row( + children: [ + PersonalizationBadge(label: 'New', size: PersonalizationBadgeSize.lg), + PersonalizationBadge(label: 'New', size: PersonalizationBadgeSize.md), + PersonalizationBadge(label: 'New', size: PersonalizationBadgeSize.sm), + PersonalizationBadge( + label: '-15%', + size: PersonalizationBadgeSize.md, + view: PersonalizationBadgeView.danger, + ), + ], + ); + }), + _Exhibit('Tag — primary with remove, secondary', (context) { + return _Row( + children: [ + PersonalizationTag( + label: 'Nike', + onRemove: () {}, + removeIconBuilder: _removeIcon, + ), + PersonalizationTag( + label: 'Size 42', + view: PersonalizationTagView.secondary, + onRemove: () {}, + removeIconBuilder: _removeIcon, + ), + const PersonalizationTag( + label: 'Running', + view: PersonalizationTagView.secondary, + ), + ], + ); + }), + _Exhibit( + 'Checkbox — unchecked, checked, indeterminate, disabled; with label', + (context) { + return const _Column( + children: [ + _Row( + children: [ + PersonalizationCheckbox( + state: PersonalizationCheckboxState.unchecked, + ), + PersonalizationCheckbox( + state: PersonalizationCheckboxState.checked, + ), + PersonalizationCheckbox( + state: PersonalizationCheckboxState.indeterminate, + ), + PersonalizationCheckbox( + state: PersonalizationCheckboxState.checked, + disabled: true, + ), + ], + ), + PersonalizationCheckboxWithLabel( + label: 'In stock only', + state: PersonalizationCheckboxState.checked, + ), + ], + ); + }, + ), + _Exhibit('Dots, Count, Rating', (context) { + return _Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const PersonalizationDots(count: 5, selectedIndex: 1), + const PersonalizationCount( + prefix: 'Showing', + shown: 12, + separator: 'of', + total: 128, + ), + PersonalizationRating(value: '4.7', reviews: 128, iconBuilder: _icon), + ], + ); + }), + _Exhibit('Loader, Favorites Badge', (context) { + return _Row( + children: [ + const PersonalizationLoader(), + PersonalizationFavoritesBadge(iconBuilder: _icon), + ], + ); + }), + _Exhibit('Product Image — 1:1, 4:3, 3:4', (context) { + return _Row( + children: [ + for (final (index, aspect) + in PersonalizationProductImageAspect.values.indexed) + SizedBox( + width: 104, + child: PersonalizationProductImage( + aspect: aspect, + image: _products[index].image, + ), + ), + ], + ); + }), + _Exhibit( + 'Empty State', + (context) => const PersonalizationEmptyState( + message: 'No results for your request.', + ), + ), + _Exhibit('Barcode — Code 128', (context) { + // The barcode brings no background of its own: scanners want white in + // either theme, so it sits on a white box, as it does on the loyalty card. + return Align( + alignment: Alignment.centerLeft, + child: DecoratedBox( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(PersonalizationRadius.lg), + ), + child: const Padding( + padding: EdgeInsets.all(20), + child: PersonalizationBarcode(code: _loyaltyCardNumber), + ), + ), + ); + }), + _Exhibit('Icons — the full set, 24 dp', (context) { + final color = PersonalizationTheme.of(context).colors.textPrimary; + return _ScrollRow( + children: [ + for (final asset in PersonalizationIcons.all) + _icon(context, asset, 24, color), + ], + ); + }), +]; + +final List<_Exhibit> _blockExhibits = [ + _Exhibit('Product Card — carousel, grid, list', (context) { + return _Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 220, + child: _card(PersonalizationProductCardType.carousel, _products[0]), + ), + SizedBox( + width: 161, + child: _card(PersonalizationProductCardType.grid, _products[1]), + ), + _card(PersonalizationProductCardType.list, _products[2]), + ], + ); + }), + _Exhibit('Product Card — image 4:3, 1:1, 3:4 (carousel and list)', (context) { + const aspects = [ + PersonalizationProductImageAspect.landscape, + PersonalizationProductImageAspect.square, + PersonalizationProductImageAspect.portrait, + ]; + return _Column( + children: [ + _ScrollRow( + children: [ + for (final (index, aspect) in aspects.indexed) + SizedBox( + width: 220, + child: _card( + PersonalizationProductCardType.carousel, + _products[index + 3], + aspect: aspect, + ), + ), + ], + ), + for (final (index, aspect) in aspects.indexed) + _card( + PersonalizationProductCardType.list, + _products[index + 3], + aspect: aspect, + ), + ], + ); + }), + _Exhibit('Recommender Block — carousel', (context) { + return _recommender( + PersonalizationProductsLayout.carousel, + 'Recommended for you', + _products, + ); + }), + _Exhibit('Recommender Block — grid', (context) { + return _recommender( + PersonalizationProductsLayout.grid, + 'Similar products', + _products.take(4).toList(), + ); + }), + _Exhibit('Recommender Block — list', (context) { + return _recommender( + PersonalizationProductsLayout.list, + 'Recently viewed', + _products.take(3).toList(), + ); + }), + _Exhibit( + 'Instant Search — recent searches', + (context) => const _InstantSearchExhibit(), + ), + _Exhibit( + 'Instant Search — typing, matches in bold', + (context) => const _InstantSearchExhibit(typing: true), + ), + _Exhibit( + 'Instant Search — with images', + (context) => const _InstantSearchExhibit(images: true), + ), + _Exhibit( + 'Catalog — header, grid ⇄ list, count, load more', + (context) => const _CatalogExhibit(), + ), + _Exhibit( + 'Catalog — empty state', + (context) => const PersonalizationCatalog( + header: _SearchResultsTitleExhibit(count: 0), + products: [], + emptyText: 'No results for your request.', + iconBuilder: _icon, + // Inside the showcase's scroll: laid out whole, no scrolling of its own. + scrollable: false, + ), + ), + _Exhibit( + 'Filters — range, checkbox lists with show more, reset / apply', + (context) => _filters(), + ), + _Exhibit( + 'In App Popup — image, one button', + (context) => _inAppPopup(context, PersonalizationInAppPopupView.image), + ), + _Exhibit( + 'In App Popup — image background, both buttons', + (context) => _inAppPopup( + context, + PersonalizationInAppPopupView.imageBackground, + closeText: 'Not now', + ), + ), + _Exhibit( + 'In App Popup — text only, close button with text', + (context) => _inAppPopup( + context, + PersonalizationInAppPopupView.text, + closeText: 'Maybe later', + ), + ), + _Exhibit( + 'In App Popup — icon, no buttons (cross only)', + (context) => _inAppPopup( + context, + PersonalizationInAppPopupView.icon, + actionText: null, + ), + ), + _Exhibit( + 'In App Popup, fullscreen — image', + (context) => _inAppPopup( + context, + PersonalizationInAppPopupView.image, + fullscreen: true, + ), + ), + _Exhibit( + 'In App Popup, fullscreen — image background, both buttons', + (context) => _inAppPopup( + context, + PersonalizationInAppPopupView.imageBackground, + closeText: 'Not now', + fullscreen: true, + ), + ), + _Exhibit( + 'In App Popup, fullscreen — text only', + (context) => _inAppPopup( + context, + PersonalizationInAppPopupView.text, + fullscreen: true, + ), + ), + _Exhibit( + 'In App Popup, fullscreen — icon', + (context) => _inAppPopup( + context, + PersonalizationInAppPopupView.icon, + fullscreen: true, + ), + ), + _Exhibit('Toast — top and bottom', (context) { + return _Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const PersonalizationToast(text: 'Copied'), + _ScrollRow( + children: [ + PersonalizationButton( + label: 'Show at the bottom', + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.secondary, + onPressed: () => PersonalizationToast.show(context, 'Copied'), + ), + PersonalizationButton( + label: 'Show at the top', + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.secondary, + onPressed: () => PersonalizationToast.show( + context, + 'Code copied to clipboard', + position: PersonalizationToastPosition.top, + ), + ), + ], + ), + ], + ); + }), + _Exhibit( + 'Loyalty Card — light, stamps 0 of 5', + (context) => _loyaltyCard(context, stamps: 0), + ), + _Exhibit( + 'Loyalty Card — brand colour, stamps 4 of 5', + (context) => _loyaltyCard(context, stamps: 4, brand: true), + ), +]; + +/// The Stories V2 block the demo shop serves (api.rees46.ru). +const String _storiesCode = '115bd0b67cf5989a1b60c841790b2af6'; + +/// 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), +); + +/// Drives the live block from the buttons under it. +final PersonalizationStoriesController _storiesController = + PersonalizationStoriesController(); + +List<_Exhibit> _storyExhibits(String shopId) => [ + _Exhibit( + 'Stories — live block $_storiesCode (demo shop); ' + 'links open in the system browser. Seen slides survive a restart.', + (context) => PersonalizationStories( + code: _storiesCode, + shopId: shopId, + controller: _storiesController, + 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 — programmatic control: open the second story, pause and ' + 'resume it after 3 s, reload the block, show the block without the bar', + (context) => Wrap( + spacing: 8, + runSpacing: 8, + children: [ + PersonalizationButton( + label: 'Open #2, pause at 3 s', + size: PersonalizationButtonSize.sm, + onPressed: () { + _storiesController.open(1); + Future.delayed(const Duration(seconds: 3), () { + _storiesController.pause(); + Future.delayed( + const Duration(seconds: 3), + _storiesController.resume, + ); + }); + }, + ), + PersonalizationButton( + label: 'Reload', + size: PersonalizationButtonSize.sm, + view: PersonalizationButtonView.secondary, + onPressed: _storiesController.reload, + ), + PersonalizationButton( + label: 'Show without bar', + size: PersonalizationButtonSize.sm, + view: PersonalizationButtonView.secondary, + onPressed: () => PersonalizationStories.show( + context, + code: _storiesCode, + shopId: shopId, + promoCopiedText: 'Code copied to clipboard', + onError: (error) => _snack(context, 'Stories error: $error'), + iconBuilder: _icon, + ), + ), + ], + ), + ), + _Exhibit( + 'Story Viewer — sample block, offline: price, promo code, discount, a product ' + 'with the promo code of its text block (SOUND10), a product video with buttons, carousel and sound, a fitted photo on its letterbox, ' + 'text blocks with a promo code, a failed photo with Retry, and a GIF: an 8 s ' + 'dial on a 5 s slide plays its whole loop and stops while held, its cover ' + 'stays on the first frame', + (context) { + final stories = _sampleStories((file) => 'assets/uikit/$file'); + return PersonalizationStoriesBar( + padding: EdgeInsets.zero, + items: [ + for (final story in stories) + PersonalizationStoryItem( + id: story.id, + label: story.name, + image: _FirstFrameAsset(story.avatar), + segments: story.slides.length, + ), + ], + onItemTap: (item) => _openSampleStories( + context, + index: stories.indexWhere((story) => story.id == item.id), + ), + iconBuilder: _icon, + ); + }, + ), + _Exhibit('Story Cover — default, pinned, viewed, skeleton', (context) { + return _ScrollRow( + children: [ + PersonalizationStoryCover(image: _image('jacket')), + PersonalizationStoryCover( + image: _image('jacket'), + pinned: true, + iconBuilder: _icon, + ), + PersonalizationStoryCover( + image: _image('jacket'), + state: PersonalizationStoryCoverState.viewed, + ), + const PersonalizationStoryCover( + state: PersonalizationStoryCoverState.skeleton, + ), + ], + ); + }), + _Exhibit( + 'Story Cover — segments lit by index: slides 1, 2 / 2, 4 seen; pinned with ' + '1 seen; viewed; pinned and viewed (a plain warning ring)', + (context) { + return _ScrollRow( + children: [ + PersonalizationStoryCover( + image: _image('sneakers'), + segments: 5, + seenSegments: const {0, 1}, + ), + PersonalizationStoryCover( + image: _image('sneakers'), + segments: 5, + seenSegments: const {1, 3}, + ), + PersonalizationStoryCover( + image: _image('sneakers'), + pinned: true, + segments: 5, + seenSegments: const {0}, + iconBuilder: _icon, + ), + PersonalizationStoryCover( + image: _image('sneakers'), + state: PersonalizationStoryCoverState.viewed, + segments: 5, + seenSegments: const {0, 1, 2, 3, 4}, + ), + PersonalizationStoryCover( + image: _image('sneakers'), + state: PersonalizationStoryCoverState.viewed, + pinned: true, + segments: 5, + seenSegments: const {0, 1, 2, 3, 4}, + iconBuilder: _icon, + ), + ], + ); + }, + ), + _Exhibit('Story Preview and Stories Bar — pinned, default, viewed', ( + context, + ) { + return PersonalizationStoriesBar( + padding: EdgeInsets.zero, + items: [ + PersonalizationStoryItem( + id: '1', + label: 'Pinned', + image: _image('watch'), + pinned: true, + segments: 3, + ), + PersonalizationStoryItem( + id: '2', + label: 'Default', + image: _image('headphones'), + segments: 4, + seenSegments: const {0}, + ), + PersonalizationStoryItem( + id: '3', + label: 'Viewed', + image: _image('backpack'), + viewed: true, + ), + PersonalizationStoryItem( + id: '4', + label: 'A label too long for one line takes two, then an ellipsis', + image: _image('bottle'), + ), + ], + onItemTap: (item) => _snack(context, 'Story: ${item.label}'), + iconBuilder: _icon, + ); + }), + _Exhibit( + 'Stories Bar — loading', + (context) => const PersonalizationStoriesBar( + loading: true, + padding: EdgeInsets.zero, + ), + ), + _Exhibit( + 'Story Progress — 5 slides, the second at 40%', + (context) => + const PersonalizationStoryProgress(count: 5, current: 1, progress: 0.4), + ), + _Exhibit('Story Navigation — progress and the cross', (context) { + return PersonalizationStoryNavigation( + count: 5, + current: 1, + progress: 0.4, + onClose: () => _snack(context, 'Close'), + iconBuilder: _icon, + ); + }), + _Exhibit('Story Price — price, discount, promo code, long promo code', ( + context, + ) { + return _Column( + children: [ + const PersonalizationStoryPrice( + price: '1 190 900 ₽', + oldPrice: '245 000 ₽', + ), + const PersonalizationStoryPrice( + type: PersonalizationStoryPriceType.discount, + price: '1 190 900 ₽', + oldPrice: '245 000 ₽', + discount: '10%', + ), + PersonalizationStoryPrice( + type: PersonalizationStoryPriceType.promoCode, + price: '1 190 900 ₽', + oldPrice: '245 000 ₽', + promoCode: 'PROMO', + iconBuilder: _icon, + ), + PersonalizationStoryPrice( + type: PersonalizationStoryPriceType.promoCode, + price: '1 190 900 ₽', + oldPrice: '245 000 ₽', + promoCode: 'YAGODA-MALINA', + copiedText: 'Code copied to clipboard', + onPromoCopied: (code) => _snack(context, 'Copied: $code'), + iconBuilder: _icon, + ), + ], + ); + }), + _Exhibit('Story Timer — merged and separate', (context) { + return _Column( + children: [ + PersonalizationStoryTimer(endTime: _timerEnd), + PersonalizationStoryTimer( + endTime: _timerEnd, + view: PersonalizationStoryTimerView.separate, + ), + ], + ); + }), + _Exhibit( + 'Story Text Block — solid large / medium / small, transparent; ' + 'on a media slide (dark tokens)', + (context) => _OnMediaSlide( + child: _Column( + children: [ + const PersonalizationStoryTextBlock( + text: 'Open eat dear winding belonging.', + size: PersonalizationStoryTextSize.large, + background: Color(0xFF16AE13), + ), + PersonalizationStoryTextBlock( + text: 'Open eat dear winding belonging though differed stand left.', + background: PersonalizationColors.light.semanticWarning, + ), + PersonalizationStoryTextBlock( + text: 'Open eat dear winding belonging though differed stand left.', + size: PersonalizationStoryTextSize.small, + background: PersonalizationColors.light.semanticInfo, + ), + const PersonalizationStoryTextBlock( + text: 'Open eat dear winding belonging.', + textAlign: TextAlign.center, + ), + ], + ), + ), + ), + _Exhibit( + 'Story Used Products — collapsed with the sound button, expanded', + (context) => _OnMediaSlide( + padding: EdgeInsets.zero, + child: _Column( + children: [ + const _SoundedUsedProducts(), + PersonalizationStoryUsedProducts( + products: _products.take(4).toList(), + showText: 'Used products', + hideText: 'Hide products', + initiallyExpanded: true, + onProductTap: (product) => + _snack(context, 'Product: ${product.name}'), + iconBuilder: _icon, + ), + ], + ), + ), + ), + _Exhibit('Badge "Sale!" — LG warning, as on the Action slides', (context) { + return const _Row(children: [PersonalizationBadge(label: 'Sale!')]); + }), +]; + +/// A stand-in for a media slide: a photo under the kit's dark tokens, the way the +/// viewer renders image and video slides. +class _OnMediaSlide extends StatelessWidget { + const _OnMediaSlide({ + required this.child, + this.padding = const EdgeInsets.all(16), + }); + + final Widget child; + final EdgeInsetsGeometry padding; + + @override + Widget build(BuildContext context) { + final base = Theme.of(context); + return Theme( + data: base.copyWith(extensions: [PersonalizationTheme.dark]), + child: ClipRRect( + borderRadius: BorderRadius.circular(PersonalizationRadius.xl2), + child: DecoratedBox( + decoration: BoxDecoration( + image: DecorationImage( + image: _image('jacket'), + fit: BoxFit.cover, + colorFilter: const ColorFilter.mode( + Color(0x66000000), + BlendMode.darken, + ), + ), + ), + child: Padding(padding: padding, child: child), + ), + ), + ); + } +} + +/// Collapsed used products with a working mute toggle at the start of the row. +class _SoundedUsedProducts extends StatefulWidget { + const _SoundedUsedProducts(); + + @override + State<_SoundedUsedProducts> createState() => _SoundedUsedProductsState(); +} + +class _SoundedUsedProductsState extends State<_SoundedUsedProducts> { + bool _muted = true; + + @override + Widget build(BuildContext context) { + return PersonalizationStoryUsedProducts( + products: _products.take(4).toList(), + showText: 'Used products', + hideText: 'Hide products', + leading: PersonalizationStorySoundButton( + muted: _muted, + onPressed: () => setState(() => _muted = !_muted), + iconBuilder: _icon, + ), + iconBuilder: _icon, + ); + } +} + +/// Where a picture of the sample block lives: its file under `assets/uikit/`. +typedef _SampleUrl = String Function(String file); + +/// The pictures of the sample stories ship with the app and reach the viewer over a +/// loopback HTTP server: the viewer takes no imageProvider, so they go through the +/// SDK's own loader. Only that loader plays a GIF slide and stretches the slide to one +/// loop of it — a host imageProvider takes a GIF over, and its slide keeps the server +/// duration. +final Future _sampleServer = _serveSampleAssets(); + +Future _serveSampleAssets() async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((request) async { + final response = request.response; + try { + final data = await rootBundle.load('assets/uikit${request.uri.path}'); + response.add( + data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes), + ); + } catch (_) { + response.statusCode = HttpStatus.notFound; + } + await response.close(); + }); + return 'http://${server.address.address}:${server.port}'; +} + +/// A sample bar cover the way the SDK draws covers by default: a GIF stays on its +/// first frame. The sample bar is the host here, so the host draws its covers. +@immutable +class _FirstFrameAsset extends ImageProvider<_FirstFrameAsset> { + const _FirstFrameAsset(this.asset); + + final String asset; + + @override + Future<_FirstFrameAsset> obtainKey(ImageConfiguration configuration) => + SynchronousFuture<_FirstFrameAsset>(this); + + @override + ImageStreamCompleter loadImage( + _FirstFrameAsset key, + ImageDecoderCallback decode, + ) => OneFrameImageStreamCompleter(_load(decode)); + + Future _load(ImageDecoderCallback decode) async { + final codec = await decode(await rootBundle.loadBuffer(asset)); + final frame = await codec.getNextFrame(); + codec.dispose(); + return ImageInfo(image: frame.image); + } + + @override + bool operator ==(Object other) => + other is _FirstFrameAsset && other.asset == asset; + + @override + int get hashCode => asset.hashCode; +} + +Map _sampleProductSlide( + String id, + Map product, { + Map? textBlock, +}) => { + 'id': id, + 'duration': 6, + 'type': '', + 'elements': [ + ?textBlock, + {'type': 'button', 'title': 'More info', 'link': 'https://example.com'}, + {'type': 'product', 'item': product}, + ], +}; + +/// Stories in the server's shape, so the sample runs through the same parsing as +/// the live block: product slides of every price kind, a media slide with text +/// blocks, a button and used products, and a GIF slide. +List _sampleStories(_SampleUrl url) => StoriesBlock.fromJson({ + 'id': 'sample', + 'stories': [ + { + 'id': 'products', + 'name': 'Products', + 'avatar': url('headphones.jpg'), + 'slides': [ + _sampleProductSlide('price', { + 'id': 'h1', + 'brand': 'Sony', + 'name': 'Wireless over-ear headphones, noise cancelling', + 'picture': url('headphones.jpg'), + 'price': 299, + 'price_formatted': r'299 $', + 'oldprice': 349, + 'oldprice_formatted': r'349 $', + 'url': 'https://example.com/headphones', + }), + _sampleProductSlide('promo', { + 'id': 'w1', + 'brand': 'Garmin', + 'name': 'GPS running watch', + 'picture': url('watch.jpg'), + 'price': 449, + 'price_formatted': r'449 $', + 'oldprice': 499, + 'oldprice_formatted': r'499 $', + 'promocode': 'YAGODA-MALINA', + 'price_with_promocode_formatted': r'399 $', + 'url': 'https://example.com/watch', + }), + _sampleProductSlide('discount', { + 'id': 's1', + 'brand': 'Nike', + 'name': 'Air Zoom Pegasus 41 running shoes', + 'picture': url('pegasus.jpg'), + 'price': 140, + 'price_formatted': r'140 $', + 'oldprice': 165, + 'oldprice_formatted': r'165 $', + 'discount_percent': 12.5, + 'url': 'https://example.com/pegasus', + }), + // The product has no promo code of its own: the card shows the code of the + // slide's text block, and the text block itself is not drawn. + _sampleProductSlide( + 'text-promo', + { + 'id': 'g1', + 'brand': 'Ray-Ban', + 'name': 'Wayfarer sunglasses', + 'picture': url('sunglasses.jpg'), + 'price': 159, + 'price_formatted': r'159 $', + 'url': 'https://example.com/sunglasses', + }, + textBlock: { + 'type': 'text_block', + 'text_input': 'Your promo code SOUND10', + 'promocode': 'SOUND10', + 'font_size': 20, + 'y_offset': 10, + }, + ), + // A product over a video: every slide button, the used products and the + // sound toggle; the video streams once and then plays from the disk cache. + { + 'id': 'video', + 'duration': 10, + 'type': 'video', + 'background': _sampleVideo, + 'background_color': '#1E3A5F', + 'elements': [ + { + 'type': 'button', + 'title': 'Buy now', + 'link': 'https://example.com', + }, + {'type': 'button', 'title': 'Open the product'}, + { + 'type': 'product', + 'title': 'Your code', + 'item': { + 'id': 'b1', + 'brand': 'Osprey', + 'name': 'Daylite backpack', + 'picture': url('backpack.jpg'), + 'price': 80, + 'price_formatted': r'80 $', + 'promocode': 'BUTTERFLY', + 'price_with_promocode_formatted': r'64 $', + 'url': 'https://example.com/backpack', + }, + }, + _sampleUsedProducts(url), + ], + }, + ], + }, + { + 'id': 'media', + 'name': 'Media', + 'avatar': url('jacket.jpg'), + 'slides': [ + // A square photo fitted whole: the rest of the screen is its letterbox + // colour, and a bare photo takes the 50% scrim. + { + 'id': 'fitted', + 'duration': 5, + 'type': 'image', + 'background': url('sneakers.jpg'), + 'background_color': '#1E3A5F', + }, + { + 'id': 'text', + 'duration': 8, + 'type': 'image', + 'background': url('jacket.jpg'), + 'background_color': '#3B2A1E', + 'elements': [ + { + 'type': 'text_block', + 'text_input': 'Open eat dear winding belonging.', + 'font_size': 36, + 'text_background_color': '#16AE13', + 'text_background_color_opacity': '100%', + 'y_offset': 9, + }, + { + 'type': 'text_block', + 'text_input': 'Tap to copy the code SALE10', + 'font_size': 20, + 'text_align': 'center', + 'text_background_color': '#0087E8', + 'text_background_color_opacity': '100%', + 'y_offset': 30, + 'promocode': 'SALE10', + }, + { + 'type': 'text_block', + 'text_input': 'Open eat dear winding belonging though differed.', + 'font_size': 24, + 'y_offset': 45, + }, + { + 'type': 'button', + 'title': 'Go shopping', + 'link': 'https://example.com', + }, + _sampleUsedProducts(url), + ], + }, + // The photo cannot load: the slide stops and offers Retry. + { + 'id': 'retry', + 'duration': 5, + 'type': 'image', + 'background': url('missing.jpg'), + }, + ], + }, + // An 8 s dial GIF on a 5 s slide: the slide lasts the whole loop, the hand stops + // while the slide is held, and the cover stays on the first frame. + { + 'id': 'gif', + 'name': 'GIF', + 'avatar': url('story_clock.gif'), + 'slides': [ + { + 'id': 'gif', + 'duration': 5, + 'type': 'image', + 'background': url('story_clock.gif'), + 'background_color': '#1B2A41', + }, + ], + }, + ], +}).stories; + +/// A short public clip (the Flutter docs' butterfly). +const String _sampleVideo = + 'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4'; + +/// The "Used products" carousel of the sample slides. +Map _sampleUsedProducts(_SampleUrl url) => { + 'type': 'products', + 'labels': { + 'show_carousel': 'Used products', + 'hide_carousel': 'Hide products', + }, + 'products': [ + for (final (index, name) in ['backpack', 'bottle', 'sunglasses'].indexed) + { + 'id': 'm$index', + 'brand': 'Brand', + 'name': 'Product ${index + 1}', + 'picture': url('$name.jpg'), + 'price': 99, + 'price_formatted': r'99 $', + 'oldprice': 120, + 'oldprice_formatted': r'120 $', + 'discount_percent': 17.5, + }, + ], +}; + +Future _openSampleStories(BuildContext context, {int index = 0}) async { + final base = await _sampleServer; + if (!context.mounted) return; + await Navigator.of(context, rootNavigator: true).push( + PersonalizationStoryViewer.route( + PersonalizationStoryViewer( + stories: _sampleStories((file) => '$base/$file'), + initialStory: index, + // No SDK: the sample does not track; links and products come back here. + onLinkClick: (url) => PersonalizationToast.show(context, 'Link: $url'), + onProductClick: (product) => + PersonalizationToast.show(context, 'Product: ${product.name}'), + promoCopiedText: 'Code copied to clipboard', + iconBuilder: _icon, + ), + ), + ); +} + +void _snack(BuildContext context, String message) => ScaffoldMessenger.of( + context, +).showSnackBar(SnackBar(content: Text(message))); + +/// The popup as the SDK will hand it over: the host supplies the image and wires the +/// two callbacks. Fixed height here only because the showcase is a scrolling column — +/// on screen the popup is sized by whoever presents it. +Widget _inAppPopup( + BuildContext context, + PersonalizationInAppPopupView view, { + String? actionText = 'Action', + String? closeText, + bool fullscreen = false, +}) { + return SizedBox( + // Полноэкранному нужно больше места: отступы и кегли там на ступень крупнее. + height: fullscreen ? 620 : 460, + child: PersonalizationInAppPopup( + view: view, + presentation: fullscreen + ? PersonalizationInAppPopupPresentation.fullscreen + : PersonalizationInAppPopupPresentation.modal, + title: 'Pizza ipsum dolor meat lovers', + text: 'Cheese ranch Philly roll pepperoni hand thin garlic bacon.', + actionText: actionText, + closeText: closeText, + image: + view == PersonalizationInAppPopupView.text || + view == PersonalizationInAppPopupView.icon + ? null + : _image('jacket'), + icon: const Icon( + Icons.verified_user, + size: 100, + color: Color(0xFF16AE13), + ), + iconBuilder: _icon, + onAction: () => _snack(context, 'Popup action'), + onClose: () => _snack(context, 'Popup closed'), + ), + ); +} + +/// The card number the loyalty exhibits encode. +const String _loyaltyCardNumber = '2000012345678'; + +/// The loyalty card as a host fills it. The SDK's loyalty status carries only +/// membership and the level, so the balance, the stamps and the card number +/// are the host's own data; the logo, stripe and emblem are demo art bundled +/// with the example — brand art does not ship in the SDK. +Widget _loyaltyCard( + BuildContext context, { + required int stamps, + bool brand = false, +}) { + // Semantic/Info, as in the design file's dark example. + final brandBlue = PersonalizationTheme.of(context).colors.semanticInfo; + const white = Color(0xFFFFFFFF); + // The kit never tints the host's logo, so the demo tints it itself to the + // content colour: Text/Primary by default, white on the brand card. + final content = brand + ? white + : PersonalizationTheme.of(context).colors.textPrimary; + return PersonalizationLoyaltyCard( + logo: Image.asset('assets/uikit/loyalty_logo.png', color: content), + balanceLabel: 'Бонусы', + balanceValue: '50 550', + stripe: const AssetImage('assets/uikit/loyalty_stripe.jpg'), + emblem: const AssetImage('assets/uikit/loyalty_emblem.png'), + stamps: stamps, + stampsTotal: 5, + fields: const [ + PersonalizationLoyaltyCardField(label: 'Владелец', value: 'Олег'), + PersonalizationLoyaltyCardField(label: 'Уровень', value: 'Базовый'), + ], + code: _loyaltyCardNumber, + cardColor: brand ? brandBlue : null, + contentColor: brand ? white : null, + iconBuilder: _icon, + ); +} + +// --- Stateful exhibits ------------------------------------------------------ + +class _ButtonGroupExhibit extends StatefulWidget { + const _ButtonGroupExhibit({required this.size}); + + final PersonalizationButtonGroupSize size; + + @override + State<_ButtonGroupExhibit> createState() => _ButtonGroupExhibitState(); +} + +class _ButtonGroupExhibitState extends State<_ButtonGroupExhibit> { + int _selected = 0; + + @override + Widget build(BuildContext context) { + return PersonalizationButtonGroup( + size: widget.size, + selectedIndex: _selected, + onSelected: (index) => setState(() => _selected = index), + iconBuilder: _icon, + items: const [ + PersonalizationButtonGroupItem( + icon: PersonalizationIcons.grid2x2, + activeIcon: PersonalizationIcons.grid2x2Fill, + ), + PersonalizationButtonGroupItem( + icon: PersonalizationIcons.list, + activeIcon: PersonalizationIcons.listFill, + ), + ], + ); + } +} + +class _SearchResultsTitleExhibit extends StatefulWidget { + const _SearchResultsTitleExhibit({this.count = 128}); + + final int count; + + @override + State<_SearchResultsTitleExhibit> createState() => + _SearchResultsTitleExhibitState(); +} + +class _SearchResultsTitleExhibitState + extends State<_SearchResultsTitleExhibit> { + int _view = 0; + + @override + Widget build(BuildContext context) { + return PersonalizationSearchResultsTitle( + title: 'Sneakers', + selectedViewIndex: _view, + onViewChanged: (index) => setState(() => _view = index), + onBack: () {}, + onFilters: () {}, + onSort: () {}, + results: PersonalizationSearchResults( + prefix: 'Found', + count: widget.count, + suffix: 'products', + ), + filters: [ + PersonalizationSearchFilter(label: 'Nike', onRemove: () {}), + PersonalizationSearchFilter(label: 'Size 42', onRemove: () {}), + ], + iconBuilder: _icon, + ); + } +} + +/// The catalogue as a host would wire it: the results title in the header slot +/// drives the grid/list switch, "load more" appends a page after a short +/// simulated delay. +/// Instant search in its three states: recent searches before typing, suggestions with the +/// query highlighted while typing, and rows with images. The host owns the data; the kit only +/// renders what it is given and reports the taps. +class _InstantSearchExhibit extends StatefulWidget { + const _InstantSearchExhibit({this.typing = false, this.images = false}); + + final bool typing; + final bool images; + + @override + State<_InstantSearchExhibit> createState() => _InstantSearchExhibitState(); +} + +class _InstantSearchExhibitState extends State<_InstantSearchExhibit> { + late final TextEditingController _controller = TextEditingController( + text: widget.typing ? 'boots' : '', + ); + List _recent = [ + 'mens winter boots', + 'kids shoes', + 'bag', + 'accessories', + 'black boots', + ]; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final typing = widget.typing; + return PersonalizationInstantSearch( + controller: _controller, + placeholder: 'want to buy...', + cancelText: 'Cancel', + onCancel: () {}, + showImages: widget.images, + recentLabel: typing ? null : 'Recent searches', + clearText: 'Clear', + onClearRecent: () => setState(() => _recent = []), + recentSearches: typing ? const [] : _recent, + moreText: 'more', + onMoreRecent: () {}, + onRecentRemove: (item) => + setState(() => _recent = _recent.where((it) => it != item).toList()), + suggestions: typing + ? const [ + 'winter', + 'mens', + 'kids', + 'for outdoor', + 'womens', + 'low', + 'black', + 'orange', + ] + : const [], + categoriesLabel: typing ? 'Category' : 'Popular category', + categories: typing + ? const [ + PersonalizationSuggestion(id: 'c1', title: 'Womens boots'), + PersonalizationSuggestion(id: 'c2', title: 'Mens boots'), + PersonalizationSuggestion(id: 'c3', title: 'Kids boots'), + ] + : [ + // The design gives categories pictures too. Photos other than the + // three products below, so the two sections do not repeat each other. + PersonalizationSuggestion( + id: 'c1', + title: 'Running shoes', + subtitle: 'Shoes', + image: _image('sneakers'), + ), + PersonalizationSuggestion( + id: 'c2', + title: 'Running apparel', + subtitle: 'Clothing', + image: _image('jacket'), + ), + PersonalizationSuggestion( + id: 'c3', + title: 'Trail gear', + subtitle: 'Outdoor', + image: _image('watch'), + ), + ], + productsLabel: typing ? 'Products' : 'Frequently searched', + products: typing + ? const [ + PersonalizationSuggestion(id: 'p1', title: 'winter womens boots'), + PersonalizationSuggestion(id: 'p2', title: 'boots for mens'), + PersonalizationSuggestion( + id: 'p3', + title: 'winter boots for mens', + ), + PersonalizationSuggestion(id: 'p4', title: 'kids winter boots'), + ] + : [ + for (final p in _products.take(widget.images ? 3 : 5)) + PersonalizationSuggestion( + id: p.id, + title: p.name, + subtitle: p.price, + image: p.image, + ), + ], + onCategoryTap: (_) {}, + onProductTap: (_) {}, + iconBuilder: _icon, + ); + } +} + +class _CatalogExhibit extends StatefulWidget { + const _CatalogExhibit(); + + @override + State<_CatalogExhibit> createState() => _CatalogExhibitState(); +} + +/// The catalogue as a host would wire it: the category title (title + view switch, as on +/// the CatalogGrid page) sits in the header slot and drives the grid/list switch. The +/// search results title with back, filters and sort belongs to the search flow. +class _CatalogExhibitState extends State<_CatalogExhibit> { + PersonalizationProductsLayout _layout = PersonalizationProductsLayout.grid; + int _view = 0; + List _shown = _products.take(4).toList(); + bool _loading = false; + + Future _loadMore() async { + setState(() => _loading = true); + await Future.delayed(const Duration(milliseconds: 800)); + if (!mounted) return; + setState(() { + final page = _products.skip(_shown.length % _products.length).take(4); + _shown = [ + ..._shown, + for (final p in page) p.copyWith(id: '${p.id}-${_shown.length}'), + ]; + _loading = false; + }); + } + + @override + Widget build(BuildContext context) { + return PersonalizationCatalog( + header: PersonalizationTitle( + title: 'Sneakers', + trailing: PersonalizationButtonGroup( + size: PersonalizationButtonGroupSize.md, + selectedIndex: _view, + onSelected: (index) => setState(() { + _view = index; + _layout = index == 0 + ? PersonalizationProductsLayout.grid + : PersonalizationProductsLayout.list; + }), + iconBuilder: _icon, + items: const [ + PersonalizationButtonGroupItem( + icon: PersonalizationIcons.grid2x2, + activeIcon: PersonalizationIcons.grid2x2Fill, + ), + PersonalizationButtonGroupItem( + icon: PersonalizationIcons.list, + activeIcon: PersonalizationIcons.listFill, + ), + ], + ), + ), + layout: _layout, + products: _shown, + loading: _loading, + count: PersonalizationCatalogCount( + prefix: 'Showing', + shown: _shown.length, + separator: 'of', + total: _totalProducts, + ), + loadMoreText: 'Load more', + onLoadMore: _loadMore, + onProductAction: (_) {}, + iconBuilder: _icon, + // Inside the showcase's scroll: laid out whole, no scrolling of its own. + scrollable: false, + ); + } +} + +// --- Layout helpers --------------------------------------------------------- + +class _Row extends StatelessWidget { + const _Row({required this.children}); + + final List children; + + @override + Widget build(BuildContext context) { + return Row( + children: [ + for (final (index, child) in children.indexed) ...[ + if (index > 0) const SizedBox(width: 8), + child, + ], + ], + ); + } +} + +class _ScrollRow extends StatelessWidget { + const _ScrollRow({required this.children}); + + final List children; + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: _Row(children: children), + ); + } +} + +class _Column extends StatelessWidget { + const _Column({ + required this.children, + this.crossAxisAlignment = CrossAxisAlignment.stretch, + }); + + final List children; + final CrossAxisAlignment crossAxisAlignment; + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: crossAxisAlignment, + children: [ + for (final (index, child) in children.indexed) ...[ + if (index > 0) const SizedBox(height: 12), + child, + ], + ], + ); + } +} + +/// The kit hands over the asset and the colour it wants; the host picks the renderer. +Widget _icon(BuildContext context, String asset, double size, Color color) { + return SvgPicture.asset( + asset, + width: size, + height: size, + colorFilter: ColorFilter.mode(color, BlendMode.srcIn), + ); +} + +Widget _removeIcon(BuildContext context, String asset) { + return _icon( + context, + asset, + 16, + PersonalizationTheme.of(context).colors.textPrimary, + ); +} + +/// The filters screen with the sections from the design file; toggles and ranges update its own state. +Widget _filters() { + const colors = [ + 'All', + 'Black', + 'White', + 'Red', + 'Light blue', + 'Green', + 'Yellow', + 'Brown', + 'Grey', + 'Pink', + ]; + const ratings = ['All', '5 stars', '4+ stars', '3+ stars']; + return PersonalizationFilters( + title: 'Filters', + onClose: () {}, + resetText: 'Reset', + applyText: 'Apply', + onReset: () {}, + onApply: (_) {}, + sections: [ + const PersonalizationFilterRange( + id: 'size', + title: 'Size', + fromLabel: 'From', + toLabel: 'to', + from: '42', + to: '43', + select: true, + ), + PersonalizationFilterOptions( + id: 'colors', + title: 'Colors', + options: [ + for (final (index, label) in colors.indexed) + PersonalizationFilterOption( + id: label.toLowerCase(), + label: label, + checked: index == 1, + ), + ], + showMoreText: 'Show more', + showLessText: 'Show less', + ), + const PersonalizationFilterRange( + id: 'price', + title: 'Price (USD)', + fromLabel: 'From', + toLabel: 'to', + from: '50', + to: '500', + ), + PersonalizationFilterOptions( + id: 'rating', + title: 'Rating', + options: [ + for (final (index, label) in ratings.indexed) + PersonalizationFilterOption( + id: label, + label: label, + checked: index == 1, + ), + ], + ), + ], + iconBuilder: _icon, + ); +} + +Widget _card( + PersonalizationProductCardType type, + PersonalizationProduct product, { + PersonalizationProductImageAspect aspect = + PersonalizationProductImageAspect.square, +}) { + return PersonalizationProductCard( + type: type, + image: product.image, + imageAspect: aspect, + brand: product.brand, + name: product.name, + rating: product.rating, + price: product.price, + oldPrice: product.oldPrice, + discount: product.discount, + actionText: product.actionText, + onAction: () {}, + iconBuilder: _icon, + ); +} + +Widget _recommender( + PersonalizationProductsLayout layout, + String title, + List products, +) { + return PersonalizationRecommenderBlock( + layout: layout, + title: title, + showAllText: 'Show all', + onShowAll: () {}, + products: products, + onProductAction: (_) {}, + iconBuilder: _icon, + ); +} + +// --- Fixtures --------------------------------------------------------------- + +const int _totalProducts = 128; + +/// Photos ship with the app: the showcase must not depend on the network. +ImageProvider _image(String seed) => AssetImage('assets/uikit/$seed.jpg'); + +/// Static products for the exhibits. Strings arrive formatted — that is the kit's contract. +final List _products = [ + PersonalizationProduct( + id: '1', + name: 'Air Zoom Pegasus 41 running shoes', + price: r'$140', + image: _image('pegasus'), + brand: 'Nike', + rating: const PersonalizationProductRating(value: '4.7', reviews: 128), + oldPrice: r'$165', + discount: '-15%', + actionText: 'Add to cart', + ), + PersonalizationProduct( + id: '2', + name: 'Wireless over-ear headphones', + price: r'$299', + image: _image('headphones'), + brand: 'Sony', + rating: const PersonalizationProductRating(value: '4.8', reviews: 2140), + actionText: 'Add to cart', + ), + PersonalizationProduct( + id: '3', + name: 'Everyday backpack 20 L', + price: r'$89', + image: _image('backpack'), + brand: 'Peak Design', + rating: const PersonalizationProductRating(value: '4.6', reviews: 412), + oldPrice: r'$110', + discount: '-19%', + actionText: 'Add to cart', + ), + PersonalizationProduct( + id: '4', + name: 'Trail running jacket', + price: r'$175', + image: _image('jacket'), + brand: 'Salomon', + rating: const PersonalizationProductRating(value: '4.5', reviews: 77), + actionText: 'Add to cart', + ), + PersonalizationProduct( + id: '5', + name: 'Polarized sunglasses', + price: r'$120', + image: _image('sunglasses'), + brand: 'Oakley', + rating: const PersonalizationProductRating(value: '4.4', reviews: 305), + oldPrice: r'$150', + discount: '-20%', + actionText: 'Add to cart', + ), + PersonalizationProduct( + id: '6', + name: 'Insulated bottle 750 ml', + price: r'$35', + image: _image('bottle'), + brand: 'Hydro Flask', + rating: const PersonalizationProductRating(value: '4.9', reviews: 980), + actionText: 'Add to cart', + ), + PersonalizationProduct( + id: '7', + name: 'GPS running watch', + price: r'$449', + image: _image('watch'), + brand: 'Garmin', + rating: const PersonalizationProductRating(value: '4.7', reviews: 1532), + actionText: 'Add to cart', + ), + PersonalizationProduct( + id: '8', + name: 'Court sneakers', + price: r'$95', + image: _image('sneakers'), + brand: 'Adidas', + rating: const PersonalizationProductRating(value: '4.3', reviews: 64), + oldPrice: r'$120', + discount: '-21%', + actionText: 'Add to cart', + ), +]; + +extension on PersonalizationProduct { + PersonalizationProduct copyWith({required String id}) { + return PersonalizationProduct( + id: id, + name: name, + price: price, + image: image, + brand: brand, + rating: rating, + oldPrice: oldPrice, + discount: discount, + actionText: actionText, + ); + } +} diff --git a/example/pubspec.lock b/example/pubspec.lock index b21c337..2112ba7 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -1,6 +1,14 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" async: dependency: transitive description: @@ -41,6 +49,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" cupertino_icons: dependency: "direct main" description: @@ -73,6 +89,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" file: dependency: transitive description: @@ -99,16 +123,37 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + flutter_svg: + dependency: "direct main" + description: + name: flutter_svg + sha256: "35882981abcbfb8c15b286f0cd690ff25bac12d95eff3e25ee207f37d4c42e7f" + url: "https://pub.dev" + source: hosted + version: "2.3.0" flutter_test: dependency: "direct dev" description: flutter source: sdk version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" fuchsia_remote_debug_protocol: dependency: transitive description: flutter source: sdk version: "0.0.0" + html: + dependency: transitive + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.dev" + source: hosted + version: "0.15.7" http: dependency: transitive description: @@ -202,6 +247,38 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" patrol: dependency: "direct dev" description: @@ -226,6 +303,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.8.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" platform: dependency: transitive description: @@ -256,7 +341,63 @@ packages: path: ".." relative: true source: path - version: "0.2.0" + version: "1.1.0" + shared_preferences: + dependency: transitive + description: + name: shared_preferences + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + url: "https://pub.dev" + source: hosted + version: "2.5.5" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 + url: "https://pub.dev" + source: hosted + version: "2.4.23" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea" + url: "https://pub.dev" + source: hosted + version: "2.5.7" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" shelf: dependency: transitive description: @@ -334,6 +475,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + vector_graphics: + dependency: transitive + description: + name: vector_graphics + sha256: "9d0e3b9cb16542ad660daee871e726a10d13a93b7b5391677c3160e8f5e83935" + url: "https://pub.dev" + source: hosted + version: "1.2.3" + vector_graphics_codec: + dependency: transitive + description: + name: vector_graphics_codec + sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146" + url: "https://pub.dev" + source: hosted + version: "1.1.13" + vector_graphics_compiler: + dependency: transitive + description: + name: vector_graphics_compiler + sha256: "4dca4feb77dc3ec7f6e27e49c53241eb8217f55e4f9b12599a27f8903bca5682" + url: "https://pub.dev" + source: hosted + version: "1.3.0" vector_math: dependency: transitive description: @@ -342,6 +507,46 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + video_player: + dependency: transitive + description: + name: video_player + sha256: "48a7bdaa38a3d50ec10c78627abdbfad863fdf6f0d6e08c7c3c040cfd80ae36f" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + video_player_android: + dependency: transitive + description: + name: video_player_android + sha256: "877a6c7ba772456077d7bfd71314629b3fe2b73733ce503fc77c3314d43a0ca0" + url: "https://pub.dev" + source: hosted + version: "2.9.5" + video_player_avfoundation: + dependency: transitive + description: + name: video_player_avfoundation + sha256: "2fc56e537324a19eb649fca991aa308ac961b5406292876fa657b062de461fd8" + url: "https://pub.dev" + source: hosted + version: "2.12.0" + video_player_platform_interface: + dependency: transitive + description: + name: video_player_platform_interface + sha256: "92c0fbabe20c788e71fd10d26cea998d0d253282e65d145aed0818731cf593ce" + url: "https://pub.dev" + source: hosted + version: "6.9.0" + video_player_web: + dependency: transitive + description: + name: video_player_web + sha256: "9f3c00be2ef9b76a95d94ac5119fb843dca6f2c69e6c9968f6f2b6c9e7afbdeb" + url: "https://pub.dev" + source: hosted + version: "2.4.0" vm_service: dependency: transitive description: @@ -366,6 +571,22 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "67f0aff7be013d107995e9b75bf4e7f2c3ef2dfdb2c8e68024bba0a7fd5756a4" + url: "https://pub.dev" + source: hosted + version: "7.0.1" sdks: dart: ">=3.11.1 <4.0.0" - flutter: ">=3.32.0" + flutter: ">=3.38.0" diff --git a/example/pubspec.yaml b/example/pubspec.yaml index b829cea..a3b4990 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -29,6 +29,9 @@ dependencies: # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.8 + # The SDK ships its icons as SVG assets and leaves rendering to the host. + flutter_svg: ^2.2.0 + dev_dependencies: integration_test: sdk: flutter @@ -62,10 +65,11 @@ flutter: # the material Icons class. uses-material-design: true - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg + # Photos and loyalty-card art (logo, stripe, level emblem) for the UI Kit + # showcase — bundled so the demo does not depend on the network. Brand art is + # demo-only: the SDK does not ship it. + assets: + - assets/uikit/ # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/to/resolution-aware-images diff --git a/ios/Classes/Rees46FlutterSdkPlugin.swift b/ios/Classes/Rees46FlutterSdkPlugin.swift index 31f30fa..abdd0af 100644 --- a/ios/Classes/Rees46FlutterSdkPlugin.swift +++ b/ios/Classes/Rees46FlutterSdkPlugin.swift @@ -11,12 +11,16 @@ public class Rees46FlutterSdkPlugin: NSObject, FlutterPlugin, FlutterApplication private var messenger: FlutterBinaryMessenger? private var api: PersonalizationHostApiImpl? private var flutterApi: PersonalizationFlutterApi? + private var storiesApi: PersonalizationStoriesFlutterApi? public static func register(with registrar: FlutterPluginRegistrar) { let instance = Rees46FlutterSdkPlugin() instance.messenger = registrar.messenger() instance.api = PersonalizationHostApiImpl() instance.flutterApi = PersonalizationFlutterApi(binaryMessenger: registrar.messenger()) + let storiesApi = PersonalizationStoriesFlutterApi(binaryMessenger: registrar.messenger()) + instance.storiesApi = storiesApi + StoriesAudio.shared.onVolumeUp = { storiesApi.onStoriesVolumeUp { _ in } } PersonalizationHostApiSetup.setUp( binaryMessenger: registrar.messenger(), api: instance.api @@ -377,6 +381,8 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { return [ "products": r.products.map { _searchProductToDict($0) }, "suggests": r.suggests.map { ["name": $0.name, "url": $0.url] }, + "last_queries": r.lastQueries.map { ["name": $0.name, "url": $0.url] }, + "popular_categories": r.popularCategories.map { ["name": $0.name, "url": $0.url] }, ] } @@ -456,11 +462,25 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { let priceMax = p?["price_max"] as? Double let colors = p?["colors"] as? [String] let fashionSizes = p?["fashion_sizes"] as? [String] + let filters = p?["filters"] as? [String: Any] + // The native iOS search pages by product offset, while page is 1-based as on Android: + // page N starts at (N - 1) * limit, and the first page (or page <= 0) has no offset. The + // server's default page size isn't pinned down anywhere, so a later page without a limit is + // rejected rather than guessed: no offset would return page 1 again, and the page number as + // the offset would shift by N products. + var offset: Int? + if let page = page, page > 1 { + guard let limit = limit, limit > 0 else { + completion(.failure(PigeonError(code: "bad_args", message: "page > 1 requires limit on iOS", details: nil))) + return + } + offset = (page - 1) * limit + } sdk.search( query: query, limit: limit, - offset: page, + offset: offset, categoryLimit: categoryLimit, brandLimit: brandLimit, categories: categoriesInt, @@ -471,7 +491,7 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { excludedMerchants: nil, excludedBrands: excludedBrands, brands: brands, - filters: nil, + filters: filters, priceMin: priceMin, priceMax: priceMax, colors: colors, @@ -501,10 +521,23 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { "products": r.products.map { _searchProductToDict($0) }, "categories": r.categories.map { _searchCategoryToDict($0) }, "products_total": r.productsTotal, + "queries": r.queries.map { ["name": $0.name, "url": $0.url] }, ] 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] } + } + if let industrial = r.industrialFilters { + dict["industrial_filters"] = [ + "colors": industrial.fashionColors.map { ["color": $0.color, "count": $0.count] }, + "fashion_sizes": industrial.fashionSizes.map { ["size": $0.size, "count": $0.count] }, + ] + } if let locs = r.locations { dict["locations"] = locs.map { loc -> [String: Any] in var d: [String: Any] = ["id": loc.id, "name": loc.name] @@ -532,6 +565,9 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { "currency": p.currency, "sales_rate": p.salesRate, "relative_sales_rate": p.relativeSalesRate, + "oldprice": p.oldPrice, + "oldprice_formatted": p.oldPriceFormatted, + "discount": p.discount, ] _ = dict // suppress unused warning; all fields set above return dict @@ -689,6 +725,72 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi { } } + func getStories(code: 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 + } + if code.isEmpty { + completion(.failure(PigeonError(code: "bad_args", message: "code is required", details: nil))) + return + } + // The same request `getStories(code:)` sends, through the SDK's public raw entry point, + // so the server JSON reaches Dart as is — the payload the Android bridge hands over. + // `StoryContent` keeps most of the fields internal and drops the rest, so it cannot be + // re-encoded. Queued on the session queue like `getStories`: it waits for the init that + // provides the device id. + sdk.sessionQueue.addOperation { + let params: [String: String] = ["shop_id": sdk.shopId, "did": sdk.deviceId] + sdk.getRequest(path: "stories/\(code)", params: params, false) { result in + switch result { + case .success(let dict): + Self._encodeCatalog(dict, errorCode: "get_stories_failed", completion: completion) + case .failure(let err): + completion(.failure(PigeonError(code: "get_stories_failed", message: String(describing: err), details: nil))) + } + } + } + } + + func openUrl(url: String, completion: @escaping (Result) -> Void) { + guard let target = URL(string: url), target.scheme?.isEmpty == false else { + completion(.success(false)) + return + } + DispatchQueue.main.async { + UIApplication.shared.open(target, options: [:]) { opened in + completion(.success(opened)) + } + } + } + + // MARK: - Stories viewer (UI kit) + + func getStoriesSeen(shop: String) throws -> [String: [Any?]] { + return StoriesSeenStore.read(shop: shop).mapValues { $0 as [Any?] } + } + + func setStorySlideSeen(shop: String, storyId: String, slideId: String) throws { + StoriesSeenStore.add(shop: shop, storyId: storyId, slideId: slideId) + } + + func getCacheDirectory() throws -> String { + let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first + return (caches ?? FileManager.default.temporaryDirectory).path + } + + func beginStoriesAudio() throws { + StoriesAudio.shared.begin() + } + + func updateStoriesAudio(muted: Bool) throws { + StoriesAudio.shared.update(muted: muted) + } + + func endStoriesAudio() throws { + StoriesAudio.shared.end() + } + private static func _profileResponseToDict(_ p: GetProfileResponse) -> [String: Any] { var d: [String: Any] = [:] if let v = p.id { d["id"] = v } diff --git a/ios/Classes/StoriesSupport.swift b/ios/Classes/StoriesSupport.swift new file mode 100644 index 0000000..4789c3b --- /dev/null +++ b/ios/Classes/StoriesSupport.swift @@ -0,0 +1,96 @@ +import AVFoundation +import Foundation + +/// The slides of the UI kit's stories (V2) the user has seen, per shop: one UserDefaults entry +/// per shop, `[storyId: [slideId]]`. It survives app restarts, so a story reopens at its first +/// unseen slide and its cover keeps the seen segments. +/// +/// The plugin's own store, not the native SDK's: the Flutter viewer is drawn in Dart. +enum StoriesSeenStore { + private static let keyPrefix = "rees46_flutter_stories_seen." + + /// Seen slide ids by story id for `shop`; empty when nothing was seen yet. + static func read(shop: String) -> [String: [String]] { + let stored = UserDefaults.standard.dictionary(forKey: keyPrefix + shop) ?? [:] + var result: [String: [String]] = [:] + for (storyId, value) in stored { + if let slides = value as? [String] { result[storyId] = slides } + } + return result + } + + /// Adds `slideId` to the seen slides of `storyId` for `shop`. + static func add(shop: String, storyId: String, slideId: String) { + var stored = read(shop: shop) + var slides = stored[storyId] ?? [] + if slides.contains(slideId) { return } + slides.append(slideId) + stored[storyId] = slides + UserDefaults.standard.set(stored, forKey: keyPrefix + shop) + } +} + +/// The audio session while the stories viewer plays video. +/// +/// - `begin` saves the app's session before the first video, `end` puts it back when the +/// viewer closes. +/// - Muted, the session is `ambient`: video never interrupts other apps' audio (the user's +/// music keeps playing). Unmuted, it is `playback`: the story's sound takes over. +/// - While active, the session's `outputVolume` is watched: the hardware volume going up is +/// reported through `onVolumeUp`, and the viewer unmutes. +final class StoriesAudio { + static let shared = StoriesAudio() + + /// The hardware volume went up while the viewer plays video. Called on the main queue. + var onVolumeUp: (() -> Void)? + + private var saved: (category: AVAudioSession.Category, mode: AVAudioSession.Mode, + options: AVAudioSession.CategoryOptions)? + private var volumeObservation: NSKeyValueObservation? + /// The viewer played sound and so took the audio from other apps. + private var tookAudio = false + + func begin() { + guard saved == nil else { return } + let session = AVAudioSession.sharedInstance() + saved = (session.category, session.mode, session.categoryOptions) + } + + func update(muted: Bool) { + begin() + let session = AVAudioSession.sharedInstance() + if muted { + try? session.setCategory(.ambient, mode: .default, options: []) + } else { + try? session.setCategory(.playback, mode: .default, options: []) + tookAudio = true + } + // The volume is observable only on an active session; `ambient` mixes with other audio. + try? session.setActive(true) + observeVolume() + } + + func end() { + volumeObservation?.invalidate() + volumeObservation = nil + guard let saved = saved else { return } + self.saved = nil + let session = AVAudioSession.sharedInstance() + // Deactivated before the category goes back, so a non-mixable category the app had does + // not take over the audio here. After sound played, the app whose audio the story + // interrupted is told it may resume. Fails harmlessly while something else still plays. + try? session.setActive(false, options: tookAudio ? .notifyOthersOnDeactivation : []) + try? session.setCategory(saved.category, mode: saved.mode, options: saved.options) + tookAudio = false + } + + private func observeVolume() { + guard volumeObservation == nil else { return } + volumeObservation = AVAudioSession.sharedInstance().observe( + \.outputVolume, options: [.old, .new] + ) { [weak self] _, change in + guard let old = change.oldValue, let new = change.newValue, new > old else { return } + DispatchQueue.main.async { self?.onVolumeUp?() } + } + } +} diff --git a/ios/Classes/pigeon/PersonalizationApi.g.swift b/ios/Classes/pigeon/PersonalizationApi.g.swift index 132a49b..5744ec3 100644 --- a/ios/Classes/pigeon/PersonalizationApi.g.swift +++ b/ios/Classes/pigeon/PersonalizationApi.g.swift @@ -668,6 +668,37 @@ protocol PersonalizationHostApi { /// 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) + /// Returns the stories block [code] (`stories/{code}`) as the server's JSON string, + /// untouched: `{ "id": ..., "stories": [...], "settings": {...} }`. Both platforms hand + /// over the same raw payload, so Dart parses one shape. + /// Dart layer parses the result into [StoriesBlock]. + func getStories(code: String, shopId: String?, completion: @escaping (Result) -> Void) + /// 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) + /// 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 + /// hands nested lists over as `List`, and a typed `List` here + /// generates a lazy cast that throws on the first read. + func getStoriesSeen(shop: String) throws -> [String: [Any?]] + /// Records [slideId] of story [storyId] as seen for [shop]. + func setStorySlideSeen(shop: String, storyId: String, slideId: String) throws + /// The app's cache directory: Android `Context.cacheDir`, iOS `Library/Caches`. The + /// stories viewer keeps its video cache under it. + func getCacheDirectory() throws -> String + /// Remembers the app's audio session before the stories viewer plays its first video, + /// so [endStoriesAudio] can put it back. iOS only; a no-op on Android, where a muted + /// video never takes the audio focus (`mixWithOthers`). + func beginStoriesAudio() throws + /// While the viewer plays video: muted — the `ambient` category, which never + /// interrupts other apps' audio; unmuted — `playback`. Also starts watching the + /// hardware volume (see [PersonalizationStoriesFlutterApi.onStoriesVolumeUp]). iOS + /// only; a no-op on Android. + func updateStoriesAudio(muted: Bool) throws + /// The viewer closed: restores the session saved by [beginStoriesAudio] and stops + /// watching the volume. iOS only; a no-op on Android. + func endStoriesAudio() throws /// Routes a push to the shop it belongs to (payload `shop_id`) and tracks it /// via the native `REES46.handlePush`. [event] is the index of the Dart /// `PushEvent` enum: 0 = received, 1 = delivered, 2 = clicked. The native side @@ -1090,6 +1121,150 @@ class PersonalizationHostApiSetup { } else { getCollectionChannel.setMessageHandler(nil) } + /// Returns the stories block [code] (`stories/{code}`) as the server's JSON string, + /// untouched: `{ "id": ..., "stories": [...], "settings": {...} }`. Both platforms hand + /// over the same raw payload, so Dart parses one shape. + /// Dart layer parses the result into [StoriesBlock]. + let getStoriesChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStories\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getStoriesChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let codeArg = args[0] as! String + let shopIdArg: String? = nilOrValue(args[1]) + api.getStories(code: codeArg, shopId: shopIdArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getStoriesChannel.setMessageHandler(nil) + } + /// Opens [url] with the system handler (browser or the app that claims the link). + /// Returns false when nothing could open it. + let openUrlChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openUrl\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + openUrlChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let urlArg = args[0] as! String + api.openUrl(url: urlArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + openUrlChannel.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 + /// hands nested lists over as `List`, and a typed `List` here + /// generates a lazy cast that throws on the first read. + let getStoriesSeenChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStoriesSeen\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getStoriesSeenChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let shopArg = args[0] as! String + do { + let result = try api.getStoriesSeen(shop: shopArg) + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + getStoriesSeenChannel.setMessageHandler(nil) + } + /// Records [slideId] of story [storyId] as seen for [shop]. + let setStorySlideSeenChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.setStorySlideSeen\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setStorySlideSeenChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let shopArg = args[0] as! String + let storyIdArg = args[1] as! String + let slideIdArg = args[2] as! String + do { + try api.setStorySlideSeen(shop: shopArg, storyId: storyIdArg, slideId: slideIdArg) + reply(wrapResult(nil)) + } catch { + reply(wrapError(error)) + } + } + } else { + setStorySlideSeenChannel.setMessageHandler(nil) + } + /// The app's cache directory: Android `Context.cacheDir`, iOS `Library/Caches`. The + /// stories viewer keeps its video cache under it. + let getCacheDirectoryChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCacheDirectory\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getCacheDirectoryChannel.setMessageHandler { _, reply in + do { + let result = try api.getCacheDirectory() + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + getCacheDirectoryChannel.setMessageHandler(nil) + } + /// Remembers the app's audio session before the stories viewer plays its first video, + /// so [endStoriesAudio] can put it back. iOS only; a no-op on Android, where a muted + /// video never takes the audio focus (`mixWithOthers`). + let beginStoriesAudioChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.beginStoriesAudio\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + beginStoriesAudioChannel.setMessageHandler { _, reply in + do { + try api.beginStoriesAudio() + reply(wrapResult(nil)) + } catch { + reply(wrapError(error)) + } + } + } else { + beginStoriesAudioChannel.setMessageHandler(nil) + } + /// While the viewer plays video: muted — the `ambient` category, which never + /// interrupts other apps' audio; unmuted — `playback`. Also starts watching the + /// hardware volume (see [PersonalizationStoriesFlutterApi.onStoriesVolumeUp]). iOS + /// only; a no-op on Android. + let updateStoriesAudioChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.updateStoriesAudio\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + updateStoriesAudioChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let mutedArg = args[0] as! Bool + do { + try api.updateStoriesAudio(muted: mutedArg) + reply(wrapResult(nil)) + } catch { + reply(wrapError(error)) + } + } + } else { + updateStoriesAudioChannel.setMessageHandler(nil) + } + /// The viewer closed: restores the session saved by [beginStoriesAudio] and stops + /// watching the volume. iOS only; a no-op on Android. + let endStoriesAudioChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.endStoriesAudio\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + endStoriesAudioChannel.setMessageHandler { _, reply in + do { + try api.endStoriesAudio() + reply(wrapResult(nil)) + } catch { + reply(wrapError(error)) + } + } + } else { + endStoriesAudioChannel.setMessageHandler(nil) + } /// Routes a push to the shop it belongs to (payload `shop_id`) and tracks it /// via the native `REES46.handlePush`. [event] is the index of the Dart /// `PushEvent` enum: 0 = received, 1 = delivered, 2 = clicked. The native side @@ -1444,3 +1619,43 @@ class PersonalizationFlutterApi: PersonalizationFlutterApiProtocol { } } } +/// Native events of the stories viewer. Separate from [PersonalizationFlutterApi]: the +/// push dispatcher owns that channel, the UI kit owns this one. +/// +/// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. +protocol PersonalizationStoriesFlutterApiProtocol { + /// The hardware volume went up while the viewer plays video (iOS: the audio session's + /// `outputVolume` grew). Android delivers the volume key to Flutter itself. + func onStoriesVolumeUp(completion: @escaping (Result) -> Void) +} +class PersonalizationStoriesFlutterApi: PersonalizationStoriesFlutterApiProtocol { + private let binaryMessenger: FlutterBinaryMessenger + private let messageChannelSuffix: String + init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") { + self.binaryMessenger = binaryMessenger + self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" + } + var codec: PersonalizationApiPigeonCodec { + return PersonalizationApiPigeonCodec.shared + } + /// The hardware volume went up while the viewer plays video (iOS: the audio session's + /// `outputVolume` grew). Android delivers the volume key to Flutter itself. + func onStoriesVolumeUp(completion: @escaping (Result) -> Void) { + let channelName: String = "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationStoriesFlutterApi.onStoriesVolumeUp\(messageChannelSuffix)" + let channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage(nil) { response in + guard let listResponse = response as? [Any?] else { + completion(.failure(createConnectionError(withChannelName: channelName))) + return + } + if listResponse.count > 1 { + let code: String = listResponse[0] as! String + let message: String? = nilOrValue(listResponse[1]) + let details: String? = nilOrValue(listResponse[2]) + completion(.failure(PigeonError(code: code, message: message, details: details))) + } else { + completion(.success(())) + } + } + } +} diff --git a/lib/rees46_sdk.dart b/lib/rees46_sdk.dart index c08b3ea..05b281a 100644 --- a/lib/rees46_sdk.dart +++ b/lib/rees46_sdk.dart @@ -1,4 +1,5 @@ -export 'src/personalization_sdk.dart'; +// Stories stay with the UI kit until its release: the kit imports them from src. +export 'src/personalization_sdk.dart' hide PersonalizationStoriesBridge; export 'src/multi_instance/rees46.dart'; export 'src/multi_instance/rees46_config.dart'; export 'src/multi_instance/push_event.dart'; diff --git a/lib/src/personalization_sdk.dart b/lib/src/personalization_sdk.dart index c2a823d..401daea 100644 --- a/lib/src/personalization_sdk.dart +++ b/lib/src/personalization_sdk.dart @@ -18,6 +18,7 @@ import 'products/products_list_response.dart'; import 'search/search_params.dart'; import 'search/search_response.dart'; import 'sdk_init_config.dart'; +import 'stories/stories_response.dart'; import 'subscriptions/manage_subscription_params.dart'; import 'tracking/purchase_line_item.dart'; import 'tracking/tracking_api.dart'; @@ -351,3 +352,34 @@ 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. +extension PersonalizationStoriesBridge on PersonalizationSdk { + /// The stories block [code] (`stories/{code}`). + Future getStories(String code) async { + if (code.isEmpty) { + throw ArgumentError.value(code, 'code', 'must be non-empty'); + } + final json = await _api.getStories(code, shopId); + return StoriesBlock.fromJson(jsonDecode(json) as Map); + } + + /// Opens [url] with the system handler; `false` when nothing could open it. + Future openUrl(String url) => _api.openUrl(url); + + /// The stories slides seen on this device for [shop] (slide ids by story id), from the + /// plugin's own persistent store. + Future>> getStoriesSeen(String shop) async { + final stored = await _api.getStoriesSeen(shop); + return >{ + for (final entry in stored.entries) + entry.key: entry.value.whereType().toList(), + }; + } + + /// Records slide [slideId] of story [storyId] as seen for [shop]. + Future setStorySlideSeen(String shop, String storyId, String slideId) => + _api.setStorySlideSeen(shop, storyId, slideId); +} diff --git a/lib/src/pigeon/personalization_api.g.dart b/lib/src/pigeon/personalization_api.g.dart index c37d9ad..df816ce 100644 --- a/lib/src/pigeon/personalization_api.g.dart +++ b/lib/src/pigeon/personalization_api.g.dart @@ -1237,6 +1237,233 @@ class PersonalizationHostApi { } } + /// Returns the stories block [code] (`stories/{code}`) as the server's JSON string, + /// untouched: `{ "id": ..., "stories": [...], "settings": {...} }`. Both platforms hand + /// over the same raw payload, so Dart parses one shape. + /// Dart layer parses the result into [StoriesBlock]. + Future getStories(String code, String? shopId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStories$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([code, shopId]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + /// Opens [url] with the system handler (browser or the app that claims the link). + /// Returns false when nothing could open it. + Future openUrl(String url) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openUrl$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); + 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 if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as bool?)!; + } + } + + /// 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 + /// hands nested lists over as `List`, and a typed `List` here + /// generates a lazy cast that throws on the first read. + Future>> getStoriesSeen(String shop) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStoriesSeen$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([shop]); + 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 if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Map?)!.cast>(); + } + } + + /// Records [slideId] of story [storyId] as seen for [shop]. + Future setStorySlideSeen(String shop, String storyId, String slideId) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.setStorySlideSeen$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([shop, storyId, slideId]); + 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 app's cache directory: Android `Context.cacheDir`, iOS `Library/Caches`. The + /// stories viewer keeps its video cache under it. + Future getCacheDirectory() async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getCacheDirectory$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + /// Remembers the app's audio session before the stories viewer plays its first video, + /// so [endStoriesAudio] can put it back. iOS only; a no-op on Android, where a muted + /// video never takes the audio focus (`mixWithOthers`). + Future beginStoriesAudio() async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.beginStoriesAudio$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + /// While the viewer plays video: muted — the `ambient` category, which never + /// interrupts other apps' audio; unmuted — `playback`. Also starts watching the + /// hardware volume (see [PersonalizationStoriesFlutterApi.onStoriesVolumeUp]). iOS + /// only; a no-op on Android. + Future updateStoriesAudio(bool muted) async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.updateStoriesAudio$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([muted]); + 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 viewer closed: restores the session saved by [beginStoriesAudio] and stops + /// watching the volume. iOS only; a no-op on Android. + Future endStoriesAudio() async { + final String pigeonVar_channelName = 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.endStoriesAudio$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + /// Routes a push to the shop it belongs to (payload `shop_id`) and tracks it /// via the native `REES46.handlePush`. [event] is the index of the Dart /// `PushEvent` enum: 0 = received, 1 = delivered, 2 = clicked. The native side @@ -1657,3 +1884,36 @@ abstract class PersonalizationFlutterApi { } } } + +/// Native events of the stories viewer. Separate from [PersonalizationFlutterApi]: the +/// push dispatcher owns that channel, the UI kit owns this one. +abstract class PersonalizationStoriesFlutterApi { + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + /// The hardware volume went up while the viewer plays video (iOS: the audio session's + /// `outputVolume` grew). Android delivers the volume key to Flutter itself. + void onStoriesVolumeUp(); + + static void setUp(PersonalizationStoriesFlutterApi? api, {BinaryMessenger? binaryMessenger, String messageChannelSuffix = '',}) { + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + { + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationStoriesFlutterApi.onStoriesVolumeUp$messageChannelSuffix', pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (api == null) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + try { + api.onStoriesVolumeUp(); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse(error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } +} diff --git a/lib/src/search/search_params.dart b/lib/src/search/search_params.dart index 3df4467..1c57076 100644 --- a/lib/src/search/search_params.dart +++ b/lib/src/search/search_params.dart @@ -7,10 +7,15 @@ import 'dart:convert'; /// Cross-platform notes: /// - [categories]: list of category ID strings. Android joins them with commas; /// iOS converts them to integers internally. -/// - [page]: maps to Android `PAGE` param and iOS `offset` param. +/// - [page]: 1-based. Android sends it as `page`; the iOS search only takes an +/// offset, so iOS sends `(page - 1) * limit` and rejects a [page] past the first +/// without a [limit]. +/// +/// [filters] are the shop's own facets by name — `{"Материал корпуса": ["Металл"]}` — +/// as the full search response lists them in `filters`. /// /// Excluded Android-only params: `extended`, `exclude`, `excludedMerchants`, -/// `noClarification`, `filters` (complex SearchFilters object). +/// `noClarification`. class SearchParams { final int? limit; final int? page; @@ -26,6 +31,7 @@ class SearchParams { final double? priceMax; final List? colors; final List? fashionSizes; + final Map>? filters; const SearchParams({ this.limit, @@ -42,6 +48,7 @@ class SearchParams { this.priceMax, this.colors, this.fashionSizes, + this.filters, }); String toJson() => jsonEncode({ @@ -61,6 +68,7 @@ class SearchParams { if (colors != null && colors!.isNotEmpty) 'colors': colors, if (fashionSizes != null && fashionSizes!.isNotEmpty) 'fashion_sizes': fashionSizes, + if (filters != null && filters!.isNotEmpty) 'filters': filters, }); } diff --git a/lib/src/search/search_response.dart b/lib/src/search/search_response.dart index 652dbb2..57f3cb8 100644 --- a/lib/src/search/search_response.dart +++ b/lib/src/search/search_response.dart @@ -2,9 +2,12 @@ import '../json_number.dart'; /// Response from [PersonalizationSdk.searchFull]. /// -/// Excluded Android-only response fields: brands (`List`), clarification, -/// collections, html, priceMedian, priceRanges, requestsCount, searchQuery. -/// Excluded iOS-only response fields: filters, industrialFilters, redirect, queries. +/// Facets ([brands], [filters], [industrialFilters]) are filled when the native side +/// delivers them; an older native SDK leaves them empty. +/// +/// Excluded Android-only response fields: clarification, collections, html, +/// priceMedian, priceRanges, requestsCount, searchQuery. +/// Excluded iOS-only response fields: redirect, queries. class SearchFullResponse { final List products; final List categories; @@ -12,12 +15,22 @@ class SearchFullResponse { final SearchPriceRange? priceRange; final List? locations; + /// Brand names found in the results (Android carries counts too, iOS only names). + final List brands; + + /// Shop facets keyed by name: value → product count. + final Map filters; + final SearchIndustrialFilters? industrialFilters; + const SearchFullResponse({ required this.products, required this.categories, required this.productsTotal, this.priceRange, this.locations, + this.brands = const [], + this.filters = const {}, + this.industrialFilters, }); factory SearchFullResponse.fromJson(Map json) { @@ -37,6 +50,79 @@ class SearchFullResponse { locations: (json['locations'] as List?) ?.map((e) => SearchLocation.fromJson(e as Map)) .toList(), + brands: _parseBrands(json['brands']), + filters: _parseFilters(json['filters']), + industrialFilters: json['industrial_filters'] is Map + ? SearchIndustrialFilters.fromJson( + Map.from(json['industrial_filters'] as Map), + ) + : null, + ); + } +} + +/// 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; + final Map values; + + const SearchFilter({required this.count, required this.values}); + + factory SearchFilter.fromJson(Map json) { + final values = json['values']; + return SearchFilter( + count: toIntOrNull(json['count']) ?? 0, + values: values is Map + ? { + for (final entry in values.entries) + entry.key.toString(): toIntOrNull(entry.value) ?? 0, + } + : const {}, + ); + } +} + +/// Fashion facets of a full search: colours and sizes with product counts. +class SearchIndustrialFilters { + final List colors; + final List fashionSizes; + + const SearchIndustrialFilters({ + this.colors = const [], + this.fashionSizes = const [], + }); + + factory SearchIndustrialFilters.fromJson(Map json) { + List names(dynamic raw, String key) => raw is List + ? raw + .map((e) => e is Map ? e[key]?.toString() : null) + .whereType() + .toList() + : const []; + return SearchIndustrialFilters( + colors: names(json['colors'], 'color'), + fashionSizes: names(json['fashion_sizes'], 'size'), ); } } @@ -44,10 +130,10 @@ class SearchFullResponse { /// Search product — intersection of Android [com.personalization.api.responses.product.Product] /// and iOS [Product] (from SearchResponse). /// -/// Excluded Android-only fields: _id, imageUrlHandle, urlHandle, picture, categoryIds, +/// 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, oldPrice / oldPriceFull -/// (and their formatted variants), discount, isNew, params. +/// Excluded iOS-only fields: barcode, model, deeplinkIos, oldPriceFull (and its +/// formatted variant), isNew, params. class SearchProduct { final String id; final String name; @@ -67,6 +153,17 @@ class SearchProduct { /// JSON key: "image_url_resized" on both platforms. final Map resizedImages; + /// Resized copy of the main image (`picture`), the one to show in lists. + final String? picture; + + /// Price before the discount (`oldprice`), 0 when there is none. + final double oldPrice; + final String? oldPriceFormatted; + + /// Discount in percent (`discount`), 0 when there is none. + final int discount; + final String? discountFormatted; + const SearchProduct({ required this.id, required this.name, @@ -82,6 +179,11 @@ class SearchProduct { required this.salesRate, required this.relativeSalesRate, required this.resizedImages, + this.picture, + this.oldPrice = 0.0, + this.oldPriceFormatted, + this.discount = 0, + this.discountFormatted, }); factory SearchProduct.fromJson(Map json) { @@ -100,6 +202,11 @@ class SearchProduct { salesRate: toIntOrNull(json['sales_rate']) ?? 0, relativeSalesRate: toDoubleOrNull(json['relative_sales_rate']) ?? 0.0, resizedImages: _parseResizedImages(json['image_url_resized']), + picture: json['picture'] as String?, + oldPrice: toDoubleOrNull(json['oldprice']) ?? 0.0, + oldPriceFormatted: json['oldprice_formatted'] as String?, + discount: toIntOrNull(json['discount']) ?? 0, + discountFormatted: json['discount_formatted'] as String?, ); } } @@ -111,19 +218,23 @@ class SearchProduct { /// and [SearchLocation] models. /// /// Excluded Android-only fields: clarification, collections, html, requestsCount, -/// searchQuery, bookAuthor, queries. -/// Excluded iOS-only fields: filters, industrialFilters, redirect, queries, brands. +/// searchQuery, bookAuthor. +/// Excluded iOS-only fields: filters, industrialFilters, redirect, brands. class SearchInstantResponse { final List products; final List categories; final int productsTotal; final List? locations; + /// Phrases suggested for the typed text (`queries`). + final List queries; + const SearchInstantResponse({ required this.products, required this.categories, required this.productsTotal, this.locations, + this.queries = const [], }); factory SearchInstantResponse.fromJson(Map json) { @@ -138,10 +249,19 @@ class SearchInstantResponse { locations: (json['locations'] as List?) ?.map((e) => SearchLocation.fromJson(e as Map)) .toList(), + queries: _parseSuggests(json['queries']), ); } } +List _parseSuggests(dynamic raw) { + if (raw is! List) return const []; + return raw + .whereType() + .map((e) => SearchSuggest.fromJson(Map.from(e))) + .toList(); +} + Map _parseResizedImages(dynamic raw) { if (raw is Map) { return Map.fromEntries( @@ -205,21 +325,30 @@ class SearchPriceRange { /// Contains trending/popular products and search suggestions configured for the shop. /// /// Excluded Android-only fields: html. -/// Excluded iOS-only fields: lastQueries, lastProducts. +/// Excluded iOS-only fields: lastProducts. class SearchBlankResponse { final List products; final List suggests; - const SearchBlankResponse({required this.products, required this.suggests}); + /// The user's latest search phrases as the server remembers them. + final List lastQueries; + final List popularCategories; + + const SearchBlankResponse({ + required this.products, + required this.suggests, + this.lastQueries = const [], + this.popularCategories = const [], + }); factory SearchBlankResponse.fromJson(Map json) { return SearchBlankResponse( products: (json['products'] as List? ?? []) .map((e) => SearchProduct.fromJson(e as Map)) .toList(), - suggests: (json['suggests'] as List? ?? []) - .map((e) => SearchSuggest.fromJson(e as Map)) - .toList(), + suggests: _parseSuggests(json['suggests']), + lastQueries: _parseSuggests(json['last_queries']), + popularCategories: _parseSuggests(json['popular_categories']), ); } } diff --git a/lib/src/stories/stories_response.dart b/lib/src/stories/stories_response.dart new file mode 100644 index 0000000..1ab2348 --- /dev/null +++ b/lib/src/stories/stories_response.dart @@ -0,0 +1,413 @@ +import '../json_number.dart'; + +/// 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 +/// the old stories) are not carried: the kit styles stories with its own tokens. +class StoriesBlock { + /// Block id on the server. + final String id; + final List stories; + + const StoriesBlock({required this.id, required this.stories}); + + factory StoriesBlock.fromJson(Map json) { + return StoriesBlock( + id: json['id']?.toString() ?? '', + stories: _maps(json['stories']).map(Story.fromJson).toList(), + ); + } +} + +/// One story: a cover in the bar and the slides the viewer plays. +class Story { + final String id; + final String name; + + /// Cover image URL. + final String avatar; + + /// Seen by this device, as the server remembers it. + final bool viewed; + + /// Pinned by the shop to the start of the bar. + final bool pinned; + + /// Slide to start from — the first one the user has not seen yet. + final int startPosition; + final List slides; + + const Story({ + required this.id, + required this.name, + required this.avatar, + this.viewed = false, + this.pinned = false, + this.startPosition = 0, + required this.slides, + }); + + factory Story.fromJson(Map json) { + return Story( + id: json['id']?.toString() ?? '', + name: json['name'] as String? ?? '', + avatar: json['avatar'] as String? ?? '', + viewed: json['viewed'] == true, + pinned: json['pinned'] == true, + startPosition: toIntOrNull(json['start_position']) ?? 0, + slides: _maps(json['slides']).map(StorySlide.fromJson).toList(), + ); + } +} + +/// What a slide shows behind its elements. +enum StorySlideType { + /// `image`: [StorySlide.background] is a picture. + image, + + /// `video`: [StorySlide.background] is a video, [StorySlide.preview] its poster. + video, + + /// `""`: a dynamic product slide, the product comes in a [StoryProductElement]. + product, +} + +/// One slide of a story. +class StorySlide { + /// Slide id: a number for media slides, a string like `"39_0"` for dynamic ones. + final String id; + final StorySlideType type; + + /// Image or video URL; empty on product slides. + final String background; + + /// Colour behind the background, `#RRGGBB`; empty when not set. + final String backgroundColor; + + /// Poster of a video slide; empty when not set. + final String preview; + + /// How long the slide stays on screen. + final Duration duration; + final List elements; + + /// Seconds a slide lasts when the server does not say (or says 0) — the same on every + /// platform. + static const int defaultDurationSeconds = 10; + + const StorySlide({ + required this.id, + required this.type, + this.background = '', + this.backgroundColor = '', + this.preview = '', + this.duration = const Duration(seconds: defaultDurationSeconds), + this.elements = const [], + }); + + factory StorySlide.fromJson(Map json) { + final seconds = toIntOrNull(json['duration']); + return StorySlide( + id: json['id']?.toString() ?? '', + type: switch (json['type']) { + 'image' => StorySlideType.image, + 'video' => StorySlideType.video, + _ => StorySlideType.product, + }, + background: json['background'] as String? ?? '', + backgroundColor: json['background_color'] as String? ?? '', + preview: json['preview'] as String? ?? '', + duration: Duration( + seconds: seconds == null || seconds <= 0 + ? defaultDurationSeconds + : seconds, + ), + elements: _maps( + json['elements'], + ).map(StoryElement.fromJson).whereType().toList(), + ); + } + + /// The product of a dynamic product slide, if it has one. + StoryProduct? get product { + for (final element in elements) { + if (element is StoryProductElement) return element.item; + } + return null; + } +} + +/// An element placed on a slide. Unknown types and `header` (not drawn by the kit) are +/// dropped while parsing. +sealed class StoryElement { + const StoryElement(); + + /// The element for [json], or `null` for a type the kit does not draw. + static StoryElement? fromJson(Map json) { + return switch (json['type']) { + 'button' => StoryButtonElement.fromJson(json), + 'product' => StoryProductElement.fromJson(json), + 'products' => StoryProductsElement.fromJson(json), + 'text_block' => StoryTextBlockElement.fromJson(json), + _ => null, + }; + } +} + +/// `button`: a call to action with a link. +class StoryButtonElement extends StoryElement { + final String title; + final String link; + final String linkAndroid; + final String linkIos; + + /// Legacy colours of the old stories; the kit draws its own primary button. + final String background; + final String color; + final bool textBold; + + const StoryButtonElement({ + required this.title, + this.link = '', + this.linkAndroid = '', + this.linkIos = '', + this.background = '', + this.color = '', + this.textBold = false, + }); + + factory StoryButtonElement.fromJson(Map json) { + return StoryButtonElement( + title: json['title'] as String? ?? '', + link: json['link'] as String? ?? '', + linkAndroid: json['link_android'] as String? ?? '', + linkIos: json['link_ios'] as String? ?? '', + background: json['background'] as String? ?? '', + color: json['color'] as String? ?? '', + textBold: json['text_bold'] == true || json['bold'] == true, + ); + } +} + +/// `product`: the product of a dynamic product slide. +class StoryProductElement extends StoryElement { + final String title; + final StoryProduct? item; + + const StoryProductElement({this.title = '', this.item}); + + factory StoryProductElement.fromJson(Map json) { + final item = json['item']; + return StoryProductElement( + title: json['title'] as String? ?? '', + item: item is Map && item.isNotEmpty + ? StoryProduct.fromJson(Map.from(item)) + : null, + ); + } +} + +/// `products`: the products "used" on a media slide, behind a show / hide toggle. +class StoryProductsElement extends StoryElement { + /// Toggle label while collapsed (`labels.show_carousel`); empty when not set. + final String showLabel; + + /// Toggle label while expanded (`labels.hide_carousel`); empty when not set. + final String hideLabel; + final List products; + + const StoryProductsElement({ + this.showLabel = '', + this.hideLabel = '', + required this.products, + }); + + factory StoryProductsElement.fromJson(Map json) { + final labels = json['labels']; + String label(String key) => + labels is Map ? (labels[key] as String? ?? '') : ''; + return StoryProductsElement( + showLabel: label('show_carousel'), + hideLabel: label('hide_carousel'), + products: _maps(json['products']).map(StoryProduct.fromJson).toList(), + ); + } +} + +/// `text_block`: a text over a media slide. +class StoryTextBlockElement extends StoryElement { + final String text; + + /// Font size in logical pixels; 14 when not set, as in the native SDKs. + final double fontSize; + + /// `serif`, `sans-serif`, `monospaced` or empty. + final String fontType; + final bool bold; + final bool italic; + + /// `left`, `center`, `right` or empty. + final String textAlign; + + /// `#RRGGBB`; empty — the kit's colour. + final String textColor; + + /// `#RRGGBB` behind the text; see [backgroundOpacity]. + final String backgroundColor; + + /// 0…1, from `"0%"`…`"100%"`. 0 — the text has no frame. + final double backgroundOpacity; + + /// Line height as a multiple of the font size; 0 — the font's own. + final double lineSpacing; + + /// Top of the block, in percent of the slide height. + final double yOffset; + + /// A code the block copies on tap; `null` when it has none. + final String? promocode; + + static const double defaultFontSize = 14; + + const StoryTextBlockElement({ + required this.text, + this.fontSize = defaultFontSize, + this.fontType = '', + this.bold = false, + this.italic = false, + this.textAlign = '', + this.textColor = '', + this.backgroundColor = '', + this.backgroundOpacity = 0, + this.lineSpacing = 0, + this.yOffset = 0, + this.promocode, + }); + + factory StoryTextBlockElement.fromJson(Map json) { + final promocode = json['promocode']; + return StoryTextBlockElement( + text: json['text_input'] as String? ?? '', + fontSize: toDoubleOrNull(json['font_size']) ?? defaultFontSize, + fontType: json['font_type'] as String? ?? '', + bold: json['bold'] == true || json['text_bold'] == true, + italic: json['italic'] == true, + textAlign: json['text_align'] as String? ?? '', + textColor: json['text_color'] as String? ?? '', + backgroundColor: json['text_background_color'] as String? ?? '', + backgroundOpacity: parseStoryOpacity( + json['text_background_color_opacity'], + ), + lineSpacing: toDoubleOrNull(json['text_line_spacing']) ?? 0, + yOffset: toDoubleOrNull(json['y_offset']) ?? 0, + promocode: promocode is String && promocode.isNotEmpty ? promocode : null, + ); + } +} + +/// A product of a stories block — the fields the kit shows and links to. +class StoryProduct { + final String id; + final String name; + final String brand; + + /// Resized copy of the image (`picture`), the one to show; empty when not set. + final String picture; + + /// Original image (`image_url`). + final String imageUrl; + final double price; + final String priceFormatted; + + /// Price before the discount, 0 when there is none. + final double oldPrice; + final String oldPriceFormatted; + + /// Discount in percent (`discount_percent`), 0 when there is none. Kept fractional: + /// the admin may send `12.5`. + final double discountPercent; + + /// Promo code for this product, empty when there is none. + final String promocode; + + /// Price with the promo code applied (`price_with_promocode`), 0 when not sent. + final double priceWithPromocode; + + /// Price with the promo code applied, formatted. + final String priceWithPromocodeFormatted; + final String currency; + final String url; + final String deeplinkAndroid; + final String deeplinkIos; + + const StoryProduct({ + required this.id, + required this.name, + this.brand = '', + this.picture = '', + this.imageUrl = '', + this.price = 0, + this.priceFormatted = '', + this.oldPrice = 0, + this.oldPriceFormatted = '', + this.discountPercent = 0, + this.promocode = '', + this.priceWithPromocode = 0, + this.priceWithPromocodeFormatted = '', + this.currency = '', + this.url = '', + this.deeplinkAndroid = '', + this.deeplinkIos = '', + }); + + factory StoryProduct.fromJson(Map json) { + String text(String key) => json[key]?.toString() ?? ''; + return StoryProduct( + id: text('id'), + name: text('name'), + brand: text('brand'), + picture: text('picture'), + imageUrl: text('image_url'), + price: toDoubleOrNull(json['price']) ?? 0, + priceFormatted: text('price_formatted'), + oldPrice: toDoubleOrNull(json['oldprice']) ?? 0, + oldPriceFormatted: text('oldprice_formatted'), + discountPercent: toDoubleOrNull(json['discount_percent']) ?? 0, + promocode: text('promocode'), + priceWithPromocode: toDoubleOrNull(json['price_with_promocode']) ?? 0, + priceWithPromocodeFormatted: text('price_with_promocode_formatted'), + currency: text('currency'), + url: text('url'), + deeplinkAndroid: text('deeplink_android'), + deeplinkIos: text('deeplink_ios'), + ); + } + + /// The old price is worth showing: it is set and above the current one. + bool get hasOldPrice => oldPrice > price && oldPriceFormatted.isNotEmpty; + + /// The image to show: the resized copy, else the original; empty when neither is set. + String get image => picture.isNotEmpty ? picture : imageUrl; +} + +/// Reads an opacity into 0…1. A string is percents with or without the sign (`"50%"`, +/// `"50"`), as the admin sends it and the native SDKs read it; a number above 1 is +/// percents too, otherwise a fraction. +double parseStoryOpacity(dynamic value) { + final isText = value is String; + final number = toDoubleOrNull(isText ? value.replaceAll('%', '') : value); + if (number == null || number <= 0) return 0; + final fraction = isText || number > 1 ? number / 100 : number; + return fraction.clamp(0, 1).toDouble(); +} + +Iterable> _maps(dynamic raw) { + if (raw is! List) return const []; + return raw.whereType().map(Map.from); +} diff --git a/lib/src/ui/components/personalization_accordion.dart b/lib/src/ui/components/personalization_accordion.dart new file mode 100644 index 0000000..31692bb --- /dev/null +++ b/lib/src/ui/components/personalization_accordion.dart @@ -0,0 +1,79 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; +import '../personalization_icons.dart'; + +/// Строка-аккордеон списка. +/// +/// Источник: Figma Mobile SDK UI Kit, секция List (241:10565), фрейм Accordion (241:10575). +/// Два варианта — Expanded=False и True, отличаются только направлением шеврона. +/// +/// Шеврон отдаётся путём к SVG-ассету: пакет не рисует SVG сам, +/// отрисовку выбирает потребитель через [iconBuilder]. +class PersonalizationAccordion extends StatelessWidget { + const PersonalizationAccordion({ + super.key, + required this.label, + this.count, + this.expanded = false, + this.onToggle, + this.iconBuilder, + }); + + final String label; + + /// Число в скобках после подписи. `null` — не показывать. + final int? count; + final bool expanded; + final ValueChanged? onToggle; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final style = TextStyle( + fontSize: 16, + height: 24 / 16, + letterSpacing: 0, + fontWeight: FontWeight.w400, + fontFamily: theme.fontFamily.familyFor(FontWeight.w400), + package: theme.fontFamily.package, + color: colors.textPrimary, + ); + final asset = expanded + ? PersonalizationIcons.angleUp + : PersonalizationIcons.angleDown; + + return GestureDetector( + onTap: onToggle == null ? null : () => onToggle!(!expanded), + child: Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text(label, style: style), + if (count != null) ...[ + const SizedBox(width: 4), + Text( + '($count)', + style: style.copyWith(color: colors.textSecondary), + ), + ], + const SizedBox(width: 4), + SizedBox( + width: 24, + height: 24, + child: iconBuilder?.call(context, asset, 24, colors.textPrimary), + ), + ], + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_badge.dart b/lib/src/ui/components/personalization_badge.dart new file mode 100644 index 0000000..44cd255 --- /dev/null +++ b/lib/src/ui/components/personalization_badge.dart @@ -0,0 +1,79 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Размер бейджа. +enum PersonalizationBadgeSize { sm, md, lg } + +/// Вид: warning — как в секции Badge, danger — бейдж скидки на карточке товара (Card/Product, 126:2263), тот же SM в цвете Semantic/Danger. +enum PersonalizationBadgeView { warning, danger } + +/// Бейдж дизайн-системы. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Badge (241:7434). +/// +/// Внимание: типографика бейджа не совпадает со ступенями [PersonalizationTypography] — +/// кегль берётся с одной ступени, интерлиньяж с другой (20/24, 16/20, 14/16). +/// Поэтому стиль собирается здесь явно, а не переиспользуется. +class PersonalizationBadge extends StatelessWidget { + const PersonalizationBadge({ + super.key, + required this.label, + this.size = PersonalizationBadgeSize.lg, + this.view = PersonalizationBadgeView.warning, + }); + + final String label; + final PersonalizationBadgeSize size; + final PersonalizationBadgeView view; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final (padH, padV, radius, fontSize, lineHeight) = switch (size) { + PersonalizationBadgeSize.lg => ( + 12.0, + 8.0, + PersonalizationRadiusToken.buttonLg, + 20.0, + 24.0, + ), + PersonalizationBadgeSize.md => ( + 8.0, + 4.0, + PersonalizationRadiusToken.buttonMd, + 16.0, + 20.0, + ), + PersonalizationBadgeSize.sm => ( + 4.0, + 2.0, + PersonalizationRadiusToken.buttonSm, + 14.0, + 16.0, + ), + }; + + return Container( + padding: EdgeInsets.symmetric(horizontal: padH, vertical: padV), + decoration: BoxDecoration( + color: view == PersonalizationBadgeView.danger + ? colors.semanticDanger + : colors.semanticWarning, + borderRadius: BorderRadius.circular(theme.radius.resolve(radius)), + ), + child: Text( + label, + style: TextStyle( + fontSize: fontSize, + height: lineHeight / fontSize, + fontWeight: FontWeight.w600, + fontFamily: theme.fontFamily.familyFor(FontWeight.w600), + package: theme.fontFamily.package, + color: colors.textLightPrimary, + ), + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_barcode.dart b/lib/src/ui/components/personalization_barcode.dart new file mode 100644 index 0000000..8dbffe6 --- /dev/null +++ b/lib/src/ui/components/personalization_barcode.dart @@ -0,0 +1,167 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +import 'personalization_code128.dart'; + +/// Штрихкод Code 128. +/// +/// Источник: Figma Mobile SDK UI Kit, компонент Wallet/Code (520:8886): штрихкод +/// 232×42 на белой подложке. Здесь только штрихи — подложку с полями рисует тот, +/// кто кладёт штрихкод (карта лояльности, промокод). +/// +/// Ширина модуля — целое число физических пикселей: дробные модули на экране +/// размываются, и сканер читает их хуже. Во Flutter разметка в логических +/// единицах, поэтому модуль считается через плотность экрана: +/// `floor(232 * dpr / модулей) / dpr`, не меньше `1 / dpr`. Штрихкод не +/// растягивается ровно на 232, а берёт наибольший целый модуль, при котором в +/// 232 помещается, — итоговая ширина чуть меньше и зависит от длины кода. Если +/// разметка даёт меньше 232, модуль считается от доступной ширины. Штрихи +/// чёрные в любой теме: сканеру нужен контраст, а не палитра. +/// +/// Строку, которую Code 128 не несёт (пустую, не ASCII), не рисует — размер +/// нулевой. Для скринридера штрихкод читается своей строкой. +class PersonalizationBarcode extends StatelessWidget { + const PersonalizationBarcode({super.key, required this.code}); + + /// Кодируемая строка — номер карты, промокод. + final String code; + + /// Ширина, в которую штрихкод вписывается, и его высота — из макета. + static const double preferredWidth = 232; + static const double preferredHeight = 42; + + @override + Widget build(BuildContext context) { + final modules = PersonalizationCode128.encode(code); + if (modules == null) return const SizedBox.shrink(); + return Semantics( + container: true, + label: code, + child: _Bars( + modules: modules, + devicePixelRatio: MediaQuery.maybeDevicePixelRatioOf(context) ?? 1, + ), + ); + } +} + +/// Штрихи как RenderBox, а не CustomPaint под LayoutBuilder: модуль зависит от +/// доступной ширины, а карта лояльности меряет содержимое через IntrinsicHeight, +/// которого LayoutBuilder не поддерживает. +class _Bars extends LeafRenderObjectWidget { + const _Bars({required this.modules, required this.devicePixelRatio}); + + final List modules; + final double devicePixelRatio; + + @override + _RenderBars createRenderObject(BuildContext context) => + _RenderBars(modules, devicePixelRatio); + + @override + void updateRenderObject(BuildContext context, _RenderBars renderObject) { + renderObject + ..modules = modules + ..devicePixelRatio = devicePixelRatio; + } +} + +class _RenderBars extends RenderBox { + _RenderBars(this._modules, this._devicePixelRatio); + + List _modules; + set modules(List value) { + if (listEquals(value, _modules)) return; + _modules = value; + markNeedsLayout(); + } + + double _devicePixelRatio; + set devicePixelRatio(double value) { + if (value == _devicePixelRatio) return; + _devicePixelRatio = value; + markNeedsLayout(); + } + + /// Модуль, найденный при последней разметке: пересчитывать его из размера при + /// отрисовке нельзя — погрешность деления может отнять целый пиксель. + double _module = 0; + + /// Ширина модуля в логических единицах при данной доступной ширине. + double _moduleFor(double maxWidth) { + final available = math.min(PersonalizationBarcode.preferredWidth, maxWidth); + // Эпсилон — против погрешности плотности вроде 2.625: 3.9999 не должно + // превратиться в 3. + final pixels = (available * _devicePixelRatio / _modules.length + 1e-6) + .floorToDouble(); + return math.max(1, pixels) / _devicePixelRatio; + } + + Size _sizeFor(BoxConstraints constraints, double module) => + constraints.constrain( + Size(_modules.length * module, PersonalizationBarcode.preferredHeight), + ); + + @override + Size computeDryLayout(covariant BoxConstraints constraints) => + _sizeFor(constraints, _moduleFor(constraints.maxWidth)); + + @override + void performLayout() { + _module = _moduleFor(constraints.maxWidth); + size = _sizeFor(constraints, _module); + } + + @override + double computeMinIntrinsicWidth(double height) => + _modules.length * _moduleFor(double.infinity); + + @override + double computeMaxIntrinsicWidth(double height) => + computeMinIntrinsicWidth(height); + + @override + double computeMinIntrinsicHeight(double width) => + PersonalizationBarcode.preferredHeight; + + @override + double computeMaxIntrinsicHeight(double width) => + PersonalizationBarcode.preferredHeight; + + @override + void paint(PaintingContext context, Offset offset) { + final canvas = context.canvas; + final drawn = _modules.length * _module; + // По центру, если разметка дала больше, чем занимают модули. Начало + // прижато к физическому пикселю, иначе края всех штрихов лягут между + // пикселями. + final dpr = _devicePixelRatio; + double x = offset.dx + (size.width - drawn) / 2; + x = (x * dpr).roundToDouble() / dpr; + + // Без сглаживания: край штриха либо закрашен, либо нет — полупрозрачная + // кромка сканеру только мешает. + final paint = Paint() + // Чёрный, а не токен: сканеру нужен контраст в любой теме. + ..color = const Color(0xFF000000) + ..isAntiAlias = false; + + int i = 0; + while (i < _modules.length) { + int run = 1; + while (i + run < _modules.length && _modules[i + run] == _modules[i]) { + run++; + } + if (_modules[i]) { + canvas.drawRect( + Rect.fromLTWH(x, offset.dy, run * _module, size.height), + paint, + ); + } + x += run * _module; + i += run; + } + } +} diff --git a/lib/src/ui/components/personalization_button.dart b/lib/src/ui/components/personalization_button.dart new file mode 100644 index 0000000..b6bacf5 --- /dev/null +++ b/lib/src/ui/components/personalization_button.dart @@ -0,0 +1,279 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_colors.dart'; +import '../personalization_theme.dart'; + +/// Размер кнопки. +enum PersonalizationButtonSize { lg, md, sm } + +/// Вид кнопки. +enum PersonalizationButtonView { primary, secondary, ghost } + +/// Кнопка дизайн-системы. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Button (90:862), фрейм 90:869. +/// Матрица: 3 размера x 3 вида x 3 состояния x 4 конфигурации контента. +/// +/// Состояние Focus из макета — это нажатие, оно ведётся внутри виджета. +/// Disabled наступает, когда [onPressed] не задан. +/// +/// Иконки отдаются путями к SVG-ассетам ([PersonalizationIcons]): пакет не +/// рисует SVG сам, отрисовку выбирает потребитель через [iconBuilder]. +class PersonalizationButton extends StatefulWidget { + const PersonalizationButton({ + super.key, + this.label, + this.size = PersonalizationButtonSize.lg, + this.view = PersonalizationButtonView.primary, + this.onPressed, + this.iconStart, + this.iconEnd, + this.iconBuilder, + this.onDark = false, + this.rounded = false, + }); + + final String? label; + final PersonalizationButtonSize size; + final PersonalizationButtonView view; + + /// Не задан — кнопка недоступна. + final VoidCallback? onPressed; + + /// Кнопка стоит поверх тёмного (картинки-фона). В макете такие контролы берут + /// инвертированную палитру: заливка Secondary белая 5%, подпись и иконка светлые. + /// На [PersonalizationButtonView.primary] не влияет — она и так светлая по тексту. + final bool onDark; + + /// Скругление Rounded вместо радиуса размера: кнопка-иконка становится кругом. + /// Так в макете устроен крестик Close (секция Button) — кнопка MD Secondary, + /// у которой радиус переопределён на Rounded. + final bool rounded; + + /// Ассет иконки перед текстом. Без текста кнопка становится кнопкой-иконкой. + final String? iconStart; + + /// Ассет иконки после текста. + final String? iconEnd; + + /// Как нарисовать иконку заданного размера и цвета из ассета. Не задан — + /// место под иконку остаётся пустым, но отступы сохраняются. + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + State createState() => _PersonalizationButtonState(); +} + +class _PersonalizationButtonState extends State { + bool _pressed = false; + + bool get _enabled => widget.onPressed != null; + + bool get _hasText => widget.label != null && widget.label!.isNotEmpty; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final metrics = _metrics[widget.size]!; + final foreground = _foreground(colors); + + final children = [ + if (widget.iconStart != null) + _icon(context, widget.iconStart!, metrics, foreground), + if (_hasText) + Text( + widget.label!, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: metrics.fontSize, + height: metrics.lineHeight / metrics.fontSize, + letterSpacing: metrics.letterSpacing, + fontWeight: FontWeight.w600, + fontFamily: theme.fontFamily.familyFor(FontWeight.w600), + package: theme.fontFamily.package, + color: foreground, + ), + ), + if (widget.iconEnd != null) + _icon(context, widget.iconEnd!, metrics, foreground), + ]; + + return GestureDetector( + onTap: widget.onPressed, + onTapDown: _enabled ? (_) => setState(() => _pressed = true) : null, + onTapUp: _enabled ? (_) => setState(() => _pressed = false) : null, + onTapCancel: _enabled ? () => setState(() => _pressed = false) : null, + child: Container( + padding: _padding(metrics), + decoration: BoxDecoration( + color: _background(colors), + borderRadius: BorderRadius.circular( + theme.radius.resolve( + widget.rounded + ? PersonalizationRadiusToken.rounded + : metrics.radius, + ), + ), + ), + 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], + ], + ], + ), + ), + ); + } + + Widget _icon( + BuildContext context, + String asset, + _ButtonMetrics metrics, + Color color, + ) { + return SizedBox( + width: metrics.iconSize, + height: metrics.iconSize, + child: widget.iconBuilder?.call(context, asset, metrics.iconSize, color), + ); + } + + EdgeInsets _padding(_ButtonMetrics metrics) { + if (!_hasText) { + // Кнопка-иконка: по вертикали как у текстовой, по горизонтали своё — 12/8/4. + return EdgeInsets.symmetric( + vertical: metrics.paddingVertical, + horizontal: metrics.paddingIconOnly, + ); + } + return EdgeInsets.only( + left: widget.iconStart != null + ? metrics.paddingNarrow + : metrics.paddingWide, + right: widget.iconEnd != null + ? metrics.paddingNarrow + : metrics.paddingWide, + top: metrics.paddingVertical, + bottom: metrics.paddingVertical, + ); + } + + Color _background(PersonalizationColors colors) { + if (!_enabled) { + switch (widget.view) { + case PersonalizationButtonView.primary: + return colors.buttonPrimaryDisabled; + case PersonalizationButtonView.secondary: + return colors.buttonSecondaryDisabled; + case PersonalizationButtonView.ghost: + return colors.backgroundTransparent; + } + } + if (_pressed) { + // Ghost в нажатии красится тем же, что и Secondary. + return widget.view == PersonalizationButtonView.primary + ? colors.buttonPrimaryFocus + : colors.buttonSecondaryFocus; + } + switch (widget.view) { + // Кнопка привязана к Brand/Primary, а не к Button/Primary — так в макете. + case PersonalizationButtonView.primary: + return colors.brandPrimary; + case PersonalizationButtonView.secondary: + return widget.onDark + ? colors.buttonSecondaryOnDark + : colors.buttonSecondary; + case PersonalizationButtonView.ghost: + return colors.backgroundTransparent; + } + } + + Color _foreground(PersonalizationColors colors) { + if (widget.view == PersonalizationButtonView.primary || widget.onDark) { + return _enabled ? colors.textLightPrimary : colors.textLightHint; + } + return _enabled ? colors.textPrimary : colors.textHint; + } +} + +class _ButtonMetrics { + const _ButtonMetrics({ + required this.fontSize, + required this.lineHeight, + required this.letterSpacing, + required this.radius, + required this.paddingVertical, + required this.paddingWide, + required this.paddingNarrow, + required this.paddingIconOnly, + required this.iconSize, + }); + + final double fontSize; + final double lineHeight; + final double letterSpacing; + final PersonalizationRadiusToken radius; + final double paddingVertical; + + /// Горизонтальный отступ со стороны без иконки. + final double paddingWide; + + /// Горизонтальный отступ со стороны с иконкой. + final double paddingNarrow; + + /// Горизонтальный отступ кнопки-иконки: у LG он 12 при вертикальном 8, + /// у остальных равен вертикальному. + final double paddingIconOnly; + final double iconSize; +} + +const Map _metrics = + { + PersonalizationButtonSize.lg: _ButtonMetrics( + fontSize: 20, + lineHeight: 32, + letterSpacing: 0, + radius: PersonalizationRadiusToken.buttonLg, + paddingVertical: 8, + paddingWide: 24, + paddingNarrow: 16, + paddingIconOnly: 12, + iconSize: 32, + ), + PersonalizationButtonSize.md: _ButtonMetrics( + fontSize: 16, + lineHeight: 24, + letterSpacing: 0, + radius: PersonalizationRadiusToken.buttonMd, + paddingVertical: 8, + paddingWide: 16, + paddingNarrow: 12, + paddingIconOnly: 8, + iconSize: 24, + ), + // SM берёт кегль со ступени sm, а интерлиньяж со ступени base: + // в макете 14/24, тогда как ступень sm — это 14/20. + PersonalizationButtonSize.sm: _ButtonMetrics( + fontSize: 14, + lineHeight: 24, + letterSpacing: 0.05, + radius: PersonalizationRadiusToken.buttonSm, + paddingVertical: 4, + paddingWide: 12, + paddingNarrow: 8, + paddingIconOnly: 4, + iconSize: 20, + ), + }; diff --git a/lib/src/ui/components/personalization_button_group.dart b/lib/src/ui/components/personalization_button_group.dart new file mode 100644 index 0000000..062b769 --- /dev/null +++ b/lib/src/ui/components/personalization_button_group.dart @@ -0,0 +1,141 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Размер группы кнопок. +enum PersonalizationButtonGroupSize { md, sm } + +/// Сегмент группы. +class PersonalizationButtonGroupItem { + const PersonalizationButtonGroupItem({required this.icon, this.activeIcon}); + + /// Ассет иконки сегмента. + final String icon; + + /// Ассет иконки выбранного сегмента. В макете Grid оставляет ту же иконку, + /// а List подменяет её на залитую, поэтому это отдельное поле. + final String? activeIcon; +} + +/// Группа кнопок (сегментированный переключатель). +/// +/// Источник: Figma Mobile SDK UI Kit, секция Button Group (185:5253): +/// фрейм Base Button (185:5315) — сегмент, фрейм Button Group (185:5484) — сама группа. +/// +/// В макете нарисован только случай на два сегмента (Grid/List) в размере MD, +/// сегмент же есть и в MD, и в SM — поэтому размер вынесен в API, +/// а число сегментов не ограничено. +class PersonalizationButtonGroup extends StatelessWidget { + const PersonalizationButtonGroup({ + super.key, + required this.items, + this.selectedIndex = 0, + this.size = PersonalizationButtonGroupSize.md, + this.onSelected, + this.iconBuilder, + }); + + final List items; + final int selectedIndex; + final PersonalizationButtonGroupSize size; + final ValueChanged? onSelected; + + /// Как нарисовать иконку заданного размера и цвета из ассета. Не задан — + /// место под иконку остаётся пустым, но отступы сохраняются. + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final metrics = _groupMetrics[size]!; + final side = metrics.iconSize + metrics.padding * 2; + + return Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration( + color: colors.buttonSecondary, + borderRadius: BorderRadius.circular( + theme.radius.resolve(PersonalizationRadiusToken.buttonMd), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (int index = 0; index < items.length; index++) ...[ + if (index > 0) const SizedBox(width: 2), + _segment(context, theme, metrics, side, index), + ], + ], + ), + ); + } + + Widget _segment( + BuildContext context, + PersonalizationTheme theme, + _GroupMetrics metrics, + double side, + int index, + ) { + final colors = theme.colors; + final item = items[index]; + final active = index == selectedIndex; + final asset = active ? (item.activeIcon ?? item.icon) : item.icon; + final tint = active ? colors.textInvertedPrimary : colors.textHint; + + return GestureDetector( + onTap: onSelected == null ? null : () => onSelected!(index), + child: Container( + width: side, + height: side, + alignment: Alignment.center, + decoration: BoxDecoration( + color: active ? colors.buttonPrimary : colors.backgroundTransparent, + borderRadius: BorderRadius.circular( + theme.radius.resolve(metrics.radius), + ), + ), + child: SizedBox( + width: metrics.iconSize, + height: metrics.iconSize, + child: iconBuilder?.call(context, asset, metrics.iconSize, tint), + ), + ), + ); + } +} + +class _GroupMetrics { + const _GroupMetrics({ + required this.radius, + required this.padding, + required this.iconSize, + }); + + final PersonalizationRadiusToken radius; + + /// Отступ сегмента: 6 в MD и 2 в SM, обоих значений нет в шкале спейсингов. + final double padding; + final double iconSize; +} + +const Map _groupMetrics = + { + PersonalizationButtonGroupSize.md: _GroupMetrics( + radius: PersonalizationRadiusToken.segmentedMd, + padding: 6, + iconSize: 24, + ), + PersonalizationButtonGroupSize.sm: _GroupMetrics( + radius: PersonalizationRadiusToken.segmentedSm, + padding: 2, + iconSize: 20, + ), + }; diff --git a/lib/src/ui/components/personalization_catalog.dart b/lib/src/ui/components/personalization_catalog.dart new file mode 100644 index 0000000..833a1e5 --- /dev/null +++ b/lib/src/ui/components/personalization_catalog.dart @@ -0,0 +1,254 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_icons.dart'; +import '../personalization_spacing.dart'; +import 'personalization_button.dart'; +import 'personalization_count.dart'; +import 'personalization_empty_state.dart'; +import 'personalization_loader.dart'; +import 'personalization_product.dart'; +import 'personalization_product_card.dart'; +import 'personalization_product_image.dart'; +import 'personalization_products_list.dart'; + +/// Счётчик каталога «показано N из M». Слова — параметры. +@immutable +class PersonalizationCatalogCount { + const PersonalizationCatalogCount({ + required this.prefix, + required this.shown, + required this.separator, + required this.total, + }); + + final String prefix; + final int shown; + final String separator; + final int total; +} + +/// Экран каталога: заголовок, плитка или список товаров, внизу лоадер, счётчик +/// и кнопка «загрузить ещё». +/// +/// Источник: Figma Mobile SDK UI Kit, секция Card — Search results (167:4477) и +/// Category (167:4856). Оба одной формы, разница только в заголовке: у выдачи +/// [PersonalizationSearchResultsTitle], у категории [PersonalizationTitle] с +/// переключателем вида. Поэтому заголовок здесь — слот, а не вариант. +/// Три нижних элемента в макете скрываемые (showLoader, showCount, showLoadMore). +/// Шаг блока 12, шаг плитки и списка 16 по обеим осям. +/// +/// Пустая выдача — страница SearchResultsScreen, Search Results/Empty State (319:7743): +/// заголовок тот же, вместо плитки [PersonalizationEmptyState]. Показывается, когда +/// задан [emptyText] и товаров нет. +/// +/// Весь каталог — одна лента: заголовок, карточки и нижние элементы — её части, а +/// карточки строятся только под видимую часть, сколько бы страниц ни догрузилось. +/// Поэтому его не вкладывают в прокрутку, он прокручивается сам. Внутри чужой +/// вертикальной прокрутки ([scrollable] `false` или высота не ограничена) он +/// раскладывается целиком, как обычный блок, и сам не прокручивается. +class PersonalizationCatalog extends StatelessWidget { + const PersonalizationCatalog({ + super.key, + this.header, + this.layout = PersonalizationProductsLayout.grid, + required this.products, + this.imageAspect = PersonalizationProductImageAspect.square, + this.onProductAction, + this.onProductTap, + this.emptyText, + this.loading = false, + this.count, + this.loadMoreText, + this.onLoadMore, + this.iconBuilder, + this.scrollable = true, + this.controller, + this.padding, + }); + + final Widget? header; + final PersonalizationProductsLayout layout; + final List products; + + /// Пропорция картинок карточек, см. [PersonalizationProductCard.imageAspect]. + final PersonalizationProductImageAspect imageAspect; + final ValueChanged? onProductAction; + + /// Нажатие на карточку — открыть товар. + final ValueChanged? onProductTap; + + /// Текст пустой выдачи. `null` — без пустого состояния, плитка остаётся на месте. + final String? emptyText; + final bool loading; + final PersonalizationCatalogCount? count; + + /// Подпись кнопки «загрузить ещё». `null` — без кнопки. + final String? loadMoreText; + final VoidCallback? onLoadMore; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + /// Прокручивается ли каталог сам. `false` — раскладывается целиком по высоте + /// содержимого и не прокручивается: так его кладут в чужую вертикальную прокрутку. + /// Где высота не ограничена (колонка, скролл), он и без флага раскладывается целиком. + final bool scrollable; + + /// Контроллер собственной прокрутки: следить за ней (бесконечная прокрутка) и + /// возвращать ленту к началу. + final ScrollController? controller; + + /// Поля ленты. Содержимое прокручивается под ними, а не обрезается по их краю. + final EdgeInsetsGeometry? padding; + + /// Шаг между блоками каталога. + static const double _gapBlock = PersonalizationSpacing.lg; + + /// Шаг карточек плитки и списка по обеим осям. + static const double _gapTile = PersonalizationSpacing.xl; + + @override + Widget build(BuildContext context) { + if (!scrollable) return _list(embedded: true); + // Высота не ограничена — каталог положили в колонку или чужой скролл без флага: + // раскладываем целиком, как обычный блок, а не падаем на вьюпорте без высоты. + return LayoutBuilder( + builder: (context, constraints) => + _list(embedded: !constraints.hasBoundedHeight), + ); + } + + Widget _list({required bool embedded}) { + final bool empty = products.isEmpty && (emptyText ?? '').isNotEmpty; + final bool grid = layout == PersonalizationProductsLayout.grid; + // Плитка идёт строками по две карточки, список — по одной. + final int rows = grid ? (products.length + 1) ~/ 2 : products.length; + final footer = [ + if (empty) PersonalizationEmptyState(message: emptyText!), + // Во фреймах с лоадером (296:3544, 299:6606) счётчика и кнопки нет — на время + // загрузки лоадер встаёт на их место. + if (loading) const PersonalizationLoader(), + if (count != null && !loading) + PersonalizationCount( + prefix: count!.prefix, + shown: count!.shown, + separator: count!.separator, + 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, + ), + ]; + + return CustomScrollView( + controller: controller, + // Вложенный каталог не прокручивается и не должен забирать чужой + // PrimaryScrollController. + primary: embedded ? false : null, + shrinkWrap: embedded, + physics: embedded ? const NeverScrollableScrollPhysics() : null, + slivers: [ + SliverPadding( + padding: padding ?? EdgeInsets.zero, + sliver: SliverMainAxisGroup( + slivers: [ + // Заголовок и нижние элементы — отдельные слайверы: они живут, пока жив + // каталог, и не теряют состояние, уехав за экран. Строится лениво только + // лента карточек. + if (header != null) SliverToBoxAdapter(child: header), + if (rows > 0) + SliverPadding( + padding: EdgeInsets.only(top: header != null ? _gapBlock : 0), + sliver: SliverList.separated( + itemCount: rows, + itemBuilder: (context, row) => grid + ? _gridRow(row) + : _card( + products[row], + PersonalizationProductCardType.list, + ), + separatorBuilder: (_, _) => + const SizedBox(height: _gapTile), + ), + ), + if (footer.isNotEmpty) + SliverToBoxAdapter( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + for (int i = 0; i < footer.length; i++) ...[ + if (i > 0 || header != null || rows > 0) + const SizedBox(height: _gapBlock), + footer[i], + ], + ], + ), + ), + ], + ), + ), + ], + ); + } + + /// Строка плитки. IntrinsicHeight + stretch: соседние карточки одной высоты, и + /// цена с кнопкой у них на одной линии (см. [PersonalizationProductsList]). + Widget _gridRow(int row) { + final int first = row * 2; + return IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: _card(products[first], PersonalizationProductCardType.grid), + ), + const SizedBox(width: _gapTile), + Expanded( + child: first + 1 < products.length + ? _card( + products[first + 1], + PersonalizationProductCardType.grid, + ) + : const SizedBox.shrink(), + ), + ], + ), + ); + } + + /// Карточка товара — так же, как её собирает [PersonalizationProductsList]. + Widget _card( + PersonalizationProduct product, + PersonalizationProductCardType type, + ) { + return PersonalizationProductCard( + type: type, + image: product.image, + imageAspect: imageAspect, + brand: product.brand, + name: product.name, + rating: product.rating, + price: product.price, + oldPrice: product.oldPrice, + discount: product.discount, + actionText: product.actionText, + onAction: onProductAction == null + ? null + : () => onProductAction!(product), + onTap: onProductTap == null ? null : () => onProductTap!(product), + iconBuilder: iconBuilder, + ); + } +} diff --git a/lib/src/ui/components/personalization_checkbox.dart b/lib/src/ui/components/personalization_checkbox.dart new file mode 100644 index 0000000..d8f9232 --- /dev/null +++ b/lib/src/ui/components/personalization_checkbox.dart @@ -0,0 +1,129 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Состояние чекбокса. +enum PersonalizationCheckboxState { unchecked, checked, indeterminate } + +/// Чекбокс дизайн-системы, 20x20. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Input, фрейм Checkbox (205:10128). +/// В макете только размер MD, поэтому размера в API нет. +/// +/// Галка и черта рисуются штрихом по геометрии из макета: +/// `M5 10 L8.75 13.75 L15 7.5` и `M5 10 H15`, толщина 2, круглые концы. +class PersonalizationCheckbox extends StatelessWidget { + const PersonalizationCheckbox({ + super.key, + this.state = PersonalizationCheckboxState.unchecked, + this.disabled = false, + this.onChanged, + }); + + final PersonalizationCheckboxState state; + final bool disabled; + + /// Зовётся с состоянием, в которое чекбокс переходит по нажатию. + final ValueChanged? onChanged; + + static const double size = 20; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final isFilled = state != PersonalizationCheckboxState.unchecked; + + final Widget box = CustomPaint( + size: const Size.square(size), + painter: _CheckboxPainter( + state: state, + fill: isFilled + ? (disabled ? colors.buttonPrimaryDisabled : colors.buttonPrimary) + : (disabled + ? colors.backgroundInputDisabled + : colors.backgroundInput), + border: isFilled ? null : colors.lineInput, + glyph: colors.textLightPrimary, + radius: theme.radius.resolve(PersonalizationRadiusToken.sm), + ), + ); + + if (disabled || onChanged == null) return box; + + return GestureDetector( + onTap: () => onChanged!( + state == PersonalizationCheckboxState.checked + ? PersonalizationCheckboxState.unchecked + : PersonalizationCheckboxState.checked, + ), + child: box, + ); + } +} + +class _CheckboxPainter extends CustomPainter { + const _CheckboxPainter({ + required this.state, + required this.fill, + required this.border, + required this.glyph, + required this.radius, + }); + + final PersonalizationCheckboxState state; + final Color fill; + final Color? border; + final Color glyph; + final double radius; + + @override + void paint(Canvas canvas, Size size) { + final rect = Offset.zero & size; + final rrect = RRect.fromRectAndRadius(rect, Radius.circular(radius)); + + canvas.drawRRect(rrect, Paint()..color = fill); + + if (border != null) { + // Рамка внутрь, чтобы внешний размер остался ровно 20. + final inset = rect.deflate(0.5); + canvas.drawRRect( + RRect.fromRectAndRadius(inset, Radius.circular(radius)), + Paint() + ..color = border! + ..style = PaintingStyle.stroke + ..strokeWidth = 1, + ); + } + + if (state == PersonalizationCheckboxState.unchecked) return; + + final stroke = Paint() + ..color = glyph + ..style = PaintingStyle.stroke + ..strokeWidth = 2 + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round; + + final path = Path(); + if (state == PersonalizationCheckboxState.checked) { + path + ..moveTo(5, 10) + ..lineTo(8.75, 13.75) + ..lineTo(15, 7.5); + } else { + path + ..moveTo(5, 10) + ..lineTo(15, 10); + } + canvas.drawPath(path, stroke); + } + + @override + bool shouldRepaint(_CheckboxPainter old) => + old.state != state || + old.fill != fill || + old.border != border || + old.glyph != glyph || + old.radius != radius; +} diff --git a/lib/src/ui/components/personalization_checkbox_with_label.dart b/lib/src/ui/components/personalization_checkbox_with_label.dart new file mode 100644 index 0000000..c6ec6b7 --- /dev/null +++ b/lib/src/ui/components/personalization_checkbox_with_label.dart @@ -0,0 +1,61 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; +import 'personalization_checkbox.dart'; + +/// Чекбокс с подписью. +/// +/// Источник: Figma Mobile SDK UI Kit, фрейм Checkbox with Label (205:10151). +/// Зазор 8, подпись 16/20 обычного начертания; в disabled подпись уходит +/// в Text/Hint. +class PersonalizationCheckboxWithLabel extends StatelessWidget { + const PersonalizationCheckboxWithLabel({ + super.key, + required this.label, + this.state = PersonalizationCheckboxState.unchecked, + this.disabled = false, + this.onChanged, + }); + + final String label; + final PersonalizationCheckboxState state; + final bool disabled; + final ValueChanged? onChanged; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + + final row = Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + PersonalizationCheckbox(state: state, disabled: disabled), + const SizedBox(width: 8), + Text( + label, + style: TextStyle( + fontSize: 16, + height: 20 / 16, + fontWeight: FontWeight.w400, + fontFamily: theme.fontFamily.familyFor(FontWeight.w400), + package: theme.fontFamily.package, + color: disabled ? colors.textHint : colors.textPrimary, + ), + ), + ], + ); + + if (disabled || onChanged == null) return row; + + return GestureDetector( + onTap: () => onChanged!( + state == PersonalizationCheckboxState.checked + ? PersonalizationCheckboxState.unchecked + : PersonalizationCheckboxState.checked, + ), + child: row, + ); + } +} diff --git a/lib/src/ui/components/personalization_code128.dart b/lib/src/ui/components/personalization_code128.dart new file mode 100644 index 0000000..71d5f45 --- /dev/null +++ b/lib/src/ui/components/personalization_code128.dart @@ -0,0 +1,100 @@ +/// Кодировщик штрихкода Code 128 — то, что рисует `PersonalizationBarcode`. +/// +/// Номер карты лояльности в макете (Wallet/Code, 520:8886) — линейный штрихкод, +/// а Code 128 — формат, который читают кассовые сканеры и Apple Wallet. +/// Библиотеку ради сотни строк таблицы SDK не тянет. +/// +/// Набор выбирается целиком на строку: одни цифры — набор C (две цифры на символ, +/// код вдвое короче), при нечётной длине последняя цифра уходит в набор B через +/// переключатель CODE B. Всё прочее — набор B, печатный ASCII 32…126. Строку с +/// другими символами Code 128 без расширений не несёт — тогда кодировщик +/// возвращает null, и штрихкода нет. +/// +/// В барель кита не входит: это внутренность штрихкода, наружу торчит только +/// виджет. Тесты импортируют файл напрямую. +abstract final class PersonalizationCode128 { + /// Символы строки: значения по порядку, от старт-символа до контрольного + /// включительно. Строку, которую набор не несёт, — null. + static List? values(String text) { + if (text.isEmpty) return null; + final units = text.codeUnits; + if (units.any((unit) => unit < 32 || unit > 126)) return null; + + final values = []; + final digits = units.every((unit) => unit >= 0x30 && unit <= 0x39); + if (digits && units.length >= 2) { + values.add(_startC); + final pairs = units.length ~/ 2; + for (int i = 0; i < pairs; i++) { + values.add(int.parse(text.substring(i * 2, i * 2 + 2))); + } + if (units.length.isOdd) { + values + ..add(_codeB) + ..add(units.last - 32); + } + } else { + values.add(_startB); + for (final unit in units) { + values.add(unit - 32); + } + } + values.add(checksum(values)); + return values; + } + + /// Модули слева направо, `true` — штрих. Тихих зон по краям нет — их даёт + /// подложка. + static List? encode(String text) { + final symbols = values(text); + if (symbols == null) return null; + final modules = []; + for (final value in [...symbols, _stop]) { + final pattern = _patterns[value]; + for (int i = 0; i < pattern.length; i++) { + final width = pattern.codeUnitAt(i) - 0x30; + // Ширины идут парами «штрих, пробел», начиная со штриха. + for (int k = 0; k < width; k++) { + modules.add(i.isEven); + } + } + } + return modules; + } + + /// Старт-символ плюс сумма значений, взвешенных позицией с единицы, по + /// модулю 103. [symbols] — от старт-символа до последнего символа данных. + static int checksum(List symbols) { + int sum = symbols.first; + for (int i = 1; i < symbols.length; i++) { + sum += i * symbols[i]; + } + return sum % 103; + } + + static const int _codeB = 100; + static const int _startB = 104; + static const int _startC = 105; + static const int _stop = 106; + + /// Ширины штрихов и пробелов символа, начиная со штриха; индекс — значение + /// символа. 103–105 — старт-символы A/B/C, 106 — стоп (13 модулей). + static const List _patterns = [ + '212222', '222122', '222221', '121223', '121322', '131222', '122213', // + '122312', '132212', '221213', '221312', '231212', '112232', '122132', // + '122231', '113222', '123122', '123221', '223211', '221132', '221231', // + '213212', '223112', '312131', '311222', '321122', '321221', '312212', // + '322112', '322211', '212123', '212321', '232121', '111323', '131123', // + '131321', '112313', '132113', '132311', '211313', '231113', '231311', // + '112133', '112331', '132131', '113123', '113321', '133121', '313121', // + '211331', '231131', '213113', '213311', '213131', '311123', '311321', // + '331121', '312113', '312311', '332111', '314111', '221411', '431111', // + '111224', '111422', '121124', '121421', '141122', '141221', '112214', // + '112412', '122114', '122411', '142112', '142211', '241211', '221114', // + '413111', '241112', '134111', '111242', '121142', '121241', '114212', // + '124112', '124211', '411212', '421112', '421211', '212141', '214121', // + '412121', '111143', '111341', '131141', '114113', '114311', '411113', // + '411311', '113141', '114131', '311141', '411131', '211412', '211214', // + '211232', '2331112', // + ]; +} diff --git a/lib/src/ui/components/personalization_count.dart b/lib/src/ui/components/personalization_count.dart new file mode 100644 index 0000000..dcd1ad5 --- /dev/null +++ b/lib/src/ui/components/personalization_count.dart @@ -0,0 +1,65 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Счётчик «показано N из M». +/// +/// Источник: Figma Mobile SDK UI Kit, секция Navigation (90:660), символ Count (301:6810). +/// Слова — параметры, а не константы: локализация остаётся за интегратором. +/// В макете это «Showed 6 from 569». +class PersonalizationCount extends StatelessWidget { + const PersonalizationCount({ + super.key, + required this.prefix, + required this.shown, + required this.separator, + required this.total, + }); + + /// Слово перед первым числом («Показано»). + final String prefix; + final int shown; + + /// Слово между числами («из»). + final String separator; + final int total; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + const double fontSize = 16; + final TextStyle regular = TextStyle( + fontSize: fontSize, + height: 24 / fontSize, + letterSpacing: 0, + fontWeight: FontWeight.w400, + fontFamily: theme.fontFamily.familyFor(FontWeight.w400), + package: theme.fontFamily.package, + color: colors.textSecondary, + ); + final TextStyle strong = regular.copyWith( + fontWeight: FontWeight.w600, + fontFamily: theme.fontFamily.familyFor(FontWeight.w600), + package: theme.fontFamily.package, + color: colors.textPrimary, + ); + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(prefix, style: regular), + const SizedBox(width: 4), + Text('$shown', style: strong), + const SizedBox(width: 4), + Text(separator, style: regular), + const SizedBox(width: 4), + Text('$total', style: strong), + ], + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_dots.dart b/lib/src/ui/components/personalization_dots.dart new file mode 100644 index 0000000..6b97b13 --- /dev/null +++ b/lib/src/ui/components/personalization_dots.dart @@ -0,0 +1,47 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Точки-индикатор карусели. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Navigation (90:660), +/// символы Dots (90:669) и Dot (90:685). +/// В макете нарисовано пять точек, число вынесено в API. +class PersonalizationDots extends StatelessWidget { + const PersonalizationDots({ + super.key, + required this.count, + this.selectedIndex = 0, + }); + + final int count; + final int selectedIndex; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + for (int index = 0; index < count; index++) ...[ + if (index > 0) const SizedBox(width: 12), + Container( + width: 16, + height: 16, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: index == selectedIndex + ? colors.brandPrimary + : colors.lineGeneric, + ), + ), + ], + ], + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_empty_state.dart b/lib/src/ui/components/personalization_empty_state.dart new file mode 100644 index 0000000..b3a9612 --- /dev/null +++ b/lib/src/ui/components/personalization_empty_state.dart @@ -0,0 +1,41 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Пустое состояние дизайн-системы. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Empty State (319:7736). +/// Горизонтальные отступы 16, вертикальные 92, текст по центру ступенью +/// XL/Default цветом Text/Secondary. +/// +/// Текст не зашит: в макете стоит «No results for your request.», но строку +/// подставляет потребитель — локализация остаётся на его стороне. +class PersonalizationEmptyState extends StatelessWidget { + const PersonalizationEmptyState({super.key, required this.message}); + + final String message; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 92), + child: Center( + child: Text( + message, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 20, + height: 32 / 20, + fontWeight: FontWeight.w400, + fontFamily: theme.fontFamily.familyFor(FontWeight.w400), + package: theme.fontFamily.package, + color: colors.textSecondary, + ), + ), + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_favorites_badge.dart b/lib/src/ui/components/personalization_favorites_badge.dart new file mode 100644 index 0000000..a849f31 --- /dev/null +++ b/lib/src/ui/components/personalization_favorites_badge.dart @@ -0,0 +1,40 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_icons.dart'; +import '../personalization_theme.dart'; + +/// Метка «в избранном»: звезда в круге цвета Semantic/Warning, 24x24. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Badge, символ Favorites (391:17117). +class PersonalizationFavoritesBadge extends StatelessWidget { + const PersonalizationFavoritesBadge({super.key, this.iconBuilder}); + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + return Container( + // Звезда 16 плюс поле 4 с каждой стороны. + width: 24, + height: 24, + padding: const EdgeInsets.all(4), + decoration: BoxDecoration( + shape: BoxShape.circle, + color: colors.semanticWarning, + ), + child: iconBuilder?.call( + context, + PersonalizationIcons.starFill, + 16, + colors.textLightPrimary, + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_filters.dart b/lib/src/ui/components/personalization_filters.dart new file mode 100644 index 0000000..92707af --- /dev/null +++ b/lib/src/ui/components/personalization_filters.dart @@ -0,0 +1,410 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_icons.dart'; +import '../personalization_theme.dart'; +import '../personalization_typography.dart'; +import 'personalization_accordion.dart'; +import 'personalization_button.dart'; +import 'personalization_checkbox.dart'; +import 'personalization_checkbox_with_label.dart'; +import 'personalization_input_field.dart'; +import 'personalization_title.dart'; + +/// Вариант в секции чекбоксов фильтров. +@immutable +class PersonalizationFilterOption { + const PersonalizationFilterOption({ + required this.id, + required this.label, + this.checked = false, + }); + + final String id; + final String label; + final bool checked; + + PersonalizationFilterOption copyWith({bool? checked}) => + PersonalizationFilterOption( + id: id, + label: label, + checked: checked ?? this.checked, + ); +} + +/// Секция экрана фильтров: диапазон или список чекбоксов. +@immutable +sealed class PersonalizationFilterSection { + const PersonalizationFilterSection({required this.id, required this.title}); + + final String id; + final String title; +} + +/// Два поля «от — до». [select] — поля типа Select, список открывает хост. +/// [fromPlaceholder] / [toPlaceholder] — подсказки в пустых полях, например границы диапазона. +class PersonalizationFilterRange extends PersonalizationFilterSection { + const PersonalizationFilterRange({ + required super.id, + required super.title, + required this.fromLabel, + required this.toLabel, + this.from, + this.to, + this.select = false, + this.fromPlaceholder, + this.toPlaceholder, + }); + + final String fromLabel; + final String toLabel; + final String? from; + final String? to; + final bool select; + final String? fromPlaceholder; + final String? toPlaceholder; + + PersonalizationFilterRange copyWith({String? from, String? to}) => + PersonalizationFilterRange( + id: id, + title: title, + fromLabel: fromLabel, + toLabel: toLabel, + from: from ?? this.from, + to: to ?? this.to, + select: select, + fromPlaceholder: fromPlaceholder, + toPlaceholder: toPlaceholder, + ); +} + +/// Список чекбоксов; сверх [collapsedCount] прячется за аккордеон. +class PersonalizationFilterOptions extends PersonalizationFilterSection { + const PersonalizationFilterOptions({ + required super.id, + required super.title, + required this.options, + this.collapsedCount = 5, + this.showMoreText, + this.showLessText, + }); + + final List options; + final int collapsedCount; + final String? showMoreText; + final String? showLessText; + + PersonalizationFilterOptions copyWith({ + List? options, + }) => PersonalizationFilterOptions( + id: id, + title: title, + options: options ?? this.options, + collapsedCount: collapsedCount, + showMoreText: showMoreText, + showLessText: showLessText, + ); +} + +/// Экран фильтров выдачи: заголовок с крестиком, секции и две кнопки внизу. +/// +/// Источник: Figma Mobile SDK UI Kit, страница SearchResultsScreen — Search Results/Filters +/// (203:8083) и /Filters Dark Theme (241:10831). Заголовок — [PersonalizationTitle] c +/// ghost-кнопкой cross-large (Title/Filters, 204:8340). Секции двух видов: диапазон +/// «From — to» из двух [PersonalizationInputField] md и список +/// [PersonalizationCheckboxWithLabel] с [PersonalizationAccordion] «показать ещё». +/// Внизу [PersonalizationButton] md: secondary «Reset» и primary «Apply» поровну. +/// Шаг между секциями 16, внутри секции 12, заголовок секции — LG/Emphasized 18/28. +/// Фон экрана — Background/Generic. +/// +/// Состояние чекбоксов, полей и раскрытия секций живёт здесь; хост получает изменения +/// колбэками и на «Apply» — итоговый список секций. +class PersonalizationFilters extends StatefulWidget { + const PersonalizationFilters({ + super.key, + required this.title, + this.onClose, + this.sections = const [], + this.resetText, + this.applyText, + this.onReset, + this.onApply, + this.onOptionToggle, + this.onRangeChanged, + this.onRangeSelectTap, + this.iconBuilder, + }); + + final String title; + final VoidCallback? onClose; + final List sections; + final String? resetText; + final String? applyText; + final VoidCallback? onReset; + final ValueChanged>? onApply; + + /// Изменился чекбокс: секция, вариант, новое значение. + final void Function(String sectionId, String optionId, bool checked)? + onOptionToggle; + + /// Изменилось поле диапазона: секция, «от», «до». + final void Function(String sectionId, String from, String to)? onRangeChanged; + + /// Нажато поле диапазона типа Select: секция и какое из двух (`true` — «от»). + final void Function(String sectionId, bool isFrom)? onRangeSelectTap; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + State createState() => _PersonalizationFiltersState(); +} + +class _PersonalizationFiltersState extends State { + late List _sections = widget.sections; + final Set _expanded = {}; + final Map _from = + {}; + final Map _to = + {}; + + @override + void didUpdateWidget(PersonalizationFilters oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.sections, widget.sections)) { + _sections = widget.sections; + for (final controller in _from.values.followedBy(_to.values)) { + controller.dispose(); + } + _from.clear(); + _to.clear(); + } + } + + @override + void dispose() { + for (final controller in _from.values.followedBy(_to.values)) { + controller.dispose(); + } + super.dispose(); + } + + TextEditingController _fieldController( + Map pool, + String id, + String? value, + ) => pool.putIfAbsent(id, () => TextEditingController(text: value)); + + void _update( + String sectionId, + PersonalizationFilterSection Function(PersonalizationFilterSection) change, + ) { + setState(() { + _sections = [ + for (final section in _sections) + section.id == sectionId ? change(section) : section, + ]; + }); + } + + Widget _label( + BuildContext context, + String text, + TextStyle base, + FontWeight weight, + ) { + final theme = PersonalizationTheme.of(context); + return Text( + text, + style: base.copyWith( + fontFamily: theme.fontFamily.familyFor(weight), + package: theme.fontFamily.package, + color: theme.colors.textPrimary, + ), + ); + } + + Widget _range(BuildContext context, PersonalizationFilterRange section) { + Widget field(bool isFrom) { + final controller = _fieldController( + isFrom ? _from : _to, + section.id, + isFrom ? section.from : section.to, + ); + return Expanded( + child: PersonalizationInputField( + controller: controller, + placeholder: isFrom ? section.fromPlaceholder : section.toPlaceholder, + size: PersonalizationInputFieldSize.md, + type: section.select + ? PersonalizationInputFieldType.select + : PersonalizationInputFieldType.input, + onChanged: (text) { + _update( + section.id, + (s) => (s as PersonalizationFilterRange).copyWith( + from: isFrom ? text : null, + to: isFrom ? null : text, + ), + ); + widget.onRangeChanged?.call( + section.id, + _from[section.id]?.text ?? '', + _to[section.id]?.text ?? '', + ); + }, + onSelectTap: widget.onRangeSelectTap == null + ? null + : () => widget.onRangeSelectTap!(section.id, isFrom), + iconBuilder: widget.iconBuilder, + ), + ); + } + + return Row( + children: [ + _label( + context, + section.fromLabel, + PersonalizationTypography.baseDefault, + FontWeight.w400, + ), + const SizedBox(width: 12), + field(true), + const SizedBox(width: 12), + _label( + context, + section.toLabel, + PersonalizationTypography.baseDefault, + FontWeight.w400, + ), + const SizedBox(width: 12), + field(false), + ], + ); + } + + Widget _options(BuildContext context, PersonalizationFilterOptions section) { + final bool collapsible = + section.options.length > section.collapsedCount && + (section.showMoreText ?? '').isNotEmpty; + final bool open = _expanded.contains(section.id); + final visible = collapsible && !open + ? section.options.take(section.collapsedCount) + : section.options; + final rows = [ + for (final option in visible) + PersonalizationCheckboxWithLabel( + label: option.label, + state: option.checked + ? PersonalizationCheckboxState.checked + : PersonalizationCheckboxState.unchecked, + onChanged: (next) { + final checked = next == PersonalizationCheckboxState.checked; + _update(section.id, (s) { + final current = s as PersonalizationFilterOptions; + return current.copyWith( + options: [ + for (final item in current.options) + item.id == option.id + ? item.copyWith(checked: checked) + : item, + ], + ); + }); + widget.onOptionToggle?.call(section.id, option.id, checked); + }, + ), + if (collapsible) + PersonalizationAccordion( + label: open + ? (section.showLessText ?? section.showMoreText!) + : section.showMoreText!, + count: open ? null : section.options.length - section.collapsedCount, + expanded: open, + onToggle: (next) => setState( + () => + next ? _expanded.add(section.id) : _expanded.remove(section.id), + ), + iconBuilder: widget.iconBuilder, + ), + ]; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + for (int i = 0; i < rows.length; i++) ...[ + if (i > 0) const SizedBox(height: 12), + rows[i], + ], + ], + ); + } + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + const double sectionGap = 16; + 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( + 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), + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_in_app_popup.dart b/lib/src/ui/components/personalization_in_app_popup.dart new file mode 100644 index 0000000..0bf65d3 --- /dev/null +++ b/lib/src/ui/components/personalization_in_app_popup.dart @@ -0,0 +1,331 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_elevation.dart'; +import '../personalization_icons.dart'; +import '../personalization_radius.dart'; +import '../personalization_spacing.dart'; +import '../personalization_theme.dart'; +import '../personalization_typography.dart'; +import 'personalization_button.dart'; + +/// Вид попапа: чем занято место над текстом. +enum PersonalizationInAppPopupView { image, imageBackground, text, icon } + +/// Модалка карточкой или во весь экран — от этого зависят метрики. +enum PersonalizationInAppPopupPresentation { modal, fullscreen } + +/// Инап-попап: карточка с картинкой, заголовком, текстом и кнопками. +/// +/// Источник: Figma Mobile SDK UI Kit, страница InAppPopup / Modal (1:33), +/// компонент-сеты In App Popup/Modal (469:2767) и In App Popup/Fullscreen +/// (469:2835). У обоих четыре вида: картинка сверху, картинка фоном, только +/// текст, иконка. +/// +/// Позицию на экране (верх/центр/низ/во весь экран) виджет не выбирает — это +/// дело того, кто его показывает; здесь только [presentation], от которой +/// зависят метрики: у модалки скругление 24 и отступы 20, у полноэкранной +/// скруглений нет и отступы 24, а кегли на ступень крупнее. +/// +/// Крестик стоит **всегда** и принадлежит самому попапу, а не контейнеру +/// картинки: в макете виды «только текст» и «иконка» картинки не имеют, но +/// крестик у них нарисован. Он круглый (компонент Close: кнопка MD с радиусом +/// Rounded) и во всех видах лежит поверх содержимого в правом верхнем углу, на +/// отступе попапа; над фотографией — в тёмном варианте. Текстовая кнопка +/// закрытия ([closeText]) в макете не нарисована — её даёт админка отдельным +/// тумблером рядом с кнопкой действия, поэтому она здесь вторичной кнопкой под +/// основной, на шаге 12 у модалки и 16 у полноэкранного. Пустой текст — кнопки +/// нет, остаётся один крестик. +/// +/// Поля и зазор между блоками — семантические отступы Padding/Gap Modal (20) и +/// Padding/Gap Full Screen (24), скругление модалки — радиус Modal, фон — +/// Background/Card. У модалки тень Elevation 3 цветом Shadow/Heavy темы, у +/// полноэкранного тени нет. +// TODO: связать виджет с данными SDK. Сейчас попап приходит только в натив, а через +// pigeon едет один булев флаг enableAutoPopupPresentation — payload до Dart не доходит, +// поэтому виджет пока только свёрстан и показывается в витрине примера. +// Чтобы включить: +// 1. android-sdk: точка перехвата вышла в v2.39.0, плагин на ней — +// SDK.popupPresentationListener (контракт тот же, что у iOS +// PopupPresentationDelegate: вернул null — натив не показывает). +// 2. pigeon: PopupWire (id, position, delay, components, popupActions) и +// onPopup(shopId, popup) в PersonalizationFlutterApi. +// 3. Плагины: поставить листенер / делегат, возвращать null, payload переслать в +// Dart. Флаг enableAutoPopupPresentation на Android уже доходит до Rees46Config. +// 4. Показ трекает Dart, когда виджет действительно на экране: придержанный попап +// натив не трекает и не запоминает (так и на iOS). Значит, дедуп на 60 секунд +// тоже на стороне Dart, иначе повтор с сервера покажется дважды. +class PersonalizationInAppPopup extends StatelessWidget { + const PersonalizationInAppPopup({ + super.key, + this.view = PersonalizationInAppPopupView.image, + this.presentation = PersonalizationInAppPopupPresentation.modal, + this.title, + this.text, + this.actionText, + this.closeText, + this.image, + this.icon, + this.iconBuilder, + this.onAction, + this.onClose, + }); + + final PersonalizationInAppPopupView view; + final PersonalizationInAppPopupPresentation presentation; + + final String? title; + final String? text; + + /// Подпись кнопки действия. Пусто — кнопки нет. + final String? actionText; + + /// Подпись кнопки закрытия. Пусто — остаётся только крестик. + final String? closeText; + + /// Картинку даёт хост — кит не тянет сеть. + final ImageProvider? image; + + /// Иконка вида [PersonalizationInAppPopupView.icon]. + final Widget? icon; + + /// Как нарисовать иконку крестика: пакет не рисует SVG сам. + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + final VoidCallback? onAction; + final VoidCallback? onClose; + + bool get _modal => + presentation == PersonalizationInAppPopupPresentation.modal; + + bool get _overImage => view == PersonalizationInAppPopupView.imageBackground; + + bool get _centred => + view == PersonalizationInAppPopupView.text || + view == PersonalizationInAppPopupView.icon; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final pad = _modal + ? PersonalizationSpacing.paddingModal + : PersonalizationSpacing.paddingFullScreen; + final gapSection = _modal + ? PersonalizationSpacing.gapModal + : PersonalizationSpacing.gapFullScreen; + + final surface = colors.backgroundCard; + final radius = _modal + ? BorderRadius.circular(PersonalizationRadius.modal) + : BorderRadius.zero; + + Widget content; + switch (view) { + case PersonalizationInAppPopupView.image: + content = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Картинка забирает всё, что остаётся над карточкой с текстом. + Expanded(child: _image()), + Container( + color: surface, + padding: EdgeInsets.all(pad), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + _textBlock(context), + SizedBox( + height: _modal + ? PersonalizationSpacing.xl + : PersonalizationSpacing.xl3, + ), + _buttons(context), + ], + ), + ), + ], + ); + + case PersonalizationInAppPopupView.imageBackground: + content = Stack( + fit: StackFit.expand, + children: [ + _image(), + Padding( + padding: EdgeInsets.all(pad), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Текст прижат к низу, над кнопками. + Expanded( + child: Align( + alignment: Alignment.bottomLeft, + child: _textBlock(context), + ), + ), + SizedBox(height: gapSection), + _buttons(context), + ], + ), + ), + ], + ); + + case PersonalizationInAppPopupView.text: + case PersonalizationInAppPopupView.icon: + final centre = [ + if (view == PersonalizationInAppPopupView.icon && + icon != null) ...[ + SizedBox( + width: _modal ? 100 : 120, + height: _modal ? 100 : 120, + child: icon, + ), + const SizedBox(height: PersonalizationSpacing.xl3), + ], + _textBlock(context), + ]; + content = Padding( + padding: EdgeInsets.all(pad), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: centre, + ), + ), + ), + SizedBox(height: gapSection), + _buttons(context), + ], + ), + ); + } + + // Тень снаружи карточки, поэтому она на обёртке, а не под ClipRRect — обрезка + // срезала бы её. Цвет берётся из темы: в тёмной схеме Shadow/Heavy плотнее. + return DecoratedBox( + decoration: BoxDecoration( + borderRadius: radius, + boxShadow: _modal + ? [ + for (final shadow in PersonalizationElevation.e3) + shadow.copyWith(color: colors.shadowHeavy), + ] + : null, + ), + child: ClipRRect( + borderRadius: radius, + child: Container( + color: surface, + child: Stack( + children: [ + Positioned.fill(child: content), + // Крестик всегда на месте — у видов без картинки тоже, накладкой + // поверх содержимого. + Positioned(top: pad, right: pad, child: _closeIcon(context)), + ], + ), + ), + ), + ); + } + + Widget _image() => image == null + ? const SizedBox.shrink() + : Image(image: image!, fit: BoxFit.cover); + + Widget _textBlock(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + final titleStyle = _modal + ? PersonalizationTypography.xl3Emphasized + : PersonalizationTypography.xl4Emphasized; + final textStyle = _modal + ? PersonalizationTypography.lgDefault + : PersonalizationTypography.xl2Default; + final align = _centred ? TextAlign.center : TextAlign.start; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + if ((title ?? '').isNotEmpty) + Text( + title!, + textAlign: align, + style: titleStyle.copyWith( + color: _overImage ? colors.textLightPrimary : colors.textPrimary, + ), + ), + if ((title ?? '').isNotEmpty && (text ?? '').isNotEmpty) + const SizedBox(height: PersonalizationSpacing.md), + if ((text ?? '').isNotEmpty) + Text( + text!, + textAlign: align, + style: textStyle.copyWith( + color: _overImage + ? colors.textLightSecondary + : colors.textSecondary, + ), + ), + ], + ); + } + + Widget _buttons(BuildContext context) { + final action = (actionText ?? '').isNotEmpty; + final close = (closeText ?? '').isNotEmpty; + if (!action && !close) return const SizedBox.shrink(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + if (action) + PersonalizationButton( + label: actionText, + onPressed: onAction, + iconBuilder: iconBuilder, + ), + if (action && close) + SizedBox( + height: _modal + ? PersonalizationSpacing.lg + : PersonalizationSpacing.xl, + ), + if (close) + PersonalizationButton( + label: closeText, + view: PersonalizationButtonView.secondary, + onDark: _overImage, + onPressed: onClose, + iconBuilder: iconBuilder, + ), + ], + ); + } + + // Над фотографией — и фоном, и сверху — крестик в тёмной палитре: в макете у + // него там тёмный режим. + Widget _closeIcon(BuildContext context) => PersonalizationButton( + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.secondary, + onDark: _overImage || view == PersonalizationInAppPopupView.image, + rounded: true, + iconStart: PersonalizationIcons.crossLarge, + iconBuilder: iconBuilder, + onPressed: onClose, + ); +} diff --git a/lib/src/ui/components/personalization_input_field.dart b/lib/src/ui/components/personalization_input_field.dart new file mode 100644 index 0000000..a274e2a --- /dev/null +++ b/lib/src/ui/components/personalization_input_field.dart @@ -0,0 +1,325 @@ +import 'package:flutter/material.dart' + show InputDecoration, Material, MaterialType, TextField; +import 'package:flutter/services.dart' show TextInputAction; +import 'package:flutter/widgets.dart'; + +import '../personalization_colors.dart'; +import '../personalization_theme.dart'; +import '../personalization_icons.dart'; + +/// Размер поля ввода. +enum PersonalizationInputFieldSize { lg, md, sm } + +/// Тип поля ввода. +enum PersonalizationInputFieldType { search, input, select } + +/// Поле ввода дизайн-системы. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Input (167:3746), фрейм Input Field (205:10194). +/// Матрица: 3 размера x 4 состояния x 3 типа. +/// +/// Состояния из макета не задаются снаружи, а выводятся из самого поля: +/// Default — пусто, Filled — есть текст, Focus — поле в фокусе, Disabled — [enabled]. +/// +/// Иконки отдаются путями к SVG-ассетам: пакет не рисует SVG сам, +/// отрисовку выбирает потребитель через [iconBuilder]. +/// +/// Поле построено на [TextField] ради выделения и меню копирования. [TextField] +/// требует в предках `Material` и `MaterialLocalizations`. Первое компонент +/// добавляет сам, так что его можно класть в любой оверлей. Второе даёт +/// `MaterialApp`; в `CupertinoApp` нужно добавить делегат: +/// ```dart +/// CupertinoApp( +/// localizationsDelegates: [DefaultMaterialLocalizations.delegate], +/// ) +/// ``` +class PersonalizationInputField extends StatefulWidget { + const PersonalizationInputField({ + super.key, + this.controller, + this.placeholder, + this.size = PersonalizationInputFieldSize.lg, + this.type = PersonalizationInputFieldType.search, + this.enabled = true, + this.onChanged, + this.onSubmitted, + this.onClear, + this.onSelectTap, + this.iconBuilder, + }); + + final TextEditingController? controller; + final String? placeholder; + final PersonalizationInputFieldSize size; + final PersonalizationInputFieldType type; + final bool enabled; + final ValueChanged? onChanged; + + /// Кнопка «искать» на клавиатуре у типа Search, «готово» у остальных. + final ValueChanged? onSubmitted; + + /// Нажатие на крестик у типа Search. Поле очищается в любом случае. + final VoidCallback? onClear; + + /// Нажатие на поле у типа Select: список открывает потребитель. + final VoidCallback? onSelectTap; + + /// Как нарисовать иконку заданного размера и цвета из ассета. Не задан — + /// место под иконку остаётся пустым, но отступы сохраняются. + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + State createState() => + _PersonalizationInputFieldState(); +} + +class _PersonalizationInputFieldState extends State { + late final TextEditingController _controller = + widget.controller ?? TextEditingController(); + final FocusNode _focusNode = FocusNode(); + bool _focused = false; + + bool get _ownsController => widget.controller == null; + + @override + void initState() { + super.initState(); + _focusNode.addListener(_onFocusChanged); + _controller.addListener(_onTextChanged); + } + + @override + void dispose() { + _focusNode.removeListener(_onFocusChanged); + _focusNode.dispose(); + _controller.removeListener(_onTextChanged); + if (_ownsController) _controller.dispose(); + super.dispose(); + } + + void _onFocusChanged() => setState(() => _focused = _focusNode.hasFocus); + + void _onTextChanged() => setState(() {}); + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final metrics = _inputMetrics[widget.size]!; + final filled = _controller.text.isNotEmpty; + final foreground = filled && widget.enabled + ? colors.textPrimary + : colors.textHint; + + final style = TextStyle( + fontSize: metrics.fontSize, + height: metrics.lineHeight / metrics.fontSize, + letterSpacing: metrics.letterSpacing, + fontWeight: FontWeight.w400, + fontFamily: theme.fontFamily.familyFor(FontWeight.w400), + package: theme.fontFamily.package, + color: foreground, + ); + + // Крестик — это очистка, поэтому он появляется только когда есть что чистить. + final String? endAsset; + switch (widget.type) { + case PersonalizationInputFieldType.select: + endAsset = PersonalizationIcons.angleDown; + case PersonalizationInputFieldType.search: + endAsset = filled && widget.enabled ? PersonalizationIcons.cross : null; + case PersonalizationInputFieldType.input: + endAsset = null; + } + + final field = Container( + padding: _padding(metrics), + decoration: BoxDecoration( + color: widget.enabled + ? colors.backgroundInput + : colors.backgroundInputDisabled, + borderRadius: BorderRadius.circular( + theme.radius.resolve(metrics.radius), + ), + border: Border.all( + color: _focused && widget.enabled + ? colors.lineInputFocus + : colors.lineInput, + width: _border, + ), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + if (widget.type == PersonalizationInputFieldType.search) ...[ + // В макете иконка идёт в цвет текста: серая в Default и Disabled, тёмная в Filled. + _icon(context, PersonalizationIcons.magnifier, metrics, foreground), + const SizedBox(width: 8), + ], + Expanded(child: _body(style, colors)), + if (endAsset != null) ...[ + const SizedBox(width: 8), + GestureDetector( + onTap: widget.type == PersonalizationInputFieldType.search + ? _clear + : widget.onSelectTap, + child: _icon(context, endAsset, metrics, foreground), + ), + ], + ], + ), + ); + + // Select — не поле ввода: список открывает потребитель по нажатию на всю строку. + if (widget.type == PersonalizationInputFieldType.select) { + return GestureDetector( + onTap: widget.enabled ? widget.onSelectTap : null, + child: field, + ); + } + return field; + } + + Widget _body(TextStyle style, PersonalizationColors colors) { + if (widget.type == PersonalizationInputFieldType.select) { + final filled = _controller.text.isNotEmpty; + return Text( + filled ? _controller.text : (widget.placeholder ?? ''), + style: style, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ); + } + // TextField требует предка Material — без этой обёртки он падает на ассерте + // везде, кроме Scaffold. Прозрачный тип ничего не рисует поверх нашего фона. + return Material( + type: MaterialType.transparency, + child: TextField( + controller: _controller, + focusNode: _focusNode, + enabled: widget.enabled, + onChanged: widget.onChanged, + onSubmitted: widget.onSubmitted, + textInputAction: widget.type == PersonalizationInputFieldType.search + ? TextInputAction.search + : TextInputAction.done, + style: style, + decoration: InputDecoration.collapsed( + hintText: widget.placeholder, + hintStyle: style.copyWith(color: colors.textHint), + ), + ), + ); + } + + void _clear() { + _controller.clear(); + widget.onChanged?.call(''); + widget.onClear?.call(); + } + + Widget _icon( + BuildContext context, + String asset, + _InputMetrics metrics, + Color color, + ) { + return SizedBox( + width: metrics.iconSize, + height: metrics.iconSize, + child: widget.iconBuilder?.call(context, asset, metrics.iconSize, color), + ); + } + + EdgeInsets _padding(_InputMetrics metrics) { + // Рамка добавляется к размеру сверх отступов, поэтому отступ уменьшен на её + // толщину: иначе поле выходит на 2px выше макета. + final double vertical = metrics.paddingVertical - _border; + switch (widget.type) { + case PersonalizationInputFieldType.search: + return EdgeInsets.all(vertical); + case PersonalizationInputFieldType.input: + return EdgeInsets.symmetric( + vertical: vertical, + horizontal: metrics.paddingInput - _border, + ); + case PersonalizationInputFieldType.select: + return EdgeInsets.only( + left: metrics.paddingSelectStart - _border, + right: vertical, + top: vertical, + bottom: vertical, + ); + } + } +} + +const double _border = 1; + +class _InputMetrics { + const _InputMetrics({ + required this.fontSize, + required this.lineHeight, + required this.letterSpacing, + required this.radius, + required this.paddingVertical, + required this.paddingInput, + required this.paddingSelectStart, + required this.iconSize, + }); + + final double fontSize; + final double lineHeight; + final double letterSpacing; + final PersonalizationRadiusToken radius; + final double paddingVertical; + + /// Горизонтальный отступ типа Input. У Search он равен вертикальному. + final double paddingInput; + + /// Отступ слева у типа Select. Справа там тоже вертикальный. + final double paddingSelectStart; + final double iconSize; +} + +// LG берёт кегль со ступени lg, а интерлиньяж со ступени xl: в макете 18/32, +// тогда как ступень lg — это 18/28. SM так же смешан: 14/24 против 14/20. +const Map _inputMetrics = + { + PersonalizationInputFieldSize.lg: _InputMetrics( + fontSize: 18, + lineHeight: 32, + letterSpacing: 0, + radius: PersonalizationRadiusToken.buttonLg, + paddingVertical: 12, + paddingInput: 16, + paddingSelectStart: 16, + iconSize: 32, + ), + PersonalizationInputFieldSize.md: _InputMetrics( + fontSize: 16, + lineHeight: 24, + letterSpacing: 0, + radius: PersonalizationRadiusToken.buttonMd, + paddingVertical: 8, + paddingInput: 12, + paddingSelectStart: 12, + iconSize: 24, + ), + PersonalizationInputFieldSize.sm: _InputMetrics( + fontSize: 14, + lineHeight: 24, + letterSpacing: 0.05, + radius: PersonalizationRadiusToken.buttonSm, + paddingVertical: 4, + paddingInput: 12, + paddingSelectStart: 8, + iconSize: 24, + ), + }; diff --git a/lib/src/ui/components/personalization_instant_search.dart b/lib/src/ui/components/personalization_instant_search.dart new file mode 100644 index 0000000..27f31f2 --- /dev/null +++ b/lib/src/ui/components/personalization_instant_search.dart @@ -0,0 +1,318 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; +import 'personalization_input_field.dart'; +import 'personalization_link.dart'; +import 'personalization_list_label.dart'; +import 'personalization_suggestion_row.dart'; +import 'personalization_tag.dart'; + +/// Подсказка поиска. +@immutable +class PersonalizationSuggestion { + const PersonalizationSuggestion({ + required this.id, + required this.title, + this.subtitle, + this.image, + }); + + final String id; + final String title; + + /// Цена у товара, родительская категория у категории. + final String? subtitle; + final ImageProvider? image; +} + +/// Экран мгновенного поиска: поле ввода с «Cancel», недавние запросы, подсказки, +/// категории и товары. +/// +/// Источник: Figma Mobile SDK UI Kit, страница InstantSearchField — Instant Search/Text +/// (151:3976), /Input (310:10207), /With Images (310:9829), /Clear Recent Searches +/// (310:10016). Поле — [PersonalizationInputField] типа search размера md, ссылки — +/// [PersonalizationLink], подписи блоков — [PersonalizationListLabel], теги — +/// [PersonalizationTag] с переносом по строкам, строки — [PersonalizationSuggestionRow]. +/// +/// Недавние запросы — теги с крестиком, в конце синий тег «ещё»; подсказки при вводе — +/// такие же теги без крестика. Перед категориями и перед товарами разделитель 1px. +/// Совпадение с запросом в строках выделяется полужирным само. +/// +/// Внимание: шаг колонки в макете 13 — такого значения в шкале нет, взят LG (12). +/// Разделитель в макете чёрный 4%, ближайший токен Line/Generic Subtle (5%). +class PersonalizationInstantSearch extends StatefulWidget { + const PersonalizationInstantSearch({ + super.key, + this.controller, + this.placeholder, + this.cancelText, + this.onCancel, + this.onQueryChanged, + this.onSubmit, + this.recentLabel, + this.clearText, + this.onClearRecent, + this.recentSearches = const [], + this.moreText, + this.onMoreRecent, + this.onRecentTap, + this.onRecentRemove, + this.suggestions = const [], + this.onSuggestionTap, + this.categoriesLabel, + this.categories = const [], + this.onCategoryTap, + this.productsLabel, + this.products = const [], + this.onProductTap, + this.showImages = false, + this.iconBuilder, + }); + + /// Контроллер поля; не задан — виджет заводит свой. + final TextEditingController? controller; + final String? placeholder; + + /// Подпись ссылки справа от поля. `null` — без ссылки. + final String? cancelText; + final VoidCallback? onCancel; + final ValueChanged? onQueryChanged; + final ValueChanged? onSubmit; + + /// Подпись над недавними запросами. `null` — блок без подписи и без «Clear». + final String? recentLabel; + final String? clearText; + final VoidCallback? onClearRecent; + final List recentSearches; + + /// Подпись синего тега в конце недавних запросов. `null` — без него. + final String? moreText; + final VoidCallback? onMoreRecent; + final ValueChanged? onRecentTap; + final ValueChanged? onRecentRemove; + + final List suggestions; + final ValueChanged? onSuggestionTap; + + final String? categoriesLabel; + final List categories; + final ValueChanged? onCategoryTap; + final String? productsLabel; + final List products; + final ValueChanged? onProductTap; + + /// Показывать ли картинки у строк: в макете есть оба варианта. Строка без картинки идёт без плейсхолдера. + final bool showImages; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + State createState() => + _PersonalizationInstantSearchState(); +} + +class _PersonalizationInstantSearchState + extends State { + TextEditingController? _ownController; + + TextEditingController get _controller => + widget.controller ?? (_ownController ??= TextEditingController()); + + @override + void initState() { + super.initState(); + _controller.addListener(_onText); + } + + @override + void didUpdateWidget(PersonalizationInstantSearch oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller != widget.controller) { + (oldWidget.controller ?? _ownController)?.removeListener(_onText); + _controller.addListener(_onText); + } + } + + @override + void dispose() { + _controller.removeListener(_onText); + _ownController?.dispose(); + super.dispose(); + } + + // Совпадение выделяется по тексту поля, поэтому строки перестраиваются на каждый символ. + void _onText() => setState(() {}); + + Widget _removeIcon(BuildContext context, String asset) { + final color = PersonalizationTheme.of(context).colors.textPrimary; + return widget.iconBuilder?.call(context, asset, 16, color) ?? + const SizedBox(width: 16, height: 16); + } + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + const double gap = 12; + final highlight = _controller.text; + + final Widget separator = ColoredBox( + color: colors.lineGenericSubtle, + child: const SizedBox(height: 1, width: double.infinity), + ); + + Widget rows( + List items, + PersonalizationSuggestionKind kind, + ValueChanged? onTap, + ) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (int i = 0; i < items.length; i++) ...[ + if (i > 0) const SizedBox(height: gap), + PersonalizationSuggestionRow( + kind: kind, + title: items[i].title, + subtitle: items[i].subtitle, + image: items[i].image, + // Строка без картинки идёт без плейсхолдера. + showImage: widget.showImages && items[i].image != null, + highlight: highlight, + onTap: onTap == null ? null : () => onTap(items[i]), + iconBuilder: widget.iconBuilder, + ), + ], + ], + ); + } + + final bool hasRecent = widget.recentSearches.isNotEmpty; + final sections = [ + Row( + children: [ + Expanded( + child: PersonalizationInputField( + controller: _controller, + placeholder: widget.placeholder, + size: PersonalizationInputFieldSize.md, + type: PersonalizationInputFieldType.search, + onChanged: widget.onQueryChanged, + onSubmitted: widget.onSubmit, + iconBuilder: widget.iconBuilder, + ), + ), + if (widget.cancelText != null && + widget.cancelText!.isNotEmpty) ...[ + const SizedBox(width: 16), + PersonalizationLink( + label: widget.cancelText!, + onTap: widget.onCancel, + ), + ], + ], + ), + if (hasRecent && + widget.recentLabel != null && + widget.recentLabel!.isNotEmpty) + Row( + children: [ + Expanded( + child: PersonalizationListLabel(label: widget.recentLabel!), + ), + if (widget.clearText != null && + widget.clearText!.isNotEmpty) ...[ + const SizedBox(width: gap), + PersonalizationLink( + label: widget.clearText!, + onTap: widget.onClearRecent, + ), + ], + ], + ), + if (hasRecent) + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (final item in widget.recentSearches) + // Tag сам по себе не кликабелен — нажатие ловит обёртка, крестик — сам тег. + GestureDetector( + onTap: widget.onRecentTap == null + ? null + : () => widget.onRecentTap!(item), + child: PersonalizationTag( + label: item, + view: PersonalizationTagView.secondary, + onRemove: () => widget.onRecentRemove?.call(item), + removeIconBuilder: _removeIcon, + ), + ), + if (widget.moreText != null && widget.moreText!.isNotEmpty) + GestureDetector( + onTap: widget.onMoreRecent, + child: PersonalizationTag( + label: widget.moreText!, + view: PersonalizationTagView.primary, + ), + ), + ], + ), + if (widget.suggestions.isNotEmpty) + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (final item in widget.suggestions) + GestureDetector( + onTap: widget.onSuggestionTap == null + ? null + : () => widget.onSuggestionTap!(item), + child: PersonalizationTag( + label: item, + view: PersonalizationTagView.secondary, + ), + ), + ], + ), + if (widget.categories.isNotEmpty) separator, + if (widget.categories.isNotEmpty && + widget.categoriesLabel != null && + widget.categoriesLabel!.isNotEmpty) + PersonalizationListLabel(label: widget.categoriesLabel!), + if (widget.categories.isNotEmpty) + rows( + widget.categories, + PersonalizationSuggestionKind.category, + widget.onCategoryTap, + ), + if (widget.products.isNotEmpty) separator, + if (widget.products.isNotEmpty && + widget.productsLabel != null && + widget.productsLabel!.isNotEmpty) + PersonalizationListLabel(label: widget.productsLabel!), + if (widget.products.isNotEmpty) + rows( + widget.products, + PersonalizationSuggestionKind.product, + widget.onProductTap, + ), + ]; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + for (int i = 0; i < sections.length; i++) ...[ + if (i > 0) const SizedBox(height: gap), + sections[i], + ], + ], + ); + } +} diff --git a/lib/src/ui/components/personalization_link.dart b/lib/src/ui/components/personalization_link.dart new file mode 100644 index 0000000..ceff6a1 --- /dev/null +++ b/lib/src/ui/components/personalization_link.dart @@ -0,0 +1,50 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; +import '../personalization_typography.dart'; + +/// Текстовая ссылка: «Cancel» у поля поиска, «Clear» у недавних запросов. +/// +/// В секции Components такого символа нет — стиль снят с экранов Instant Search +/// (страница InstantSearchField, 151:3976 и 310:9829): кегль base 16/24, +/// начертание 600, цвет Text/Link, без подложки и отступов. Нажатого состояния +/// в макете нет, поэтому ссылка только слегка гаснет под пальцем. +class PersonalizationLink extends StatefulWidget { + const PersonalizationLink({super.key, required this.label, this.onTap}); + + final String label; + final VoidCallback? onTap; + + @override + State createState() => _PersonalizationLinkState(); +} + +class _PersonalizationLinkState extends State { + bool _pressed = false; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: widget.onTap, + onTapDown: (_) => setState(() => _pressed = true), + onTapUp: (_) => setState(() => _pressed = false), + onTapCancel: () => setState(() => _pressed = false), + child: Opacity( + opacity: _pressed ? _pressedOpacity : 1, + child: Text( + widget.label, + maxLines: 1, + style: PersonalizationTypography.baseEmphasized.copyWith( + fontFamily: theme.fontFamily.familyFor(FontWeight.w600), + package: theme.fontFamily.package, + color: theme.colors.textLink, + ), + ), + ), + ); + } + + static const double _pressedOpacity = 0.6; +} diff --git a/lib/src/ui/components/personalization_list_label.dart b/lib/src/ui/components/personalization_list_label.dart new file mode 100644 index 0000000..2b5f7c9 --- /dev/null +++ b/lib/src/ui/components/personalization_list_label.dart @@ -0,0 +1,34 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Подпись-разделитель списка. +/// +/// Источник: Figma Mobile SDK UI Kit, секция List (241:10565), символ Label (243:10967). +/// Единственное место в макете, где шрифт берётся из Font Family/Body, а не Heading. +/// Inter в SDK не поставляется, так что на отрисовку это пока не влияет. +/// +/// Текст переводится в верхний регистр самим компонентом — так задано в макете. +class PersonalizationListLabel extends StatelessWidget { + const PersonalizationListLabel({super.key, required this.label}); + + final String label; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + return Text( + label.toUpperCase(), + style: TextStyle( + fontSize: 14, + height: 20 / 14, + letterSpacing: 0.05, + fontWeight: FontWeight.w400, + fontFamily: theme.fontFamily.familyFor(FontWeight.w400), + package: theme.fontFamily.package, + color: colors.textHint, + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_loader.dart b/lib/src/ui/components/personalization_loader.dart new file mode 100644 index 0000000..c66599a --- /dev/null +++ b/lib/src/ui/components/personalization_loader.dart @@ -0,0 +1,89 @@ +import 'dart:math' as math; + +import 'package:flutter/widgets.dart'; + +/// Индикатор загрузки дизайн-системы. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Loader (296:3717). +/// Кольцо 26 с внешним радиусом 13 и толщиной 3.5, свип-градиент от прозрачного +/// к чёрному 47%, вращение против часовой стрелки. +/// +/// Градиент снят с растрового экспорта макета: в переменных Figma значение +/// `Gradient/Loader` приходит пустым. +class PersonalizationLoader extends StatefulWidget { + const PersonalizationLoader({ + super.key, + this.size = 32, + this.period = const Duration(milliseconds: 900), + }); + + final double size; + final Duration period; + + @override + State createState() => _PersonalizationLoaderState(); +} + +class _PersonalizationLoaderState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: widget.period, + )..repeat(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + // Контейнер повторяет макет: вертикальные отступы 4, содержимое по центру. + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Center( + child: RotationTransition( + turns: _controller, + child: CustomPaint( + size: Size.square(widget.size), + painter: const _LoaderPainter(), + ), + ), + ), + ); + } +} + +class _LoaderPainter extends CustomPainter { + const _LoaderPainter(); + + @override + void paint(Canvas canvas, Size size) { + // Кольцо 26 лежит в слоте 32 по центру; толщина пропорциональна кольцу. + final ringSide = size.width * 26 / 32; + final scale = ringSide / 26; + final strokeWidth = 3.5 * scale; + final rect = Rect.fromCenter( + center: size.center(Offset.zero), + width: ringSide, + height: ringSide, + ); + final ring = rect.deflate(strokeWidth / 2); + + final paint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = strokeWidth + ..strokeCap = StrokeCap.round + ..shader = const SweepGradient( + startAngle: 0, + endAngle: math.pi * 2, + colors: [Color(0x00000000), Color(0x78000000)], + ).createShader(ring); + + canvas.drawArc(ring, 0, math.pi * 2, false, paint); + } + + @override + bool shouldRepaint(_LoaderPainter oldDelegate) => false; +} diff --git a/lib/src/ui/components/personalization_loyalty_card.dart b/lib/src/ui/components/personalization_loyalty_card.dart new file mode 100644 index 0000000..aa2503f --- /dev/null +++ b/lib/src/ui/components/personalization_loyalty_card.dart @@ -0,0 +1,558 @@ +import 'dart:math' as math; + +import 'package:flutter/widgets.dart'; + +import '../personalization_elevation.dart'; +import '../personalization_icons.dart'; +import '../personalization_spacing.dart'; +import '../personalization_theme.dart'; +import 'personalization_barcode.dart'; +import 'personalization_code128.dart'; + +/// Поле блока Info карты лояльности: подпись и значение. +@immutable +class PersonalizationLoyaltyCardField { + const PersonalizationLoyaltyCardField({ + required this.label, + required this.value, + }); + + final String label; + final String value; +} + +/// Карта лояльности в духе Apple Wallet. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Loyalty (1:34), фреймы +/// Wallet/iOS/Light Theme (570:9879) и Wallet/iOS/Dark Theme (570:10131); +/// компонент Wallet (570:9111) на странице Components, секция Card. Части: +/// Header, Wallet/Logo (570:9034), набор полей Wallet (559:8973), Wallet/Stripe +/// (520:8923), Wallet/Stamps (570:10384), Wallet/Info (570:9081), Wallet/Code +/// (520:8886). +/// +/// С данными SDK не связана: getLoyaltyStatus отдаёт только участие и уровень — +/// ни баланса, ни штампов, ни номера карты в нём нет. Всё содержимое даёт хост, +/// кит только раскладывает. Форма вступления из описания страницы в макете не +/// нарисована — её здесь нет. +/// +/// Ширина — ширина родителя, минимальная высота — пропорция пасса 370×560; +/// содержимое выше — карта растёт. Разделы идут стопкой без зазоров, пустой +/// раздел пропадает целиком: +/// - Header — логотип в начале, баланс (подпись и значение) в конце строки; +/// - Stripe — полоса высотой в ширину / 2.6 (strip Apple 375×144): картинка, +/// затемнение 30%, эмблема уровня и штампы; +/// - Info — поля [fields] поровну по ширине; +/// - Code — штрихкод [code] на белой подложке, забирает остаток высоты и +/// прижат к низу по центру. +/// +/// Скругление 2XL, обводка 1 внутрь цветом Line/Generic Subtle, тень Elevation 3 +/// цветом Shadow/Heavy темы. Фон — Background/Card, подписи и значения — +/// Text/Primary; оба переопределяются через [cardColor] и [contentColor]. Так в +/// тёмном примере макета карта фирменная синяя — Semantic/Info +/// ([PersonalizationColors.semanticInfo]), цвет передаёт хост. +class PersonalizationLoyaltyCard extends StatelessWidget { + const PersonalizationLoyaltyCard({ + super.key, + this.logo, + this.balanceLabel, + this.balanceValue, + this.stripe, + this.emblem, + this.stamps = 0, + this.stampsTotal = 0, + this.fields = const [], + this.code, + this.cardColor, + this.contentColor, + this.iconBuilder, + }); + + /// Логотип хоста. Кит задаёт ему высоту 33, ширину картинка берёт по своей + /// пропорции. Виджет, а не [ImageProvider]: логотип кит не перекрашивает — + /// хочет хост цвет текста, он красит его сам (`Image(color: ...)`). Карта + /// меряет содержимое через IntrinsicHeight, поэтому LayoutBuilder в логотипе + /// не годится; Image и SvgPicture подходят. + final Widget? logo; + + /// Подпись баланса — в макете «Бонусы»; выводится прописными. + final String? balanceLabel; + + /// Баланс уже отформатированным — в макете «50 550». + final String? balanceValue; + + /// Картинка полосы, заполняет её с обрезкой по краям. Картинки даёт хост — + /// кит не тянет сеть. + final ImageProvider? stripe; + + /// Эмблема уровня поверх полосы, у правого края, частично за её границей. + final ImageProvider? emblem; + + /// Сколько штампов собрано. Приводится к 0…[stampsTotal]. + final int stamps; + + /// Сколько мест под штампы. 0 — ряда штампов нет. + final int stampsTotal; + + /// Поля блока Info по порядку — в макете «Владелец» и «Уровень». Тумблер + /// Show Owner макета — просто поле, которое хост не передал. + final List fields; + + /// Номер карты для штрихкода Code 128. Пусто или не кодируется — раздела + /// нет, минимальная высота карты остаётся. + final String? code; + + /// Фон карты. `null` — Background/Card. + final Color? cardColor; + + /// Цвет подписей и значений. `null` — Text/Primary. + final Color? contentColor; + + /// Как нарисовать иконку штампа ([PersonalizationIcons.checkRosetteFill], + /// [PersonalizationIcons.rosette]) заданного размера и цвета. Не задан — + /// кит рисует штампы сам по контуру тех же иконок. + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + /// Пропорция пасса в макете. + static const double _designWidth = 370; + static const double _designHeight = 560; + + /// Wallet/Logo. + static const double _logoHeight = 33; + + /// Strip Apple Wallet — 375×144; в макете 368×141.5. + static const double _stripeRatio = 2.6; + + static const double _stampSize = 32; + + bool get _hasBalance => + (balanceLabel ?? '').isNotEmpty || (balanceValue ?? '').isNotEmpty; + + int get _total => math.max(0, stampsTotal); + + bool get _hasCode => + code != null && PersonalizationCode128.values(code!) != null; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final surface = cardColor ?? colors.backgroundCard; + final radius = BorderRadius.circular(theme.radius.xl2); + + return LayoutBuilder( + builder: (context, constraints) { + // Без ограничения по ширине (горизонтальная прокрутка) — ширина макета. + final width = constraints.hasBoundedWidth + ? constraints.maxWidth + : _designWidth; + + final sections = [ + if (logo != null || _hasBalance) _header(context), + if (stripe != null || emblem != null || _total > 0) + _stripe(context, width / _stripeRatio), + if (fields.isNotEmpty) _info(context), + if (_hasCode) Expanded(child: _code(context)), + ]; + + // Тень снаружи карты, поэтому она на обёртке, а не под ClipRRect — + // обрезка срезала бы её. Обводка поверх содержимого, внутри скругления: + // полоса во всю ширину её не перекрывает. + return SizedBox( + width: width, + child: DecoratedBox( + decoration: BoxDecoration( + borderRadius: radius, + boxShadow: [ + for (final shadow in PersonalizationElevation.e3) + shadow.copyWith(color: colors.shadowHeavy), + ], + ), + child: ClipRRect( + borderRadius: radius, + child: DecoratedBox( + position: DecorationPosition.foreground, + decoration: BoxDecoration( + borderRadius: radius, + border: Border.all(color: colors.lineGenericSubtle), + ), + child: ColoredBox( + color: surface, + // Высота — наибольшая из пропорции и содержимого. + // IntrinsicHeight меряет содержимое и в прокрутке без + // ограничения по высоте, где Expanded раздела Code иначе + // было бы нечего делить. + child: ConstrainedBox( + constraints: BoxConstraints( + minHeight: width * _designHeight / _designWidth, + ), + child: IntrinsicHeight( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: sections, + ), + ), + ), + ), + ), + ), + ), + ); + }, + ); + } + + // Подпись поля и баланса: 11/14, SemiBold, +0.04 em, прописными. + TextStyle _labelStyle(BuildContext context) => _style( + context, + fontSize: 11, + lineHeight: 14, + weight: FontWeight.w600, + letterSpacingEm: 0.04, + ); + + // Трекинг в макете в долях кегля, TextStyle ждёт логические пиксели. + TextStyle _style( + BuildContext context, { + required double fontSize, + required double lineHeight, + FontWeight weight = FontWeight.w400, + double letterSpacingEm = 0, + }) { + final theme = PersonalizationTheme.of(context); + return TextStyle( + fontSize: fontSize, + height: lineHeight / fontSize, + fontWeight: weight, + letterSpacing: fontSize * letterSpacingEm, + fontFamily: theme.fontFamily.familyFor(weight), + package: theme.fontFamily.package, + color: contentColor ?? theme.colors.textPrimary, + ); + } + + Widget _header(BuildContext context) { + final label = balanceLabel ?? ''; + final value = balanceValue ?? ''; + return Padding( + padding: const EdgeInsets.all(PersonalizationSpacing.xl), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + if (logo != null) SizedBox(height: _logoHeight, child: logo), + if (logo != null && _hasBalance) + const SizedBox(width: PersonalizationSpacing.xl), + if (_hasBalance) + Expanded( + // Строки баланса однострочные: IntrinsicHeight меряет шапку по + // собственной ширине картинки логотипа, а не по ширине при + // высоте 33, и перенос по такой ширине раздул бы шапку. + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + if (label.isNotEmpty) + Text( + label.toUpperCase(), + textAlign: TextAlign.end, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _labelStyle(context), + ), + if (value.isNotEmpty) + Text( + value, + textAlign: TextAlign.end, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _style( + context, + fontSize: 24, + lineHeight: 24, + letterSpacingEm: -0.05, + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _stripe(BuildContext context, double height) { + final colors = PersonalizationTheme.of(context).colors; + final filled = stamps.clamp(0, _total); + return SizedBox( + height: height, + child: Stack( + fit: StackFit.expand, + // Эмблема выходит за полосу — полоса её обрезает. + clipBehavior: Clip.hardEdge, + children: [ + // Чёрная подложка, а не токен: полоса в макете в тёмном режиме в + // любой теме, и пока картинка не загрузилась, под затемнением чёрное. + const ColoredBox(color: Color(0xFF000000)), + if (stripe != null) Image(image: stripe!, fit: BoxFit.cover), + // Затемнение 30%, чтобы штампы читались на любой картинке. + const ColoredBox(color: Color(0x4D000000)), + if (emblem != null) + // Геометрия из макета: эмблема 179.5×205.8 в точке (212.5, −16.5) + // полосы 368×141.5 — всё в долях высоты полосы. + PositionedDirectional( + top: -0.1166 * height, + end: -0.17 * height, + height: 1.4545 * height, + child: Image(image: emblem!, fit: BoxFit.contain), + ), + if (_total > 0) + Align( + alignment: AlignmentDirectional.centerStart, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: PersonalizationSpacing.xl, + ), + // Больше штампов, чем влезает в ширину, — ряд ужимается, а не + // вылезает за карту. В макете их до пяти. + child: FittedBox( + fit: BoxFit.scaleDown, + alignment: AlignmentDirectional.centerStart, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (int i = 0; i < _total; i++) ...[ + if (i > 0) + const SizedBox(width: PersonalizationSpacing.md), + // Полоса в макете всегда в тёмном режиме, поэтому + // штампы — постоянные светлые токены, а не текстовые + // цвета темы. + _stamp( + context, + filled: i < filled, + color: i < filled + ? colors.textLightSecondary + : colors.textLightHint, + ), + ], + ], + ), + ), + ), + ), + ], + ), + ); + } + + Widget _stamp( + BuildContext context, { + required bool filled, + required Color color, + }) { + final asset = filled + ? PersonalizationIcons.checkRosetteFill + : PersonalizationIcons.rosette; + return SizedBox( + width: _stampSize, + height: _stampSize, + child: + iconBuilder?.call(context, asset, _stampSize, color) ?? + CustomPaint( + painter: _StampPainter(filled: filled, color: color), + ), + ); + } + + Widget _info(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(PersonalizationSpacing.xl), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (int i = 0; i < fields.length; i++) ...[ + if (i > 0) const SizedBox(width: PersonalizationSpacing.gapModal), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + fields[i].label.toUpperCase(), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _labelStyle(context), + ), + Text( + fields[i].value, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _style( + context, + fontSize: 28, + lineHeight: 32, + letterSpacingEm: -0.05, + ), + ), + ], + ), + ), + ], + ], + ), + ); + } + + Widget _code(BuildContext context) { + final theme = PersonalizationTheme.of(context); + return Padding( + padding: const EdgeInsets.fromLTRB( + PersonalizationSpacing.xl, + PersonalizationSpacing.xl3, + PersonalizationSpacing.xl, + PersonalizationSpacing.xl3, + ), + child: Align( + alignment: Alignment.bottomCenter, + child: DecoratedBox( + decoration: BoxDecoration( + // Белый Brand/White, а не токен фона: сканеру нужна белая подложка + // в обеих темах. + color: const Color(0xFFFFFFFF), + borderRadius: BorderRadius.circular(theme.radius.lg), + border: Border.all(color: theme.colors.lineGenericSubtle), + ), + child: Padding( + padding: const EdgeInsets.all(PersonalizationSpacing.xl2), + child: PersonalizationBarcode(code: code!), + ), + ), + ), + ); + } +} + +/// Штамп без [PersonalizationLoyaltyCard.iconBuilder]: те же контуры, что в +/// ассетах check-rosette-fill.svg и rosette.svg, — пакет не рисует SVG сам. +class _StampPainter extends CustomPainter { + const _StampPainter({required this.filled, required this.color}); + + final bool filled; + final Color color; + + static final Path _checkRosetteFill = _svgPath(_checkRosetteFillData); + static final Path _rosette = _svgPath(_rosetteData); + + @override + void paint(Canvas canvas, Size size) { + canvas + ..save() + ..scale(size.width / 32, size.height / 32) + ..drawPath(filled ? _checkRosetteFill : _rosette, Paint()..color = color) + ..restore(); + } + + @override + bool shouldRepaint(_StampPainter oldDelegate) => + oldDelegate.filled != filled || oldDelegate.color != color; +} + +/// Контур из атрибута `d`: Figma экспортирует эти иконки абсолютными M, L, C и +/// Z. Сдвиг 0.6281 — из атрибута transform: контур 30.74 в рамке 32. Заливка +/// even-odd — так дырки (галочка, внутренний контур) вырезаются при любом +/// направлении обхода. +Path _svgPath(String data) { + final tokens = RegExp( + r'[MLCZ]|-?\d*\.?\d+', + ).allMatches(data).map((match) => match[0]!).toList(); + final path = Path()..fillType = PathFillType.evenOdd; + String command = 'M'; + int i = 0; + double next() => double.parse(tokens[i++]); + while (i < tokens.length) { + switch (tokens[i]) { + case 'M' || 'L' || 'C': + command = tokens[i++]; + case 'Z': + path.close(); + i++; + default: + switch (command) { + case 'M': + path.moveTo(next(), next()); + // Следующие пары после M — неявные L. + command = 'L'; + case 'L': + path.lineTo(next(), next()); + case 'C': + path.cubicTo(next(), next(), next(), next(), next(), next()); + } + } + } + return path.shift(const Offset(0.6281, 0.6281)); +} + +const String _checkRosetteFillData = + 'M13.4256 0.716651C14.5469 -0.238881 16.1969 -0.238887 17.3182 0.716651' + 'L20.12 3.10435C20.2801 3.24076 20.4796 3.32296 20.6893 3.3397' + 'L24.3592 3.63267C25.8276 3.74997 26.9939 4.91624 27.1112 6.38462' + 'L27.4042 10.0545C27.4209 10.2642 27.503 10.4638 27.6395 10.6239' + 'L30.0272 13.4256C30.9826 14.5469 30.9827 16.197 30.0272 17.3182' + 'L27.6395 20.12C27.503 20.2801 27.4209 20.4795 27.4042 20.6893' + 'L27.1112 24.3592C26.9939 25.8276 25.8276 26.9939 24.3592 27.1112' + 'L20.6893 27.4042C20.4795 27.4209 20.2801 27.503 20.12 27.6395' + 'L17.3182 30.0272C16.197 30.9827 14.5469 30.9826 13.4256 30.0272' + 'L10.6239 27.6395C10.4638 27.503 10.2642 27.4209 10.0545 27.4042' + 'L6.38462 27.1112C4.91624 26.9939 3.74998 25.8276 3.63267 24.3592' + 'L3.3397 20.6893C3.32296 20.4796 3.24076 20.2801 3.10435 20.12' + 'L0.716651 17.3182C-0.238887 16.1969 -0.23888 14.5469 0.716651 13.4256' + 'L3.10435 10.6239C3.2408 10.4637 3.32294 10.2643 3.3397 10.0545' + 'L3.63267 6.38462C3.74991 4.91619 4.91619 3.74991 6.38462 3.63267' + 'L10.0545 3.3397C10.2643 3.32294 10.4637 3.2408 10.6239 3.10435' + 'L13.4256 0.716651Z' + 'M21.579 11.1649C21.1884 10.7744 20.5554 10.7744 20.1649 11.1649' + 'L13.3719 17.9579L10.579 15.1649' + 'C10.1884 14.7744 9.55542 14.7744 9.16489 15.1649' + 'C8.77437 15.5554 8.77437 16.1884 9.16489 16.579L12.6649 20.079' + 'C13.0554 20.4693 13.6885 20.4694 14.079 20.079L21.579 12.579' + 'C21.9694 12.1885 21.9693 11.5554 21.579 11.1649Z'; + +const String _rosetteData = + 'M13.4256 0.716656C14.5469 -0.238886 16.1969 -0.238885 17.3182 0.716656' + 'L20.12 3.10435C20.2801 3.24084 20.4795 3.32296 20.6893 3.3397' + 'L24.3592 3.63267C25.8277 3.74991 26.9939 4.91619 27.1112 6.38462' + 'L27.4042 10.0545C27.4209 10.2643 27.503 10.4637 27.6395 10.6239' + 'L30.0272 13.4256C30.9827 14.5469 30.9827 16.1969 30.0272 17.3182' + 'L27.6395 20.12C27.503 20.2801 27.4209 20.4795 27.4042 20.6893' + 'L27.1112 24.3592C26.9939 25.8277 25.8277 26.9939 24.3592 27.1112' + 'L20.6893 27.4042C20.4795 27.4209 20.2801 27.503 20.12 27.6395' + 'L17.3182 30.0272C16.1969 30.9827 14.5469 30.9827 13.4256 30.0272' + 'L10.6239 27.6395C10.4637 27.503 10.2643 27.4209 10.0545 27.4042' + 'L6.38462 27.1112C4.91619 26.9939 3.74991 25.8277 3.63267 24.3592' + 'L3.3397 20.6893C3.32296 20.4795 3.24084 20.2801 3.10435 20.12' + 'L0.716656 17.3182C-0.238886 16.1969 -0.238885 14.5469 0.716656 13.4256' + 'L3.10435 10.6239C3.24084 10.4637 3.32296 10.2643 3.3397 10.0545' + 'L3.63267 6.38462C3.74991 4.91619 4.91619 3.74991 6.38462 3.63267' + 'L10.0545 3.3397C10.2643 3.32296 10.4637 3.24084 10.6239 3.10435' + 'L13.4256 0.716656Z' + 'M16.0204 2.23814C15.6467 1.91997 15.0971 1.91997 14.7235 2.23814' + 'L11.9208 4.62681C11.4403 5.03612 10.8429 5.28364 10.2137 5.33384' + 'L6.5438 5.62681C6.05435 5.66591 5.66591 6.05436 5.62681 6.5438' + 'L5.33384 10.2137C5.28364 10.8429 5.03612 11.4403 4.62681 11.9208' + 'L2.23814 14.7235C1.91997 15.0971 1.91997 15.6467 2.23814 16.0204' + 'L4.62681 18.8231C5.03612 19.3035 5.28364 19.901 5.33384 20.5301' + 'L5.62681 24.2001C5.66591 24.6895 6.05436 25.078 6.5438 25.117' + 'L10.2137 25.41C10.8429 25.4602 11.4403 25.7077 11.9208 26.117' + 'L14.7235 28.5057C15.0971 28.8239 15.6467 28.8239 16.0204 28.5057' + 'L18.8231 26.117C19.3035 25.7077 19.901 25.4602 20.5301 25.41' + 'L24.2001 25.117C24.6895 25.078 25.078 24.6895 25.117 24.2001' + 'L25.41 20.5301C25.4602 19.901 25.7077 19.3035 26.117 18.8231' + 'L28.5057 16.0204C28.8239 15.6467 28.8239 15.0971 28.5057 14.7235' + 'L26.117 11.9208C25.7077 11.4403 25.4602 10.8429 25.41 10.2137' + 'L25.117 6.5438C25.078 6.05435 24.6895 5.66591 24.2001 5.62681' + 'L20.5301 5.33384C19.901 5.28364 19.3035 5.03612 18.8231 4.62681' + 'L16.0204 2.23814Z'; diff --git a/lib/src/ui/components/personalization_product.dart b/lib/src/ui/components/personalization_product.dart new file mode 100644 index 0000000..18b7aa2 --- /dev/null +++ b/lib/src/ui/components/personalization_product.dart @@ -0,0 +1,33 @@ +import 'package:flutter/widgets.dart'; + +import 'personalization_product_card.dart'; + +/// Данные товара для карточки и раскладок каталога. +/// +/// Строки уже отформатированы: цена с валютой, оценка с запятой, скидка со знаком — +/// форматирование и локализация остаются за интегратором. +/// Картинку грузит штатный [Image] по [image]: NetworkImage есть во фреймворке. +@immutable +class PersonalizationProduct { + const PersonalizationProduct({ + required this.id, + required this.name, + required this.price, + this.image, + this.brand, + this.rating, + this.oldPrice, + this.discount, + this.actionText, + }); + + final String id; + final String name; + final String price; + final ImageProvider? image; + final String? brand; + final PersonalizationProductRating? rating; + final String? oldPrice; + final String? discount; + final String? actionText; +} diff --git a/lib/src/ui/components/personalization_product_card.dart b/lib/src/ui/components/personalization_product_card.dart new file mode 100644 index 0000000..35ac0cd --- /dev/null +++ b/lib/src/ui/components/personalization_product_card.dart @@ -0,0 +1,376 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; +import 'personalization_badge.dart'; +import 'personalization_button.dart'; +import 'personalization_product_image.dart'; +import 'personalization_rating.dart'; + +/// Тип карточки товара. +enum PersonalizationProductCardType { carousel, grid, list } + +/// Оценка товара для карточки. +class PersonalizationProductRating { + const PersonalizationProductRating({ + required this.value, + required this.reviews, + }); + + /// Уже отформатированная оценка: в макете «4,7» с запятой. + final String value; + final int reviews; +} + +/// Карточка товара. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Card, фрейм Product (126:2263): +/// carousel — колонка 220, grid — колонка на всю ширину ячейки, list — строка с картинкой +/// шириной 120 и ценой с кнопкой внизу справа. Пропорция картинки — [imageAspect]: на +/// странице ProductCard (88:69) карточка нарисована с 4:3, 1:1 и 3:4, и её высота идёт +/// за картинкой. +/// У трёх типов разная типографика названия, цены и старой цены, поэтому она задана +/// в таблице. Старая цена карусели — 16/24 по страницам ProductCard и Product Carousel; +/// мастер-компонент Product там же даёт 14/20 — расхождение в макете, взяты страницы. +/// +/// Собрана из готовых блоков: [PersonalizationProductImage], [PersonalizationRating], +/// [PersonalizationBadge] (скидка, вид danger), [PersonalizationButton]. +class PersonalizationProductCard extends StatelessWidget { + const PersonalizationProductCard({ + super.key, + this.type = PersonalizationProductCardType.carousel, + this.image, + this.imageAspect = PersonalizationProductImageAspect.square, + this.brand, + required this.name, + this.rating, + required this.price, + this.oldPrice, + this.discount, + this.actionText, + this.onAction, + this.onTap, + this.iconBuilder, + }); + + final PersonalizationProductCardType type; + final ImageProvider? image; + + /// Пропорция картинки; высота карточки идёт за ней. + final PersonalizationProductImageAspect imageAspect; + final String? brand; + final String name; + final PersonalizationProductRating? rating; + final String price; + + /// Старая цена, зачёркнутая. `null` — не показывать. + final String? oldPrice; + + /// Скидка, например «-15%». `null` — без бейджа. + final String? discount; + + /// Подпись кнопки. `null` — без кнопки. + final String? actionText; + final VoidCallback? onAction; + + /// Нажатие на карточку целиком (не на кнопку) — открыть товар. + final VoidCallback? onTap; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final metrics = _metrics[type]!; + + TextStyle style( + double fontSize, + double lineHeight, + double letterSpacing, + FontWeight weight, + Color color, + ) => TextStyle( + fontFamily: theme.fontFamily.familyFor(weight), + package: theme.fontFamily.package, + fontSize: fontSize, + height: lineHeight / fontSize, + letterSpacing: letterSpacing, + fontWeight: weight, + color: color, + ); + + Widget nameBlock(double gap) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (brand != null && brand!.isNotEmpty) ...[ + Text( + brand!, + style: style(12, 16, 0.05, FontWeight.w400, colors.textSecondary), + ), + SizedBox(height: gap), + ], + Text( + name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: style( + metrics.nameSize, + metrics.nameLineHeight, + metrics.nameLetterSpacing, + FontWeight.w400, + colors.textPrimary, + ), + ), + ], + ); + + final Widget? ratingRow = rating == null + ? null + : PersonalizationRating( + value: rating!.value, + reviews: rating!.reviews, + iconBuilder: iconBuilder, + ); + final Widget priceText = Text( + price, + style: style( + metrics.priceSize, + metrics.priceLineHeight, + 0, + FontWeight.w600, + colors.textPrimary, + ), + ); + final Widget? oldPriceText = oldPrice == null + ? null + : Text( + oldPrice!, + style: style( + metrics.oldPriceSize, + metrics.oldPriceLineHeight, + metrics.oldPriceLetterSpacing, + FontWeight.w400, + colors.textHint, + ).copyWith(decoration: TextDecoration.lineThrough), + ); + final Widget? discountBadge = discount == null + ? null + : PersonalizationBadge( + label: discount!, + size: PersonalizationBadgeSize.sm, + view: PersonalizationBadgeView.danger, + ); + final Widget? action = actionText == null + ? null + : PersonalizationButton( + label: actionText, + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.primary, + onPressed: onAction, + ); + + // List: картинка шириной 120 слева, справа колонка — название с рейтингом сверху, + // цена с кнопкой снизу. Высота строки — большее из картинки и текста, поэтому + // IntrinsicHeight: колонка тянется до картинки, а низкая картинка её не сжимает. + if (type == PersonalizationProductCardType.list) { + return _tappable( + IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + width: 120, + child: PersonalizationProductImage( + image: image, + aspect: imageAspect, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + nameBlock(2), + if (ratingRow != null) ...[ + const SizedBox(height: 4), + ratingRow, + ], + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + priceText, + if (discountBadge != null) ...[ + const SizedBox(width: 8), + discountBadge, + ], + ], + ), + ?oldPriceText, + ], + ), + ?action, + ], + ), + ], + ), + ), + ], + ), + ), + ); + } + + // Carousel и Grid: картинка, название, рейтинг, цена, кнопка — колонкой с шагом 8. + // У колонок скидка лежит на картинке: отступ 8 у carousel и 4 у grid. + // Колонка из двух групп: верх (картинка, название, рейтинг) и низ (цена, кнопка). + // Когда ряд или карусель растягивают карточку до самой высокой соседки, лишнее + // уходит между группами — цена с кнопкой остаются на одной линии, даже если + // название ушло на две строки. В макете такой случай не нарисован: там названия + // в одну строку. Сама по себе (без растяжения) колонка остаётся по содержимому. + final column = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Stack( + children: [ + PersonalizationProductImage(image: image, aspect: imageAspect), + if (discountBadge != null) + Positioned( + top: metrics.badgeInset, + right: metrics.badgeInset, + child: discountBadge, + ), + ], + ), + const SizedBox(height: 8), + nameBlock(2), + if (ratingRow != null) ...[ + const SizedBox(height: 8), + ratingRow, + ], + ], + ), + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + 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, + ], + ], + ), + if (action != null) ...[const SizedBox(height: 8), action], + ], + ), + ], + ); + return _tappable( + type == PersonalizationProductCardType.carousel + ? SizedBox(width: 220, child: column) + : column, + ); + } + + Widget _tappable(Widget child) => onTap == null + ? child + : GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onTap, + child: child, + ); +} + +class _CardMetrics { + const _CardMetrics({ + required this.nameSize, + required this.nameLineHeight, + required this.nameLetterSpacing, + required this.priceSize, + required this.priceLineHeight, + required this.oldPriceSize, + required this.oldPriceLineHeight, + required this.oldPriceLetterSpacing, + required this.badgeInset, + }); + + final double nameSize, + nameLineHeight, + nameLetterSpacing, + priceSize, + priceLineHeight; + final double oldPriceSize, + oldPriceLineHeight, + oldPriceLetterSpacing, + badgeInset; +} + +const Map _metrics = + { + PersonalizationProductCardType.carousel: _CardMetrics( + nameSize: 16, + nameLineHeight: 24, + nameLetterSpacing: 0, + priceSize: 20, + priceLineHeight: 32, + oldPriceSize: 16, + oldPriceLineHeight: 24, + oldPriceLetterSpacing: 0, + badgeInset: 8, + ), + PersonalizationProductCardType.grid: _CardMetrics( + nameSize: 16, + nameLineHeight: 24, + nameLetterSpacing: 0, + priceSize: 18, + priceLineHeight: 28, + oldPriceSize: 14, + oldPriceLineHeight: 20, + oldPriceLetterSpacing: 0.05, + badgeInset: 4, + ), + PersonalizationProductCardType.list: _CardMetrics( + nameSize: 14, + nameLineHeight: 20, + nameLetterSpacing: 0.05, + priceSize: 16, + priceLineHeight: 24, + oldPriceSize: 14, + oldPriceLineHeight: 20, + oldPriceLetterSpacing: 0.05, + badgeInset: 0, + ), + }; diff --git a/lib/src/ui/components/personalization_product_image.dart b/lib/src/ui/components/personalization_product_image.dart new file mode 100644 index 0000000..16e3291 --- /dev/null +++ b/lib/src/ui/components/personalization_product_image.dart @@ -0,0 +1,45 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Пропорция изображения товара. +enum PersonalizationProductImageAspect { square, landscape, portrait } + +/// Изображение товара с фиксированной пропорцией. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Image (88:93), фрейм Product (88:94): +/// три пропорции — 1:1, 4:3, 3:4. Ширину задаёт разметка, высота считается сама. +/// +/// Картинку грузит штатный [Image] по [image]: NetworkImage есть в самом фреймворке. +/// До загрузки виден плейсхолдер цвета Background/Card — в макете заливка +/// плейсхолдера к переменной не привязана, взят ближайший токен. +class PersonalizationProductImage extends StatelessWidget { + const PersonalizationProductImage({ + super.key, + this.image, + this.aspect = PersonalizationProductImageAspect.square, + }); + + final ImageProvider? image; + final PersonalizationProductImageAspect aspect; + + double get _ratio => switch (aspect) { + PersonalizationProductImageAspect.square => 1, + PersonalizationProductImageAspect.landscape => 4 / 3, + PersonalizationProductImageAspect.portrait => 3 / 4, + }; + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + return AspectRatio( + aspectRatio: _ratio, + // Заглушка до загрузки. В макете она нетокенный серый, здесь — Neutral 50: + // полупрозрачная, поэтому видна и на карточке, и прямо на фоне экрана. + child: ColoredBox( + color: colors.neutral50, + child: image == null ? null : Image(image: image!, fit: BoxFit.cover), + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_products_list.dart b/lib/src/ui/components/personalization_products_list.dart new file mode 100644 index 0000000..ab269d7 --- /dev/null +++ b/lib/src/ui/components/personalization_products_list.dart @@ -0,0 +1,185 @@ +import 'package:flutter/widgets.dart'; + +import 'personalization_product.dart'; +import 'personalization_product_card.dart'; +import 'personalization_product_image.dart'; + +/// Раскладка каталога. +enum PersonalizationProductsLayout { carousel, grid, list } + +/// Лента, плитка и список карточек товара. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Card — Products Carousel (203:6296) +/// и Products Grid (203:4766) в видах Grid и List. +/// Карусель — карточки carousel горизонтально с шагом 16; плитка — карточки grid +/// в две колонки с шагом 16 по обеим осям; список — карточки list столбиком с шагом 16. +/// +/// Плитка и список сами не скроллят: их высоту задаёт содержимое, прокрутка +/// остаётся за экраном хоста. Карусель скроллит горизонтально и сообщает +/// индекс первой видимой карточки через [onFirstVisibleChanged]. +class PersonalizationProductsList extends StatefulWidget { + const PersonalizationProductsList({ + super.key, + this.layout = PersonalizationProductsLayout.carousel, + required this.products, + this.imageAspect = PersonalizationProductImageAspect.square, + this.onProductAction, + this.onProductTap, + this.onFirstVisibleChanged, + this.carouselPadding, + this.iconBuilder, + }); + + final PersonalizationProductsLayout layout; + final List products; + + /// Пропорция картинок карточек, см. [PersonalizationProductCard.imageAspect]. + final PersonalizationProductImageAspect imageAspect; + final ValueChanged? onProductAction; + + /// Нажатие на карточку — открыть товар. + final ValueChanged? onProductTap; + final ValueChanged? onFirstVisibleChanged; + + /// Поля карусели внутри её прокрутки: крайние карточки уезжают под край, а не + /// обрезаются полем. У плитки и списка поля задаёт разметка хоста. + final EdgeInsetsGeometry? carouselPadding; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + State createState() => + _PersonalizationProductsListState(); +} + +class _PersonalizationProductsListState + extends State { + final ScrollController _controller = ScrollController(); + int _lastFirst = -1; + + static const double _gap = 16; + static const double _carouselCard = 220; + + @override + void initState() { + super.initState(); + _controller.addListener(_onScroll); + } + + @override + void dispose() { + _controller.removeListener(_onScroll); + _controller.dispose(); + super.dispose(); + } + + void _onScroll() { + if (widget.layout != PersonalizationProductsLayout.carousel) return; + // Первая полностью видимая карточка: шаг ленты — ширина карточки плюс зазор. + final first = (_controller.offset / (_carouselCard + _gap)).ceil(); + final clamped = first.clamp( + 0, + widget.products.isEmpty ? 0 : widget.products.length - 1, + ); + if (clamped != _lastFirst) { + _lastFirst = clamped; + widget.onFirstVisibleChanged?.call(clamped); + } + } + + Widget _card( + PersonalizationProduct product, + PersonalizationProductCardType type, + ) { + return PersonalizationProductCard( + type: type, + image: product.image, + imageAspect: widget.imageAspect, + brand: product.brand, + name: product.name, + rating: product.rating, + price: product.price, + oldPrice: product.oldPrice, + discount: product.discount, + actionText: product.actionText, + onAction: widget.onProductAction == null + ? null + : () => widget.onProductAction!(product), + onTap: widget.onProductTap == null + ? null + : () => widget.onProductTap!(product), + iconBuilder: widget.iconBuilder, + ); + } + + @override + Widget build(BuildContext context) { + final products = widget.products; + switch (widget.layout) { + case PersonalizationProductsLayout.carousel: + // IntrinsicHeight + stretch: соседние карточки одной высоты, и карточка + // сама держит цену с кнопкой у нижнего края (см. PersonalizationProductCard). + return SingleChildScrollView( + controller: _controller, + scrollDirection: Axis.horizontal, + padding: widget.carouselPadding, + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (int i = 0; i < products.length; i++) ...[ + if (i > 0) const SizedBox(width: _gap), + _card(products[i], PersonalizationProductCardType.carousel), + ], + ], + ), + ), + ); + case PersonalizationProductsLayout.grid: + return Column( + children: [ + for (int row = 0; row < products.length; row += 2) ...[ + if (row > 0) const SizedBox(height: _gap), + IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: _card( + products[row], + PersonalizationProductCardType.grid, + ), + ), + const SizedBox(width: _gap), + Expanded( + child: row + 1 < products.length + ? _card( + products[row + 1], + PersonalizationProductCardType.grid, + ) + : const SizedBox.shrink(), + ), + ], + ), + ), + ], + ], + ); + case PersonalizationProductsLayout.list: + return Column( + children: [ + for (int i = 0; i < products.length; i++) ...[ + if (i > 0) const SizedBox(height: _gap), + _card(products[i], PersonalizationProductCardType.list), + ], + ], + ); + } + } +} diff --git a/lib/src/ui/components/personalization_rating.dart b/lib/src/ui/components/personalization_rating.dart new file mode 100644 index 0000000..ce28a21 --- /dev/null +++ b/lib/src/ui/components/personalization_rating.dart @@ -0,0 +1,93 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; +import '../personalization_icons.dart'; + +/// Рейтинг товара, короткая форма. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Rating (88:209), фрейм Product Short (237:4711). +/// Вариант Reviews меняет только данные и цвет звезды: без отзывов она серая. +/// +/// Внимание: типографика 16/20 — кегль со ступени base, интерлиньяж со ступени sm. +/// Ступень base — это 16/24, поэтому размеры заданы явно. +/// +/// Цвет заполненной звезды в макете не привязан к переменной, взят ближайший +/// существующий токен semanticWarning — его стоит подтвердить у дизайнера. +class PersonalizationRating extends StatelessWidget { + const PersonalizationRating({ + super.key, + required this.value, + required this.reviews, + this.iconBuilder, + }); + + /// Уже отформатированная оценка: в макете «4,7» с запятой. + final String value; + final int reviews; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + const double fontSize = 16; + final TextStyle base = TextStyle( + fontSize: fontSize, + height: 20 / fontSize, + letterSpacing: 0, + fontWeight: FontWeight.w400, + fontFamily: theme.fontFamily.familyFor(FontWeight.w400), + package: theme.fontFamily.package, + color: colors.textHint, + ); + final Color starColor = reviews > 0 + ? colors.semanticWarning + : colors.lineGeneric; + + return Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox( + width: 20, + height: 20, + child: iconBuilder?.call( + context, + PersonalizationIcons.starFill, + 20, + starColor, + ), + ), + const SizedBox(width: 4), + Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + value, + style: base.copyWith( + fontWeight: FontWeight.w600, + fontFamily: theme.fontFamily.familyFor(FontWeight.w600), + package: theme.fontFamily.package, + color: colors.textSecondary, + ), + ), + const SizedBox(width: 2), + Text('($reviews)', style: base), + ], + ), + ], + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_recommender_block.dart b/lib/src/ui/components/personalization_recommender_block.dart new file mode 100644 index 0000000..fa86501 --- /dev/null +++ b/lib/src/ui/components/personalization_recommender_block.dart @@ -0,0 +1,119 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_icons.dart'; +import 'personalization_button.dart'; +import 'personalization_dots.dart'; +import 'personalization_product.dart'; +import 'personalization_product_card.dart'; +import 'personalization_product_image.dart'; +import 'personalization_products_list.dart'; +import 'personalization_title.dart'; + +/// Блок рекомендаций: заголовок, товары, у карусели — точки. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Card — Recommender/Carousel (90:655), +/// Recommender/Grid (126:1944), Recommender/List (126:2551). +/// У карусели заголовок с кнопкой «Show all» и точки под лентой, шаг блока 16; +/// у плитки и списка только заголовок, шаг 12. +/// +/// Собран из [PersonalizationTitle], [PersonalizationButton], +/// [PersonalizationProductsList], [PersonalizationDots]. +class PersonalizationRecommenderBlock extends StatefulWidget { + const PersonalizationRecommenderBlock({ + super.key, + this.layout = PersonalizationProductsLayout.carousel, + required this.title, + this.showAllText, + this.onShowAll, + this.showDots = true, + required this.products, + this.imageAspect = PersonalizationProductImageAspect.square, + this.onProductAction, + this.onProductTap, + this.iconBuilder, + }); + + final PersonalizationProductsLayout layout; + final String title; + + /// Подпись кнопки «показать все» у карусели. `null` — без кнопки. + final String? showAllText; + final VoidCallback? onShowAll; + + /// У карусели точки под лентой; выключаются, как в макете (showDots). + final bool showDots; + final List products; + + /// Пропорция картинок карточек, см. [PersonalizationProductCard.imageAspect]. + final PersonalizationProductImageAspect imageAspect; + final ValueChanged? onProductAction; + + /// Нажатие на карточку — открыть товар. + final ValueChanged? onProductTap; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + State createState() => + _PersonalizationRecommenderBlockState(); +} + +class _PersonalizationRecommenderBlockState + extends State { + int _page = 0; + + @override + Widget build(BuildContext context) { + final carousel = widget.layout == PersonalizationProductsLayout.carousel; + final double gap = carousel ? 16 : 12; + final bool showAll = + carousel && + widget.showAllText != null && + widget.showAllText!.isNotEmpty; + + 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), + PersonalizationProductsList( + layout: widget.layout, + products: widget.products, + imageAspect: widget.imageAspect, + onProductAction: widget.onProductAction, + onProductTap: widget.onProductTap, + onFirstVisibleChanged: carousel + ? (int index) => setState(() => _page = index) + : null, + iconBuilder: widget.iconBuilder, + ), + if (carousel && widget.showDots) ...[ + SizedBox(height: gap), + PersonalizationDots( + count: widget.products.length, + selectedIndex: _page, + ), + ], + ], + ); + } +} diff --git a/lib/src/ui/components/personalization_search_results_title.dart b/lib/src/ui/components/personalization_search_results_title.dart new file mode 100644 index 0000000..8233567 --- /dev/null +++ b/lib/src/ui/components/personalization_search_results_title.dart @@ -0,0 +1,185 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; +import '../personalization_icons.dart'; +import 'personalization_button.dart'; +import 'personalization_button_group.dart'; +import 'personalization_tag.dart'; +import 'personalization_title.dart'; + +/// Применённый фильтр: подпись и снятие по крестику. +class PersonalizationSearchFilter { + const PersonalizationSearchFilter({ + required this.label, + required this.onRemove, + }); + + final String label; + final VoidCallback onRemove; +} + +/// Строка «найдено N товаров». Слова — параметры, локализация за интегратором. +class PersonalizationSearchResults { + const PersonalizationSearchResults({ + required this.prefix, + required this.count, + required this.suffix, + }); + + final String prefix; + final int count; + final String suffix; +} + +/// Заголовок выдачи поиска. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Title (167:3802), символ Search results (167:3807). +/// Три ряда: заголовок с кнопкой «назад» и переключателем вида, строка с фильтром, +/// сортировкой и числом найденного, ряд применённых фильтров-тегов. +/// Два нижних ряда в макете скрываемые (showResults, showFilters) — здесь они +/// прячутся сами, когда данных нет. +/// +/// Собран из готовых компонентов: [PersonalizationTitle], [PersonalizationButton], +/// [PersonalizationButtonGroup], [PersonalizationTag]. +class PersonalizationSearchResultsTitle extends StatelessWidget { + const PersonalizationSearchResultsTitle({ + super.key, + required this.title, + this.selectedViewIndex = 0, + this.onBack, + this.onViewChanged, + this.onFilters, + this.onSort, + this.showFiltersButton = true, + this.showSortButton = true, + this.results, + this.filters = const [], + this.iconBuilder, + }); + + final String title; + + /// Индекс выбранного вида выдачи: 0 — плитка, 1 — список. + final int selectedViewIndex; + final VoidCallback? onBack; + final ValueChanged? onViewChanged; + final VoidCallback? onFilters; + final VoidCallback? onSort; + + /// Кнопки фильтров и сортировки; в макете они есть всегда, но виджет может их убрать. + final bool showFiltersButton; + final bool showSortButton; + final PersonalizationSearchResults? results; + final List filters; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final TextStyle regular = TextStyle( + fontSize: 14, + height: 20 / 14, + letterSpacing: 0.05, + fontWeight: FontWeight.w400, + fontFamily: theme.fontFamily.familyFor(FontWeight.w400), + package: theme.fontFamily.package, + color: colors.textSecondary, + ); + final TextStyle strong = regular.copyWith(fontWeight: FontWeight.w600); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + PersonalizationTitle( + title: title, + leading: PersonalizationButton( + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.ghost, + iconStart: PersonalizationIcons.arrowLeft, + iconBuilder: iconBuilder, + onPressed: onBack, + ), + trailing: PersonalizationButtonGroup( + items: const [ + PersonalizationButtonGroupItem( + icon: PersonalizationIcons.grid2x2, + activeIcon: PersonalizationIcons.grid2x2Fill, + ), + PersonalizationButtonGroupItem( + icon: PersonalizationIcons.list, + activeIcon: PersonalizationIcons.listFill, + ), + ], + selectedIndex: selectedViewIndex, + onSelected: onViewChanged, + iconBuilder: iconBuilder, + ), + ), + if (results != null) ...[ + const SizedBox(height: 8), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (showFiltersButton) + PersonalizationButton( + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.ghost, + iconStart: PersonalizationIcons.equalizerHorizontal, + iconBuilder: iconBuilder, + onPressed: onFilters, + ), + if (showFiltersButton && showSortButton) const SizedBox(width: 4), + if (showSortButton) + PersonalizationButton( + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.ghost, + iconStart: PersonalizationIcons.arrowsUpDown, + iconBuilder: iconBuilder, + onPressed: onSort, + ), + 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 (filters.isNotEmpty) ...[ + const SizedBox(height: 8), + Wrap( + spacing: 4, + runSpacing: 4, + children: [ + for (final PersonalizationSearchFilter filter in filters) + PersonalizationTag( + label: filter.label, + view: PersonalizationTagView.secondary, + onRemove: filter.onRemove, + removeIconBuilder: iconBuilder == null + ? null + : (BuildContext context, String asset) => iconBuilder!( + context, + asset, + 16, + colors.textPrimary, + ), + ), + ], + ), + ], + ], + ); + } +} diff --git a/lib/src/ui/components/personalization_stories_bar.dart b/lib/src/ui/components/personalization_stories_bar.dart new file mode 100644 index 0000000..d2273bc --- /dev/null +++ b/lib/src/ui/components/personalization_stories_bar.dart @@ -0,0 +1,110 @@ +import 'package:flutter/widgets.dart'; + +import 'personalization_story_cover.dart'; +import 'personalization_story_preview.dart'; + +/// Данные превью в ленте сторис. +@immutable +class PersonalizationStoryItem { + const PersonalizationStoryItem({ + required this.id, + required this.label, + this.image, + this.pinned = false, + this.viewed = false, + this.segments = 0, + this.seenSegments = const {}, + }); + + final String id; + final String label; + + /// Картинку даёт хост — кит не тянет сеть. + final ImageProvider? image; + final bool pinned; + final bool viewed; + + /// См. [PersonalizationStoryCover.segments]. + final int segments; + + /// См. [PersonalizationStoryCover.seenSegments]. + final Set seenSegments; +} + +/// Лента сторис: превью в горизонтальной прокрутке. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), фреймы «Блок сторис на +/// странице» (светлый и тёмный). +/// +/// Превью [PersonalizationStoryPreview] с шагом 16, поля ленты 16 — оба хост может +/// переопределить. Пока идёт загрузка ([loading]), вместо превью — [skeletonCount] +/// заглушек. +class PersonalizationStoriesBar extends StatelessWidget { + const PersonalizationStoriesBar({ + super.key, + this.items = const [], + this.loading = false, + this.skeletonCount = 4, + this.padding = const EdgeInsets.all(16), + this.gap = 16, + this.onItemTap, + this.iconBuilder, + }); + + final List items; + + /// Идёт загрузка: вместо [items] — заглушки. + final bool loading; + final int skeletonCount; + final EdgeInsetsGeometry padding; + final double gap; + final ValueChanged? onItemTap; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + Widget build(BuildContext context) { + final previews = [ + if (loading) + for (int i = 0; i < skeletonCount; i++) + const PersonalizationStoryPreview( + state: PersonalizationStoryCoverState.skeleton, + ) + else + for (final item in items) + PersonalizationStoryPreview( + key: ValueKey(item.id), + label: item.label, + image: item.image, + state: item.viewed + ? PersonalizationStoryCoverState.viewed + : PersonalizationStoryCoverState.unviewed, + pinned: item.pinned, + segments: item.segments, + seenSegments: item.seenSegments, + onTap: onItemTap == null ? null : () => onItemTap!(item), + iconBuilder: iconBuilder, + ), + ]; + + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: padding, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (int i = 0; i < previews.length; i++) ...[ + if (i > 0) SizedBox(width: gap), + previews[i], + ], + ], + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_story_cover.dart b/lib/src/ui/components/personalization_story_cover.dart new file mode 100644 index 0000000..3f211ff --- /dev/null +++ b/lib/src/ui/components/personalization_story_cover.dart @@ -0,0 +1,232 @@ +import 'dart:math' as math; + +import 'package:flutter/widgets.dart'; + +import '../personalization_colors.dart'; +import '../personalization_theme.dart'; +import 'personalization_favorites_badge.dart'; +import 'personalization_story_shimmer.dart'; + +/// Состояние обложки сторис. +/// +/// В макете у Story/Cover четыре состояния: Default, Pinned, Viewed, Skeleton. Pinned +/// здесь не состояние, а флаг [PersonalizationStoryCover.pinned]: в данных «закреплена» +/// и «просмотрена» независимы, и закреплённая сторис остаётся со звездой и после +/// просмотра — так и в прежних сторис SDK. Default — [unviewed]. +enum PersonalizationStoryCoverState { unviewed, viewed, skeleton } + +/// Обложка сторис: круглая картинка в кольце. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), компонент Story/Cover, +/// сегменты кольца — Progress/Circular. +/// +/// Круг 88. Кольцо — обводка 4 внутрь; картинка — круг 76 с отступом 6, то есть между +/// ними зазор 2. Цвет кольца: Button/Primary у непросмотренной, Semantic/Warning у +/// закреплённой — всегда, и после просмотра, Semantic/Neutral Subtle у просмотренной +/// незакреплённой. Закреплённой в правом нижнем углу (x62, y62) — метка Favorites 24: +/// звезда на Semantic/Warning, тоже всегда. У заглушки кольцо и картинка переливаются +/// градиентом (см. [PersonalizationStoryShimmer]). +/// +/// Сегменты: при [segments] > 1 кольцо делится на столько дуг с небольшими зазорами — +/// по дуге на слайд. Дуга i горит — Button/Primary Disabled (Brand/Primary 65%), — если +/// слайд i просмотрен (его номер есть в [seenSegments]), остальные в цвете состояния. +/// Просмотренная сторис рисуется сплошным кольцом без дуг и зазоров: незакреплённая — +/// Neutral Subtle, как состояние Viewed в макете, закреплённая — Warning. Правило +/// цветов — [ringColors]. +class PersonalizationStoryCover extends StatelessWidget { + const PersonalizationStoryCover({ + super.key, + this.image, + this.state = PersonalizationStoryCoverState.unviewed, + this.pinned = false, + this.segments = 0, + this.seenSegments = const {}, + this.iconBuilder, + }); + + /// Картинку даёт хост — кит не тянет сеть. + final ImageProvider? image; + final PersonalizationStoryCoverState state; + + /// Закреплена магазином: кольцо Semantic/Warning и звезда — и после просмотра. + final bool pinned; + + /// На сколько дуг поделить кольцо; 0 и 1 — сплошное. + final int segments; + + /// Номера просмотренных слайдов — горящие дуги. + final Set seenSegments; + + /// Как нарисовать звезду метки закреплённой: пакет не рисует SVG сам. + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + static const double size = 88; + static const double _ring = 4; + + /// Цвета дуг кольца по порядку; одна — кольцо сплошное. + /// + /// - просмотренная незакреплённая — одно Neutral Subtle; + /// - просмотренная закреплённая — одно Warning, без горящих дуг; + /// - иначе цвет состояния (Warning у закреплённой, Button/Primary у остальных), а при + /// [segments] > 1 дуга i — Button/Primary Disabled, если слайд i в [seen]. + static List ringColors( + PersonalizationColors colors, { + required PersonalizationStoryCoverState state, + bool pinned = false, + int segments = 0, + Set seen = const {}, + }) { + final viewed = state == PersonalizationStoryCoverState.viewed; + if (viewed && !pinned) return [colors.neutralSubtle]; + final stateColor = pinned ? colors.semanticWarning : colors.buttonPrimary; + if (viewed || segments <= 1) return [stateColor]; + return [ + for (int i = 0; i < segments; i++) + seen.contains(i) ? colors.buttonPrimaryDisabled : stateColor, + ]; + } + + static const double _imageInset = 6; + static const double _badgeOffset = 62; + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + + if (state == PersonalizationStoryCoverState.skeleton) { + return PersonalizationStoryShimmer( + builder: (context, gradient) => SizedBox.square( + dimension: size, + child: CustomPaint( + painter: _RingPainter( + colors: const [], + gradient: gradient, + segments: 1, + ), + child: Padding( + padding: const EdgeInsets.all(_imageInset), + child: DecoratedBox( + decoration: BoxDecoration( + shape: BoxShape.circle, + gradient: gradient, + ), + ), + ), + ), + ), + ); + } + + final ring = ringColors( + colors, + state: state, + pinned: pinned, + segments: segments, + seen: seenSegments, + ); + + return SizedBox.square( + dimension: size, + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: CustomPaint( + painter: _RingPainter(colors: ring, segments: ring.length), + ), + ), + Positioned.fill( + child: Padding( + padding: const EdgeInsets.all(_imageInset), + child: ClipOval( + child: ColoredBox( + // Заглушка до загрузки — Neutral 50, как у картинки товара. + color: colors.neutral50, + child: image == null + ? null + : Image(image: image!, fit: BoxFit.cover), + ), + ), + ), + ), + if (pinned) + Positioned( + left: _badgeOffset, + top: _badgeOffset, + child: PersonalizationFavoritesBadge(iconBuilder: iconBuilder), + ), + ], + ), + ); + } +} + +/// Кольцо обложки: обводка 4 внутрь круга, сплошная или дугами с зазорами. +class _RingPainter extends CustomPainter { + const _RingPainter({ + required this.colors, + required this.segments, + this.gradient, + }); + + /// Цвет каждой дуги; игнорируется, если задан [gradient]. + final List colors; + final int segments; + final Gradient? gradient; + + /// Зазор между дугами по средней линии кольца. + static const double _gap = 4; + + @override + void paint(Canvas canvas, Size size) { + const stroke = PersonalizationStoryCover._ring; + final rect = (Offset.zero & size).deflate(stroke / 2); + final paint = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = stroke; + final shader = gradient?.createShader(Offset.zero & size); + + if (segments <= 1) { + if (shader != null) { + paint.shader = shader; + } else { + paint.color = colors.first; + } + canvas.drawOval(rect, paint); + return; + } + + final gapAngle = _gap / (rect.width / 2); + final sweep = (math.pi * 2 - gapAngle * segments) / segments; + for (int i = 0; i < segments; i++) { + if (shader != null) { + paint.shader = shader; + } else { + paint.color = colors[i]; + } + // Первая дуга начинается сверху, после половины зазора. + final start = -math.pi / 2 + gapAngle / 2 + i * (sweep + gapAngle); + canvas.drawArc(rect, start, sweep, false, paint); + } + } + + @override + bool shouldRepaint(_RingPainter oldDelegate) => + oldDelegate.segments != segments || + oldDelegate.gradient != gradient || + !_sameColors(oldDelegate.colors, colors); + + static bool _sameColors(List a, List b) { + if (a.length != b.length) return false; + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; + } +} diff --git a/lib/src/ui/components/personalization_story_navigation.dart b/lib/src/ui/components/personalization_story_navigation.dart new file mode 100644 index 0000000..6d57dee --- /dev/null +++ b/lib/src/ui/components/personalization_story_navigation.dart @@ -0,0 +1,96 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_icons.dart'; +import '../personalization_theme.dart'; +import 'personalization_story_progress.dart'; + +/// Шапка просмотра сторис: прогресс слайдов и крестик. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), компонент +/// Navigation/Story. +/// +/// Колонка с шагом 12: [PersonalizationStoryProgress] и строка высотой 32, в конце +/// которой крестик — иконка cross 32 (глиф 18) цвета Text/Secondary с прозрачностью 65%. +/// Касания ловит только крестик. +class PersonalizationStoryNavigation extends StatelessWidget { + const PersonalizationStoryNavigation({ + super.key, + required this.count, + this.current = 0, + this.progress = 0, + this.onClose, + this.closeLabel = 'Close', + this.iconBuilder, + }); + + /// См. [PersonalizationStoryProgress]. + final int count; + final int current; + final double progress; + + final VoidCallback? onClose; + + /// Подпись крестика для скринридера. + final String closeLabel; + + /// Как нарисовать крестик: пакет не рисует SVG сам. + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + static const double _close = 32; + + /// Высота шапки: прогресс, шаг 12 и строка крестика. + static const double height = + PersonalizationStoryProgress.height + 12 + _close; + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + // Прогресс касаний не ловит: они уходят слайду под шапкой. + IgnorePointer( + child: PersonalizationStoryProgress( + count: count, + current: current, + progress: progress, + ), + ), + 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( + context, + PersonalizationIcons.cross, + _close, + colors.textSecondary, + ), + ), + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/src/ui/components/personalization_story_preview.dart b/lib/src/ui/components/personalization_story_preview.dart new file mode 100644 index 0000000..a41a479 --- /dev/null +++ b/lib/src/ui/components/personalization_story_preview.dart @@ -0,0 +1,116 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; +import '../personalization_typography.dart'; +import 'personalization_story_cover.dart'; +import 'personalization_story_shimmer.dart'; + +/// Превью сторис в ленте: обложка и подпись под ней. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), компонент Story/Preview. +/// +/// Колонка шириной 88 с шагом 8: [PersonalizationStoryCover] и подпись Regular 12/16 +/// (ступень XS) цветом Text/Primary, по центру, шириной с обложку — до двух строк, хвост +/// с многоточием. У заглушки вместо подписи — переливающаяся плашка 64×8 со скруглением +/// 5 на месте строки. +class PersonalizationStoryPreview extends StatelessWidget { + const PersonalizationStoryPreview({ + super.key, + this.label = '', + this.image, + this.state = PersonalizationStoryCoverState.unviewed, + this.pinned = false, + this.segments = 0, + this.seenSegments = const {}, + this.onTap, + this.iconBuilder, + }); + + final String label; + final ImageProvider? image; + final PersonalizationStoryCoverState state; + final bool pinned; + + /// См. [PersonalizationStoryCover.segments]. + final int segments; + + /// См. [PersonalizationStoryCover.seenSegments]. + final Set seenSegments; + + /// Нажатие на превью — открыть сторис. У заглушки не вызывается. + final VoidCallback? onTap; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + static const double width = PersonalizationStoryCover.size; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final skeleton = state == PersonalizationStoryCoverState.skeleton; + const style = PersonalizationTypography.xsDefault; + + final column = SizedBox( + width: width, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + PersonalizationStoryCover( + image: image, + state: state, + pinned: pinned, + segments: segments, + seenSegments: seenSegments, + iconBuilder: iconBuilder, + ), + const SizedBox(height: 8), + if (skeleton) + // Плашка на месте строки: высота превью та же, что с подписью. + SizedBox( + height: 16, + child: Center( + child: PersonalizationStoryShimmer( + builder: (context, gradient) => Container( + width: 64, + height: 8, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(5), + gradient: gradient, + ), + ), + ), + ), + ) + else + Text( + label, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: style.copyWith( + color: theme.colors.textPrimary, + fontFamily: theme.fontFamily.familyFor(style.fontWeight!), + package: theme.fontFamily.package, + ), + ), + ], + ), + ); + + if (skeleton || onTap == null) return column; + return Semantics( + button: true, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onTap, + child: column, + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_story_price.dart b/lib/src/ui/components/personalization_story_price.dart new file mode 100644 index 0000000..6c0e741 --- /dev/null +++ b/lib/src/ui/components/personalization_story_price.dart @@ -0,0 +1,392 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../personalization_icons.dart'; +import '../personalization_theme.dart'; +import 'personalization_toast.dart'; + +/// Вид блока цены сторис. +/// +/// В макете есть ещё Installment (рассрочка), но в данных сторис её нет — не собран. +enum PersonalizationStoryPriceType { + /// Только цена (и старая цена, если есть). + price, + + /// Цена и справа скидка на Brand/Primary. + discount, + + /// Цена и справа промокод на чёрном; нажатие копирует код. + promoCode, +} + +/// Блок цены на слайде с товаром. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), компонент +/// Card/Story/Price — виды Price, Discount и Promo code. +/// +/// Коробка со скруглением 12 и заливкой #F2F2F2 95% — в макете сырой цвет, не +/// переменная, и он одинаков в обеих темах, поэтому текст на ней всегда тёмный +/// (Text/Dark). Левая колонка с полями 12/16: старая цена (если есть) с прозрачностью +/// 50% — сумма SemiBold 14 зачёркнутая и валюта Regular 14/16 цвета Text/Dark Secondary; +/// под ней цена — сумма SemiBold 24 и валюта Regular 14/16 с шагом 4 по базовой линии, +/// Text/Dark Primary. Валюту от суммы отделяет [splitCurrency]. +/// +/// Справа, по [type]: +/// - discount — блок Brand/Primary с полями 0/16, скидка SemiBold 36 Text/Light Primary; +/// левая колонка забирает остаток; +/// - promoCode — чёрный блок (Text/Dark Primary) с полями 12/16: подпись SemiBold 14 +/// Text/Light Secondary и код SemiBold 24 Text/Light Primary по центру, иконка copy 24 +/// (глиф 20) Text/Light Hint в правом верхнем углу с отступом 4. Колонки делят ширину +/// поровну, длинный код забирает сколько нужно. Нажатие слегка увеличивает блок (как +/// Tap Zoom Effect макета), копирует код в буфер, показывает тост [copiedText] — по +/// умолчанию у верхнего края, как во фрейме «Code copied to clipboard» (367:16106), — +/// и зовёт [onPromoCopied]. +class PersonalizationStoryPrice extends StatefulWidget { + const PersonalizationStoryPrice({ + super.key, + this.type = PersonalizationStoryPriceType.price, + required this.price, + this.oldPrice, + this.discount, + this.promoCode, + this.promoCaption = 'Promo code', + this.copiedText = 'Copied', + this.copiedToastPosition = PersonalizationToastPosition.top, + this.onPromoCopied, + this.iconBuilder, + }); + + final PersonalizationStoryPriceType type; + + /// Цена уже отформатированной, с валютой — в макете «1 190 900 ₽». + final String price; + + /// Старая цена; `null` — не показывать. + final String? oldPrice; + + /// Скидка для вида discount, например «10%». + final String? discount; + + /// Код для вида promoCode. + final String? promoCode; + + /// Подпись над кодом. + final String promoCaption; + + /// Текст тоста после копирования. + final String copiedText; + + /// У какого края показать тост. + final PersonalizationToastPosition copiedToastPosition; + + /// Код скопирован. + final ValueChanged? onPromoCopied; + + /// Как нарисовать иконку копирования: пакет не рисует SVG сам. + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + /// Заливка коробки: #F2F2F2 с прозрачностью 95%. + static const Color boxColor = Color(0xF2F2F2F2); + + /// Увеличение промокода при нажатии. + static const double pressedScale = 1.03; + + /// Делит отформатированную цену на сумму и валюту: валюта — нецифровой хвост строки. + /// `"1 190 900 ₽"` → (`"1 190 900"`, `"₽"`), `"9 999₽"` → (`"9 999"`, `"₽"`). Если + /// строка кончается цифрой (`"$140"`), валюты нет — вся строка сумма. + static (String amount, String currency) splitCurrency(String formatted) { + final text = formatted.trim(); + final match = RegExp(r'^(.*\d)\s*(\D+)$').firstMatch(text); + if (match == null) return (text, ''); + return (match.group(1)!.trim(), match.group(2)!.trim()); + } + + @override + State createState() => + _PersonalizationStoryPriceState(); +} + +class _PersonalizationStoryPriceState extends State { + bool _pressed = false; + + static const double _radius = 12; + + String get _code => widget.promoCode ?? ''; + + bool get _hasSide => switch (widget.type) { + PersonalizationStoryPriceType.price => false, + PersonalizationStoryPriceType.discount => + (widget.discount ?? '').isNotEmpty, + PersonalizationStoryPriceType.promoCode => _code.isNotEmpty, + }; + + void _copy() { + final code = _code; + Clipboard.setData(ClipboardData(text: code)); + PersonalizationToast.show( + context, + widget.copiedText, + position: widget.copiedToastPosition, + ); + widget.onPromoCopied?.call(code); + } + + TextStyle _style( + PersonalizationTheme theme, + double size, + double lineHeight, + FontWeight weight, + Color color, + ) => TextStyle( + fontSize: size, + height: lineHeight / size, + fontWeight: weight, + letterSpacing: 0, + fontFamily: theme.fontFamily.familyFor(weight), + package: theme.fontFamily.package, + color: color, + ); + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final side = _hasSide; + const radius = Radius.circular(_radius); + + final left = DecoratedBox( + decoration: BoxDecoration( + color: PersonalizationStoryPrice.boxColor, + borderRadius: side + ? const BorderRadius.horizontal(left: radius) + : const BorderRadius.all(radius), + ), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + child: _prices(theme), + ), + ); + + if (!side) return left; + + if (widget.type == PersonalizationStoryPriceType.discount) { + return IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded(child: left), + DecoratedBox( + decoration: BoxDecoration( + color: colors.brandPrimary, + borderRadius: const BorderRadius.horizontal(right: radius), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Center( + child: Text( + widget.discount!, + maxLines: 1, + style: _style( + theme, + 36, + 44, + FontWeight.w600, + colors.textLightPrimary, + ), + ), + ), + ), + ), + ], + ), + ); + } + + // Промокод: колонки поровну, длинный код забирает сколько нужно — но не больше 70%, + // чтобы цене осталось место; дальше код ужимается. + return LayoutBuilder( + builder: (context, constraints) { + final width = constraints.maxWidth; + return IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded(child: left), + ConstrainedBox( + constraints: BoxConstraints( + minWidth: width / 2, + maxWidth: width * 0.7, + ), + // Ширина по содержимому в пределах ограничений выше. + child: IntrinsicWidth(child: _promo(context, theme)), + ), + ], + ), + ); + }, + ); + } + + Widget _prices(PersonalizationTheme theme) { + final colors = theme.colors; + final (amount, currency) = PersonalizationStoryPrice.splitCurrency( + widget.price, + ); + final old = widget.oldPrice; + + Widget line(Widget amountText, String currencyText, Color color) => + FittedBox( + fit: BoxFit.scaleDown, + alignment: AlignmentDirectional.centerStart, + child: Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + amountText, + if (currencyText.isNotEmpty) ...[ + const SizedBox(width: 4), + Text( + currencyText, + style: _style(theme, 14, 16, FontWeight.w400, color), + ), + ], + ], + ), + ); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if ((old ?? '').isNotEmpty) + Opacity( + opacity: 0.5, + child: Builder( + builder: (context) { + final (oldAmount, oldCurrency) = + PersonalizationStoryPrice.splitCurrency(old!); + return line( + Text( + oldAmount, + style: _style( + theme, + 14, + 16, + FontWeight.w600, + colors.textDarkSecondary, + ).copyWith(decoration: TextDecoration.lineThrough), + ), + oldCurrency, + colors.textDarkSecondary, + ); + }, + ), + ), + line( + Text( + amount, + style: _style( + theme, + 24, + 28, + FontWeight.w600, + colors.textDarkPrimary, + ), + ), + currency, + colors.textDarkPrimary, + ), + ], + ); + } + + Widget _promo(BuildContext context, PersonalizationTheme theme) { + final colors = theme.colors; + final block = DecoratedBox( + decoration: BoxDecoration( + color: colors.textDarkPrimary, + borderRadius: const BorderRadius.horizontal( + right: Radius.circular(_radius), + ), + ), + child: Stack( + fit: StackFit.expand, + children: [ + Padding( + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + widget.promoCaption, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: _style( + theme, + 14, + 20, + FontWeight.w600, + colors.textLightSecondary, + ), + ), + FittedBox( + fit: BoxFit.scaleDown, + child: Text( + _code, + maxLines: 1, + style: _style( + theme, + 24, + 28, + FontWeight.w600, + colors.textLightPrimary, + ), + ), + ), + ], + ), + ), + Positioned( + top: 4, + right: 4, + child: SizedBox.square( + dimension: 24, + child: widget.iconBuilder?.call( + context, + PersonalizationIcons.copy, + 24, + colors.textLightHint, + ), + ), + ), + ], + ), + ); + + return Semantics( + button: true, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTapDown: (_) => setState(() => _pressed = true), + onTapUp: (_) => setState(() => _pressed = false), + onTapCancel: () => setState(() => _pressed = false), + onTap: _copy, + child: AnimatedScale( + scale: _pressed ? PersonalizationStoryPrice.pressedScale : 1, + duration: const Duration(milliseconds: 120), + child: block, + ), + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_story_progress.dart b/lib/src/ui/components/personalization_story_progress.dart new file mode 100644 index 0000000..557987f --- /dev/null +++ b/lib/src/ui/components/personalization_story_progress.dart @@ -0,0 +1,65 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Прогресс сторис: по отрезку на слайд. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), шапка Navigation/Story. +/// +/// [count] отрезков равной ширины, высота 2, шаг 2, скругление 1. Дорожка — Line/Generic, +/// заливка — Text/Secondary. Отрезки до [current] залиты целиком, текущий — на +/// [progress] (0…1), после него — пустые. +class PersonalizationStoryProgress extends StatelessWidget { + const PersonalizationStoryProgress({ + super.key, + required this.count, + this.current = 0, + this.progress = 0, + }); + + final int count; + + /// Индекс текущего слайда. + final int current; + + /// Сколько показано из текущего слайда, 0…1. + final double progress; + + static const double height = 2; + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + final radius = BorderRadius.circular(1); + return SizedBox( + height: height, + child: Row( + children: [ + for (int i = 0; i < count; i++) ...[ + if (i > 0) const SizedBox(width: 2), + Expanded( + child: ClipRRect( + borderRadius: radius, + child: ColoredBox( + color: colors.lineGeneric, + child: Align( + alignment: AlignmentDirectional.centerStart, + child: FractionallySizedBox( + widthFactor: i < current + ? 1 + : i == current + ? progress.clamp(0, 1).toDouble() + : 0, + heightFactor: 1, + child: ColoredBox(color: colors.textSecondary), + ), + ), + ), + ), + ), + ], + ], + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_story_shimmer.dart b/lib/src/ui/components/personalization_story_shimmer.dart new file mode 100644 index 0000000..0c2989e --- /dev/null +++ b/lib/src/ui/components/personalization_story_shimmer.dart @@ -0,0 +1,73 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Переливание заглушек сторис: кольцо и картинка обложки, подпись превью. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), состояние Skeleton у +/// Story/Cover и Story/Preview — градиент чёрный 5% → 30% → 5%. Здесь он идёт от +/// Text/Primary, а не от сырого чёрного: в тёмной схеме чёрная заглушка пропала бы на +/// фоне, а белая с той же прозрачностью читается так же, как чёрная на светлом. +/// +/// Градиент проезжает по заглушке слева направо за [period]; [builder] получает его на +/// каждом кадре и сам решает, чем залить — фоном или шейдером кисти. +/// +/// Внутренняя деталь обложки и превью: из кита не экспортируется. +class PersonalizationStoryShimmer extends StatefulWidget { + const PersonalizationStoryShimmer({ + super.key, + required this.builder, + this.period = const Duration(milliseconds: 1200), + }); + + final Widget Function(BuildContext context, Gradient gradient) builder; + final Duration period; + + @override + State createState() => + _PersonalizationStoryShimmerState(); +} + +class _PersonalizationStoryShimmerState + extends State + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: widget.period, + )..repeat(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final base = PersonalizationTheme.of(context).colors.textPrimary; + final faint = base.withValues(alpha: 0.05); + final strong = base.withValues(alpha: 0.30); + return AnimatedBuilder( + animation: _controller, + builder: (context, _) => widget.builder( + context, + LinearGradient( + colors: [faint, strong, faint], + // Полоса шириной в заглушку въезжает слева и уходит вправо. + transform: _Slide(_controller.value * 2 - 1), + ), + ), + ); + } +} + +/// Сдвиг градиента по горизонтали в долях ширины заглушки. +class _Slide extends GradientTransform { + const _Slide(this.fraction); + + final double fraction; + + @override + Matrix4 transform(Rect bounds, {TextDirection? textDirection}) => + Matrix4.translationValues(bounds.width * fraction, 0, 0); +} diff --git a/lib/src/ui/components/personalization_story_sound_button.dart b/lib/src/ui/components/personalization_story_sound_button.dart new file mode 100644 index 0000000..ac77e2a --- /dev/null +++ b/lib/src/ui/components/personalization_story_sound_button.dart @@ -0,0 +1,63 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_icons.dart'; +import '../personalization_theme.dart'; + +/// Кнопка звука видео-слайда: динамик или перечёркнутый динамик. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), слайды с видео — +/// иконки speaker / speaker-off 32 цвета Text/Secondary в левом нижнем углу. +class PersonalizationStorySoundButton extends StatelessWidget { + const PersonalizationStorySoundButton({ + super.key, + required this.muted, + this.onPressed, + this.soundOnLabel = 'Sound on', + this.soundOffLabel = 'Sound off', + this.iconBuilder, + }); + + /// Звук выключен: показывается перечёркнутый динамик. + final bool muted; + final VoidCallback? onPressed; + + /// Подписи для скринридера — текущее состояние звука: без звука — [soundOffLabel], + /// со звуком — [soundOnLabel]. Сама кнопка — переключатель: включён, когда звук есть. + final String soundOnLabel; + final String soundOffLabel; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + static const double size = 32; + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + return Semantics( + button: true, + toggled: !muted, + label: muted ? soundOffLabel : soundOnLabel, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onPressed, + child: SizedBox.square( + dimension: size, + child: iconBuilder?.call( + context, + muted + ? PersonalizationIcons.speakerOff + : PersonalizationIcons.speaker, + size, + colors.textSecondary, + ), + ), + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_story_text_block.dart b/lib/src/ui/components/personalization_story_text_block.dart new file mode 100644 index 0000000..5e6e047 --- /dev/null +++ b/lib/src/ui/components/personalization_story_text_block.dart @@ -0,0 +1,134 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Кегль текстового блока сторис: заготовки макета для текста хоста. +enum PersonalizationStoryTextSize { + /// Regular 48/48. + large, + + /// Regular 30/36. + medium, + + /// Regular 20/24. + small, +} + +/// Текстовый блок на слайде сторис. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), компонент Text Block, +/// секция «Текстовый блок». +/// +/// Два вида. Сплошной — когда у [background] есть непрозрачность: скругление 12, поля +/// 12/16 у кегля больше 30 (Large) и 8/16 у остальных (Medium, Small), фон — цвет +/// сервера со своей прозрачностью. Прозрачный — без полей и фона: текст прямо на картинке слайда. +/// +/// Кегль, интерлиньяж, цвет, выключка, жирность и курсив приходят с элементом; для текста +/// хоста есть заготовки [size]. Кегль задан, а интерлиньяж нет — берётся заготовка для +/// этого кегля ([presetLineHeight]), а не собственный шрифта. Цвет по умолчанию — +/// Text/Light Primary на сплошном фоне и Text/Primary на прозрачном. +class PersonalizationStoryTextBlock extends StatelessWidget { + const PersonalizationStoryTextBlock({ + super.key, + required this.text, + this.size = PersonalizationStoryTextSize.medium, + this.fontSize, + this.lineHeight, + this.color, + this.background, + this.textAlign = TextAlign.start, + this.bold = false, + this.italic = false, + this.fontFamily, + this.fontFamilyFallback, + }); + + final String text; + + /// Заготовка кегля и интерлиньяжа; [fontSize] и [lineHeight] её перекрывают. + final PersonalizationStoryTextSize size; + final double? fontSize; + + /// Интерлиньяж в долях кегля, как `TextStyle.height`. + final double? lineHeight; + + /// Цвет текста; `null` — по виду блока. + final Color? color; + + /// Фон блока вместе с прозрачностью; `null` или прозрачный — блок без рамки. + final Color? background; + final TextAlign textAlign; + final bool bold; + final bool italic; + + /// Семейство шрифта элемента (serif, monospace); `null` — шрифт темы. + final String? fontFamily; + final List? fontFamilyFallback; + + /// Блок со сплошным фоном: у фона есть непрозрачность. + bool get solid => background != null && background!.a > 0; + + /// Интерлиньяж заготовки для кегля [fontSize], в долях кегля: берётся ближайшая по + /// кеглю заготовка — Large 48/48 (×1), Medium 30/36 и Small 20/24 (×1,2); поровну — + /// Large. Высота строки — кегль × доля, округлённая до целого. + static double presetLineHeight(double fontSize) { + if (fontSize <= 0) return 1.2; + // Large первой: при равном расстоянии остаётся она. + const presets = <(double, double)>[(48, 1), (30, 1.2), (20, 1.2)]; + var nearest = presets.first; + for (final preset in presets) { + if ((fontSize - preset.$1).abs() < (fontSize - nearest.$1).abs()) { + nearest = preset; + } + } + return (fontSize * nearest.$2).roundToDouble() / fontSize; + } + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final (presetSize, presetHeight) = switch (size) { + PersonalizationStoryTextSize.large => (48.0, 48.0), + PersonalizationStoryTextSize.medium => (30.0, 36.0), + PersonalizationStoryTextSize.small => (20.0, 24.0), + }; + final effectiveSize = fontSize ?? presetSize; + final weight = bold ? FontWeight.w600 : FontWeight.w400; + + final label = Text( + text, + textAlign: textAlign, + style: TextStyle( + fontSize: effectiveSize, + height: + lineHeight ?? + (fontSize == null + ? presetHeight / presetSize + : presetLineHeight(effectiveSize)), + fontWeight: weight, + fontStyle: italic ? FontStyle.italic : FontStyle.normal, + letterSpacing: 0, + fontFamily: fontFamily ?? theme.fontFamily.familyFor(weight), + fontFamilyFallback: fontFamilyFallback, + package: fontFamily == null ? theme.fontFamily.package : null, + color: color ?? (solid ? colors.textLightPrimary : colors.textPrimary), + ), + ); + + if (!solid) return label; + return DecoratedBox( + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(12), + ), + child: Padding( + padding: EdgeInsets.symmetric( + vertical: effectiveSize > 30 ? 12 : 8, + horizontal: 16, + ), + child: label, + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_story_timer.dart b/lib/src/ui/components/personalization_story_timer.dart new file mode 100644 index 0000000..cccc808 --- /dev/null +++ b/lib/src/ui/components/personalization_story_timer.dart @@ -0,0 +1,197 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Вид таймера: одной плашкой или по плашке на единицу. +enum PersonalizationStoryTimerView { merged, separate } + +/// Обратный отсчёт до [endTime]: дни, часы, минуты, секунды. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), компонент Timer на +/// слайдах Action. +/// +/// Каждая единица — число SemiBold 36 Text/Primary и подпись Regular 20 Text/Secondary с +/// шагом 2 по базовой линии. merged — одна плашка со скруглением 12, полями 8/12 и шагом +/// 12 между единицами, заливка Neutral/Neutral 100; separate — четыре плашки со +/// скруглением 8, полями 8/12 и шагом 8, каждая тянется на равную долю ширины. Часы, +/// минуты и секунды — двумя цифрами. +/// +/// Тикает раз в секунду и останавливается на нуле, тогда же зовёт [onFinished]. В данных +/// сторис таймера нет: время конца даёт хост. +class PersonalizationStoryTimer extends StatefulWidget { + const PersonalizationStoryTimer({ + super.key, + required this.endTime, + this.view = PersonalizationStoryTimerView.merged, + this.daysLabel = 'd', + this.hoursLabel = 'h', + this.minutesLabel = 'm', + this.secondsLabel = 's', + this.onFinished, + }); + + final DateTime endTime; + final PersonalizationStoryTimerView view; + final String daysLabel; + final String hoursLabel; + final String minutesLabel; + final String secondsLabel; + + /// Отсчёт дошёл до нуля. + final VoidCallback? onFinished; + + /// Остаток, разложенный на единицы: `(дни, часы, минуты, секунды)` строками, как их + /// показывает таймер. Отрицательный остаток — нули. + static (String, String, String, String) format(Duration remaining) { + final total = remaining.isNegative ? 0 : remaining.inSeconds; + String two(int value) => value.toString().padLeft(2, '0'); + return ( + '${total ~/ Duration.secondsPerDay}', + two(total % Duration.secondsPerDay ~/ Duration.secondsPerHour), + two(total % Duration.secondsPerHour ~/ Duration.secondsPerMinute), + two(total % Duration.secondsPerMinute), + ); + } + + @override + State createState() => + _PersonalizationStoryTimerState(); +} + +class _PersonalizationStoryTimerState extends State { + Timer? _ticker; + Duration _remaining = Duration.zero; + + @override + void initState() { + super.initState(); + _start(); + } + + @override + void didUpdateWidget(PersonalizationStoryTimer oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.endTime != widget.endTime) _start(); + } + + @override + void dispose() { + _ticker?.cancel(); + super.dispose(); + } + + void _start() { + _ticker?.cancel(); + _remaining = _left(); + if (_remaining <= Duration.zero) return; + _ticker = Timer.periodic(const Duration(seconds: 1), (_) => _tick()); + } + + Duration _left() { + final left = widget.endTime.difference(DateTime.now()); + return left.isNegative ? Duration.zero : left; + } + + void _tick() { + final left = _left(); + setState(() => _remaining = left); + if (left <= Duration.zero) { + _ticker?.cancel(); + _ticker = null; + widget.onFinished?.call(); + } + } + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final (days, hours, minutes, seconds) = PersonalizationStoryTimer.format( + _remaining, + ); + + TextStyle style(double size, double height, FontWeight weight, Color c) => + TextStyle( + fontSize: size, + height: height / size, + fontWeight: weight, + letterSpacing: 0, + fontFamily: theme.fontFamily.familyFor(weight), + package: theme.fontFamily.package, + color: c, + ); + + Widget unit(String value, String label) => Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text(value, style: style(36, 44, FontWeight.w600, colors.textPrimary)), + const SizedBox(width: 2), + Text( + label, + style: style(20, 28, FontWeight.w400, colors.textSecondary), + ), + ], + ); + + final units = [ + unit(days, widget.daysLabel), + unit(hours, widget.hoursLabel), + unit(minutes, widget.minutesLabel), + unit(seconds, widget.secondsLabel), + ]; + + const padding = EdgeInsets.symmetric(vertical: 8, horizontal: 12); + switch (widget.view) { + case PersonalizationStoryTimerView.merged: + return Container( + padding: padding, + decoration: BoxDecoration( + color: colors.neutral100, + borderRadius: BorderRadius.circular(12), + ), + child: _fit( + Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + for (int i = 0; i < units.length; i++) ...[ + if (i > 0) const SizedBox(width: 12), + units[i], + ], + ], + ), + ), + ); + case PersonalizationStoryTimerView.separate: + return Row( + children: [ + for (int i = 0; i < units.length; i++) ...[ + if (i > 0) const SizedBox(width: 8), + Expanded( + child: Container( + padding: padding, + decoration: BoxDecoration( + color: colors.neutral100, + borderRadius: BorderRadius.circular(8), + ), + child: _fit(units[i]), + ), + ), + ], + ], + ); + } + } + + // По центру плашки; не влезает по ширине — ужимается целиком, а не переносится. Высота + // по содержимому: FittedBox без Center растянул бы плашку по пропорции. + Widget _fit(Widget child) => Center( + heightFactor: 1, + child: FittedBox(fit: BoxFit.scaleDown, child: child), + ); +} diff --git a/lib/src/ui/components/personalization_story_used_products.dart b/lib/src/ui/components/personalization_story_used_products.dart new file mode 100644 index 0000000..4a861e3 --- /dev/null +++ b/lib/src/ui/components/personalization_story_used_products.dart @@ -0,0 +1,133 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_icons.dart'; +import '../personalization_theme.dart'; +import 'personalization_button.dart'; +import 'personalization_product.dart'; +import 'personalization_products_list.dart'; + +/// Товары со слайда сторис: кнопка-переключатель внизу и карусель над ней. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), слайды Slide с товарами +/// (свёрнуто и развёрнуто). +/// +/// Свёрнуто — строка высотой 64 с полями 16, по центру пилюля: кнопка SM Secondary со +/// скруглением Rounded, подпись [showText] (SemiBold 14/24) и иконка angle-up. Развёрнуто — +/// лист Background/Card: карусель кита (карточки 220, поля 16/0/16/16, шаг 16) и та же +/// строка с подписью [hideText] и иконкой angle-down. В начале строки — необязательный +/// [leading]: во вьюере это кнопка звука видео. +/// +/// Раскрытие ведёт сам виджет, начиная с [initiallyExpanded], либо хост — через +/// [expanded]; [onExpandedChanged] сообщает о нажатии на переключатель. Вьюер ведёт +/// раскрытие сам: шторка ставит слайд на паузу, закрывается тапом мимо неё и сбрасывается +/// при смене слайда. +class PersonalizationStoryUsedProducts extends StatefulWidget { + const PersonalizationStoryUsedProducts({ + super.key, + required this.products, + this.showText = 'Used products', + this.hideText = 'Hide products', + this.initiallyExpanded = false, + this.expanded, + this.onExpandedChanged, + this.onProductTap, + this.leading, + this.iconBuilder, + }); + + final List products; + + /// Подпись свёрнутого переключателя. + final String showText; + + /// Подпись развёрнутого переключателя. + final String hideText; + final bool initiallyExpanded; + + /// Раскрытие от хоста; `null` — виджет ведёт его сам. + final bool? expanded; + + /// Переключатель нажали: новое раскрытие. + final ValueChanged? onExpandedChanged; + + /// Нажатие на карточку — открыть товар. + final ValueChanged? onProductTap; + + /// Виджет в начале строки переключателя. + final Widget? leading; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + State createState() => + _PersonalizationStoryUsedProductsState(); +} + +class _PersonalizationStoryUsedProductsState + extends State { + late bool _own = widget.initiallyExpanded; + + bool get _expanded => widget.expanded ?? _own; + + void _toggle() { + final next = !_expanded; + if (widget.expanded == null) setState(() => _own = next); + widget.onExpandedChanged?.call(next); + } + + @override + Widget build(BuildContext context) { + final colors = PersonalizationTheme.of(context).colors; + final row = SizedBox( + height: 64, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Stack( + alignment: Alignment.center, + children: [ + if (widget.leading != null) + Align( + alignment: AlignmentDirectional.centerStart, + child: widget.leading, + ), + PersonalizationButton( + label: _expanded ? widget.hideText : widget.showText, + size: PersonalizationButtonSize.sm, + view: PersonalizationButtonView.secondary, + rounded: true, + iconEnd: _expanded + ? PersonalizationIcons.angleDown + : PersonalizationIcons.angleUp, + iconBuilder: widget.iconBuilder, + onPressed: _toggle, + ), + ], + ), + ), + ); + + if (!_expanded) return row; + return ColoredBox( + color: colors.backgroundCard, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + PersonalizationProductsList( + products: widget.products, + carouselPadding: const EdgeInsets.fromLTRB(16, 16, 0, 16), + onProductTap: widget.onProductTap, + iconBuilder: widget.iconBuilder, + ), + row, + ], + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_suggestion_row.dart b/lib/src/ui/components/personalization_suggestion_row.dart new file mode 100644 index 0000000..cc9f6dc --- /dev/null +++ b/lib/src/ui/components/personalization_suggestion_row.dart @@ -0,0 +1,149 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_icons.dart'; +import '../personalization_theme.dart'; + +/// Вид строки подсказки. +enum PersonalizationSuggestionKind { product, category } + +/// Строка подсказки поиска: товар или категория. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Card — Product (151:4003) и Category +/// (151:4011), у обоих варианты Image и Text. Строка с картинкой 40x40 и двумя +/// строками текста (у товара цена, у категории родительская категория), либо одна +/// строка текста. У категории справа шеврон. Шаг между картинкой и текстом 10 — +/// значения нет в шкале отступов, взято из макета как есть. +/// +/// [highlight] выделяет совпадение с запросом полужирным, как в макете подсказок. +class PersonalizationSuggestionRow extends StatelessWidget { + const PersonalizationSuggestionRow({ + super.key, + this.kind = PersonalizationSuggestionKind.product, + required this.title, + this.subtitle, + this.image, + this.showImage = false, + this.highlight, + this.onTap, + this.iconBuilder, + }); + + final PersonalizationSuggestionKind kind; + final String title; + + /// Цена у товара, родительская категория у категории. Видна только с картинкой. + final String? subtitle; + final ImageProvider? image; + final bool showImage; + + /// Подстрока запроса, которую надо выделить в [title]. + final String? highlight; + final VoidCallback? onTap; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final category = kind == PersonalizationSuggestionKind.category; + + TextStyle style(FontWeight weight, Color color) => TextStyle( + fontFamily: theme.fontFamily.familyFor(weight), + package: theme.fontFamily.package, + fontSize: 14, + height: 20 / 14, + letterSpacing: 0.05, + fontWeight: weight, + color: color, + ); + final regular = style(FontWeight.w400, colors.textPrimary); + final bold = style(FontWeight.w600, colors.textPrimary); + + return GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: Row( + crossAxisAlignment: category + ? CrossAxisAlignment.center + : CrossAxisAlignment.start, + children: [ + if (showImage) ...[ + SizedBox( + width: 40, + height: 40, + child: ColoredBox( + color: colors.neutral50, + child: image == null + ? null + : Image(image: image!, fit: BoxFit.cover), + ), + ), + const SizedBox(width: 10), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text.rich( + _highlighted(regular, bold), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + if (showImage && subtitle != null && subtitle!.isNotEmpty) + // У товара это цена полужирным, у категории — родитель серым. + Text( + subtitle!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: category + ? style(FontWeight.w400, colors.textHint) + : bold, + ), + ], + ), + ), + if (category) ...[ + const SizedBox(width: 10), + SizedBox( + width: 24, + height: 24, + child: iconBuilder?.call( + context, + PersonalizationIcons.angleLargeRight, + 24, + colors.textHint, + ), + ), + ], + ], + ), + ); + } + + TextSpan _highlighted(TextStyle regular, TextStyle bold) { + final query = highlight ?? ''; + final index = query.isEmpty + ? -1 + : title.toLowerCase().indexOf(query.toLowerCase()); + if (index < 0) return TextSpan(text: title, style: regular); + return TextSpan( + style: regular, + children: [ + TextSpan(text: title.substring(0, index)), + TextSpan( + text: title.substring(index, index + query.length), + style: bold, + ), + TextSpan(text: title.substring(index + query.length)), + ], + ); + } +} diff --git a/lib/src/ui/components/personalization_tag.dart b/lib/src/ui/components/personalization_tag.dart new file mode 100644 index 0000000..e5d11fd --- /dev/null +++ b/lib/src/ui/components/personalization_tag.dart @@ -0,0 +1,90 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; +import '../personalization_icons.dart'; + +/// Вид тега. +enum PersonalizationTagView { primary, secondary } + +/// Тег дизайн-системы. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Tag (243:10993). +/// В макете только размер MD, поэтому размера в API нет. +/// +/// Крестик удаления отдаётся как путь к SVG-ассету в [iconAsset]: пакет не +/// рисует SVG сам, отрисовку выбирает потребитель. +class PersonalizationTag extends StatelessWidget { + const PersonalizationTag({ + super.key, + required this.label, + this.view = PersonalizationTagView.primary, + this.onRemove, + this.removeIconBuilder, + }); + + final String label; + final PersonalizationTagView view; + + /// Задан — тег показывает крестик и зовёт колбэк по нажатию. + final VoidCallback? onRemove; + + /// Как нарисовать крестик 16x16 из [iconAsset]. Не задан — место под иконку + /// остаётся пустым, но отступы сохраняются. + final Widget Function(BuildContext context, String asset)? removeIconBuilder; + + /// Ассет крестика для [removeIconBuilder]. + static const String iconAsset = PersonalizationIcons.cross; + + bool get _removable => onRemove != null; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + final isPrimary = view == PersonalizationTagView.primary; + + return Container( + padding: EdgeInsets.only( + left: 8, + right: _removable ? 4 : 8, + top: 4, + bottom: 4, + ), + decoration: BoxDecoration( + color: isPrimary ? colors.buttonPrimary : colors.buttonSecondary, + borderRadius: BorderRadius.circular( + theme.radius.resolve(PersonalizationRadiusToken.buttonSm), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + label, + style: TextStyle( + fontSize: 12, + height: 16 / 12, + letterSpacing: 0.05, + fontWeight: FontWeight.w400, + fontFamily: theme.fontFamily.familyFor(FontWeight.w400), + package: theme.fontFamily.package, + color: isPrimary ? colors.textLightPrimary : colors.textPrimary, + ), + ), + if (_removable) ...[ + const SizedBox(width: 4), + GestureDetector( + onTap: onRemove, + child: SizedBox( + width: 16, + height: 16, + child: removeIconBuilder?.call(context, iconAsset), + ), + ), + ], + ], + ), + ); + } +} diff --git a/lib/src/ui/components/personalization_title.dart b/lib/src/ui/components/personalization_title.dart new file mode 100644 index 0000000..caccb0f --- /dev/null +++ b/lib/src/ui/components/personalization_title.dart @@ -0,0 +1,51 @@ +import 'package:flutter/widgets.dart'; + +import '../personalization_theme.dart'; + +/// Заголовок блока. +/// +/// Источник: Figma Mobile SDK UI Kit, секция Title (167:3802). +/// Все четыре заголовка на странице — один и тот же ряд «слева иконка, заголовок, +/// справа управление», отличается только содержимое по краям: +/// Recommender block (157:5176) — кнопка «Show all», Category (167:3812) — группа кнопок, +/// Filters (204:8340) — кнопка-крестик, Search results (167:3807) — кнопка «назад» и группа. +/// Поэтому края здесь — произвольные виджеты, а не фиксированные варианты. +class PersonalizationTitle extends StatelessWidget { + const PersonalizationTitle({ + super.key, + required this.title, + this.leading, + this.trailing, + }); + + final String title; + final Widget? leading; + final Widget? trailing; + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + if (leading != null) ...[leading!, const SizedBox(width: 4)], + Expanded( + child: Text( + title, + style: TextStyle( + fontSize: 24, + height: 36 / 24, + letterSpacing: 0, + fontWeight: FontWeight.w600, + fontFamily: theme.fontFamily.familyFor(FontWeight.w600), + package: theme.fontFamily.package, + color: colors.textPrimary, + ), + ), + ), + if (trailing != null) ...[const SizedBox(width: 4), trailing!], + ], + ); + } +} diff --git a/lib/src/ui/components/personalization_toast.dart b/lib/src/ui/components/personalization_toast.dart new file mode 100644 index 0000000..12eee33 --- /dev/null +++ b/lib/src/ui/components/personalization_toast.dart @@ -0,0 +1,219 @@ +import 'dart:async'; + +import 'package:flutter/semantics.dart'; +import 'package:flutter/widgets.dart'; + +import '../personalization_elevation.dart'; +import '../personalization_spacing.dart'; +import '../personalization_theme.dart'; + +/// У какого края экрана показать тост. +enum PersonalizationToastPosition { top, bottom } + +/// Тост: короткое сообщение-«пилюля» поверх экрана. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Components, секция Toast +/// (367:16179), компонент 367:16178. На странице Stories он же во фреймах +/// 367:16063 (снизу, «Copied») и 367:16106 (сверху, «Code copied to clipboard»). +/// +/// Скругление — радиус Toast (999, то есть половина высоты), заливка +/// Background/Float, тень Elevation 2 цветом Shadow/Heavy темы. Поля 16 по +/// вертикали и 20 по горизонтали, текст 18/18 Medium по центру — однострочный +/// тост высотой 50. В макете текст залит сырым #000 без переменной, здесь +/// Text/Primary, чтобы тост работал и в тёмной теме. +/// +/// Сам виджет — только пилюля. Показывает её [show]: поверх текущего экрана, по +/// центру, в 16 от края безопасной зоны, с появлением и исчезанием. +class PersonalizationToast extends StatelessWidget { + const PersonalizationToast({super.key, required this.text}); + + final String text; + + /// Появление и исчезание. + static const Duration fadeDuration = Duration(milliseconds: 200); + + static _ShownToast? _current; + + /// Показывает тост поверх текущего экрана и через [duration] убирает. + /// + /// Кладётся в корневой [Overlay]: тост относится ко всему экрану, а не к + /// вложенному навигатору. По центру, в 16 от края безопасной зоны; снизу — ещё + /// и над клавиатурой, иначе она его закроет. Ширина — не больше экрана без + /// 16 с каждой стороны, длинный текст переносится. + /// + /// Новый вызов заменяет тост, который ещё на экране, — стопкой они не + /// копятся. Касания тост не перехватывает: всё под ним нажимается как + /// обычно. Скринридеру текст объявляется. + static void show( + BuildContext context, + String text, { + PersonalizationToastPosition position = PersonalizationToastPosition.bottom, + Duration duration = const Duration(milliseconds: 2000), + }) { + final overlay = Overlay.of(context, rootOverlay: true); + _current?.remove(); + + final toast = _ShownToast(); + toast.entry = OverlayEntry( + builder: (context) => _ToastLayer( + text: text, + position: position, + duration: duration, + onHidden: toast.remove, + ), + ); + _current = toast; + overlay.insert(toast.entry!); + _announce(context, text); + } + + // Где платформа умеет объявления (iOS, веб), текст объявляется явно. На + // Android объявления устарели — там тост помечен живой областью, и TalkBack + // зачитывает его сам (см. [_ToastLayer]). + static void _announce(BuildContext context, String text) { + if (!(MediaQuery.maybeSupportsAnnounceOf(context) ?? false)) return; + final view = View.maybeOf(context); + if (view == null) return; + unawaited( + SemanticsService.sendAnnouncement( + view, + text, + Directionality.maybeOf(context) ?? TextDirection.ltr, + ), + ); + } + + @override + Widget build(BuildContext context) { + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + return DecoratedBox( + decoration: BoxDecoration( + color: colors.backgroundFloat, + borderRadius: BorderRadius.circular(theme.radius.toast), + // Цвет тени из темы: в тёмной схеме Shadow/Heavy плотнее. + boxShadow: [ + for (final shadow in PersonalizationElevation.e2) + shadow.copyWith(color: colors.shadowHeavy), + ], + ), + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: PersonalizationSpacing.xl, + horizontal: PersonalizationSpacing.xl2, + ), + child: Text( + text, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 18, + height: 1, // 18 / 18 + fontWeight: FontWeight.w500, + letterSpacing: 0, + fontFamily: theme.fontFamily.familyFor(FontWeight.w500), + package: theme.fontFamily.package, + color: colors.textPrimary, + ), + ), + ), + ); + } +} + +/// Показанный тост: его запись в оверлее. Убирается один раз — по окончании +/// исчезания или когда его сменяет следующий. +class _ShownToast { + OverlayEntry? entry; + + void remove() { + final shown = entry; + if (shown == null) return; + entry = null; + if (identical(PersonalizationToast._current, this)) { + PersonalizationToast._current = null; + } + shown + ..remove() + ..dispose(); + } +} + +/// Слой тоста в оверлее: раскладка по краю экрана, появление, таймер, исчезание. +class _ToastLayer extends StatefulWidget { + const _ToastLayer({ + required this.text, + required this.position, + required this.duration, + required this.onHidden, + }); + + final String text; + final PersonalizationToastPosition position; + final Duration duration; + final VoidCallback onHidden; + + @override + State<_ToastLayer> createState() => _ToastLayerState(); +} + +class _ToastLayerState extends State<_ToastLayer> + with SingleTickerProviderStateMixin { + late final AnimationController _opacity; + Timer? _timer; + + @override + void initState() { + super.initState(); + _opacity = AnimationController( + vsync: this, + duration: PersonalizationToast.fadeDuration, + )..forward(); + _timer = Timer(widget.duration, _hide); + } + + // Будущее обратной анимации завершается только если она доиграла: сменённый + // тост убирается сразу, и второй раз onHidden не придёт. + void _hide() => _opacity.reverse().then((_) => widget.onHidden()); + + @override + void dispose() { + _timer?.cancel(); + _opacity.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final safe = MediaQuery.paddingOf(context); + final keyboard = MediaQuery.viewInsetsOf(context).bottom; + final top = widget.position == PersonalizationToastPosition.top; + const edge = PersonalizationSpacing.xl; + + return IgnorePointer( + child: Align( + alignment: top ? Alignment.topCenter : Alignment.bottomCenter, + child: Padding( + padding: EdgeInsets.fromLTRB( + safe.left + edge, + top ? safe.top + edge : 0, + safe.right + edge, + top ? 0 : safe.bottom + keyboard + edge, + ), + child: FadeTransition( + opacity: _opacity, + child: Semantics( + container: true, + liveRegion: !MediaQuery.supportsAnnounceOf(context), + // В корневом оверлее нет Material, и Text взял бы аварийный стиль + // приложения — моноширинный с жёлтым подчёркиванием. + child: DefaultTextStyle( + style: const TextStyle(), + child: PersonalizationToast(text: widget.text), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/src/ui/personalization_colors.dart b/lib/src/ui/personalization_colors.dart new file mode 100644 index 0000000..f008be2 --- /dev/null +++ b/lib/src/ui/personalization_colors.dart @@ -0,0 +1,424 @@ +import 'package:flutter/material.dart'; + +import 'personalization_theme.dart'; + +/// Цвета дизайн-системы. +/// +/// Figma Mobile SDK UI Kit (SSwS49L1fG1psWA7xbakV6), коллекция переменных Color, +/// режимы Light и Dark. Сверено 2026-09-23. +/// +/// Набор цветов внутри [PersonalizationTheme]: подключается не сам по себе, +/// а полем темы, и читается через [of] или `PersonalizationTheme.of(context).colors`. +@immutable +class PersonalizationColors { + final Color brandPrimary; + + /// Neutral 50: полупрозрачная ступень, одинаково заметна на любом фоне — заглушки картинок. + final Color neutral50; + + /// Neutral 100: вдвое плотнее Neutral 50 — подложка таймера сторис. + final Color neutral100; + + final Color semanticWarning; + final Color semanticDanger; + + /// Semantic/Info: синий для информационных плашек — фон текстовых блоков сторис. + final Color semanticInfo; + + /// Semantic/Neutral Subtle: приглушённый нейтральный — кольцо просмотренной сторис. + final Color neutralSubtle; + final Color backgroundGeneric; + final Color backgroundCard; + + /// Поверхности поверх карточки. В светлой все три белые, различаются только + /// в тёмной: Card #1A1A1A, Float #262626, Modal #333333. + final Color backgroundFloat; + final Color backgroundModal; + final Color backgroundInput; + final Color backgroundTransparent; + final Color backgroundInputDisabled; + final Color buttonPrimary; + final Color buttonPrimaryFocus; + final Color buttonSecondary; + + /// Secondary поверх тёмного (картинки-фона): белая 5%, как в тёмном режиме файла. + final Color buttonSecondaryOnDark; + final Color buttonSecondaryFocus; + final Color buttonPrimaryDisabled; + final Color buttonSecondaryDisabled; + final Color buttonGhost; + final Color lineBrand; + final Color lineGeneric; + final Color lineGenericSubtle; + final Color lineInput; + final Color lineInputFocus; + final Color textPrimary; + final Color textSecondary; + final Color textHint; + final Color textDarkPrimary; + final Color textDarkSecondary; + final Color textDarkHint; + final Color textLightPrimary; + final Color textLightSecondary; + final Color textLightHint; + final Color textInvertedPrimary; + final Color textInvertedSecondary; + final Color textInvertedHint; + final Color textBrand; + final Color textLink; + final Color textLinkVisited; + + /// Shadow/Heavy: цвет тени вместе с её прозрачностью — 8% в светлой, 50% в тёмной. + final Color shadowHeavy; + + const PersonalizationColors({ + required this.brandPrimary, + required this.neutral50, + required this.neutral100, + required this.semanticWarning, + required this.semanticDanger, + required this.semanticInfo, + required this.neutralSubtle, + required this.backgroundGeneric, + required this.backgroundCard, + required this.backgroundFloat, + required this.backgroundModal, + required this.backgroundInput, + required this.backgroundTransparent, + required this.backgroundInputDisabled, + required this.buttonPrimary, + required this.buttonPrimaryFocus, + required this.buttonSecondary, + required this.buttonSecondaryOnDark, + required this.buttonSecondaryFocus, + required this.buttonPrimaryDisabled, + required this.buttonSecondaryDisabled, + required this.buttonGhost, + required this.lineBrand, + required this.lineGeneric, + required this.lineGenericSubtle, + required this.lineInput, + required this.lineInputFocus, + required this.textPrimary, + required this.textSecondary, + required this.textHint, + required this.textDarkPrimary, + required this.textDarkSecondary, + required this.textDarkHint, + required this.textLightPrimary, + required this.textLightSecondary, + required this.textLightHint, + required this.textInvertedPrimary, + required this.textInvertedSecondary, + required this.textInvertedHint, + required this.textBrand, + required this.textLink, + required this.textLinkVisited, + required this.shadowHeavy, + }); + + static const PersonalizationColors light = PersonalizationColors( + brandPrimary: Color(0xFF007DF2), + neutral50: Color(0x0D000000), + neutral100: Color(0x1A000000), + semanticWarning: Color(0xFFF37A17), + semanticDanger: Color(0xFFE51919), + semanticInfo: Color(0xFF0087E8), + neutralSubtle: Color(0xFFCCCCCC), + backgroundGeneric: Color(0xFFF2F2F2), + backgroundCard: Color(0xFFFFFFFF), + backgroundFloat: Color(0xFFFFFFFF), + backgroundModal: Color(0xFFFFFFFF), + backgroundInput: Color(0xFFF2F2F2), + backgroundTransparent: Color(0x00FFFFFF), + backgroundInputDisabled: Color(0x0D000000), + buttonPrimary: Color(0xFF007DF2), + buttonPrimaryFocus: Color(0xFF004BC0), + buttonSecondary: Color(0x0D000000), + buttonSecondaryOnDark: Color(0x0DFFFFFF), + buttonSecondaryFocus: Color(0x1A000000), + // Brand/Primary с прозрачностью 65%. + buttonPrimaryDisabled: Color(0xA6007DF2), + buttonSecondaryDisabled: Color(0x0D000000), + buttonGhost: Color(0x00FFFFFF), + lineBrand: Color(0xFF007DF2), + lineGeneric: Color(0x33000000), + lineGenericSubtle: Color(0x0D000000), + lineInput: Color(0x33000000), + lineInputFocus: Color(0xFF007DF2), + textPrimary: Color(0xFF000000), + textSecondary: Color(0xB2000000), + textHint: Color(0x66000000), + textDarkPrimary: Color(0xFF000000), + textDarkSecondary: Color(0xB2000000), + textDarkHint: Color(0x66000000), + textLightPrimary: Color(0xFFFFFFFF), + textLightSecondary: Color(0xCCFFFFFF), + textLightHint: Color(0x80FFFFFF), + textInvertedPrimary: Color(0xFFFFFFFF), + textInvertedSecondary: Color(0xCCFFFFFF), + textInvertedHint: Color(0x80FFFFFF), + textBrand: Color(0xFF007DF2), + textLink: Color(0xFF007DF2), + textLinkVisited: Color(0xFF4D00F2), + shadowHeavy: Color(0x14000000), + ); + + static const PersonalizationColors dark = PersonalizationColors( + brandPrimary: Color(0xFF007DF2), + neutral50: Color(0x0DFFFFFF), + neutral100: Color(0x1AFFFFFF), + semanticWarning: Color(0xFFF37A17), + semanticDanger: Color(0xFFE51919), + semanticInfo: Color(0xFF0087E8), + neutralSubtle: Color(0xFF262626), + backgroundGeneric: Color(0xFF0D0D0D), + backgroundCard: Color(0xFF1A1A1A), + backgroundFloat: Color(0xFF262626), + backgroundModal: Color(0xFF333333), + backgroundInput: Color(0xFF0D0D0D), + backgroundTransparent: Color(0x00FFFFFF), + backgroundInputDisabled: Color(0x0DFFFFFF), + buttonPrimary: Color(0xFF007DF2), + buttonPrimaryFocus: Color(0xFF32AFFF), + buttonSecondary: Color(0x0DFFFFFF), + buttonSecondaryOnDark: Color(0x0DFFFFFF), + buttonSecondaryFocus: Color(0x1AFFFFFF), + // Brand/Primary с прозрачностью 65%. + buttonPrimaryDisabled: Color(0xA6007DF2), + buttonSecondaryDisabled: Color(0x0DFFFFFF), + buttonGhost: Color(0x00FFFFFF), + lineBrand: Color(0xFF007DF2), + lineGeneric: Color(0x33FFFFFF), + lineGenericSubtle: Color(0x0DFFFFFF), + lineInput: Color(0x33FFFFFF), + lineInputFocus: Color(0xFF007DF2), + textPrimary: Color(0xFFFFFFFF), + textSecondary: Color(0xCCFFFFFF), + textHint: Color(0x80FFFFFF), + textDarkPrimary: Color(0xFF000000), + textDarkSecondary: Color(0xB2000000), + textDarkHint: Color(0x66000000), + textLightPrimary: Color(0xFFFFFFFF), + textLightSecondary: Color(0xCCFFFFFF), + textLightHint: Color(0x80FFFFFF), + textInvertedPrimary: Color(0xFF000000), + textInvertedSecondary: Color(0xB2000000), + textInvertedHint: Color(0x66000000), + textBrand: Color(0xFF007DF2), + textLink: Color(0xFF007DF2), + textLinkVisited: Color(0xFF4D00F2), + shadowHeavy: Color(0x80000000), + ); + + /// Цвета действующей темы. Расширение не подключено — берётся светлый набор, + /// чтобы компоненты не падали на голой теме. + static PersonalizationColors of(BuildContext context) => + PersonalizationTheme.of(context).colors; + + PersonalizationColors copyWith({ + Color? brandPrimary, + Color? neutral50, + Color? neutral100, + Color? semanticWarning, + Color? semanticDanger, + Color? semanticInfo, + Color? neutralSubtle, + Color? backgroundGeneric, + Color? backgroundCard, + Color? backgroundFloat, + Color? backgroundModal, + Color? backgroundInput, + Color? backgroundTransparent, + Color? backgroundInputDisabled, + Color? buttonPrimary, + Color? buttonPrimaryFocus, + Color? buttonSecondary, + Color? buttonSecondaryOnDark, + Color? buttonSecondaryFocus, + Color? buttonPrimaryDisabled, + Color? buttonSecondaryDisabled, + Color? buttonGhost, + Color? lineBrand, + Color? lineGeneric, + Color? lineGenericSubtle, + Color? lineInput, + Color? lineInputFocus, + Color? textPrimary, + Color? textSecondary, + Color? textHint, + Color? textDarkPrimary, + Color? textDarkSecondary, + Color? textDarkHint, + Color? textLightPrimary, + Color? textLightSecondary, + Color? textLightHint, + Color? textInvertedPrimary, + Color? textInvertedSecondary, + Color? textInvertedHint, + Color? textBrand, + Color? textLink, + Color? textLinkVisited, + Color? shadowHeavy, + }) { + return PersonalizationColors( + brandPrimary: brandPrimary ?? this.brandPrimary, + neutral50: neutral50 ?? this.neutral50, + neutral100: neutral100 ?? this.neutral100, + semanticWarning: semanticWarning ?? this.semanticWarning, + semanticDanger: semanticDanger ?? this.semanticDanger, + semanticInfo: semanticInfo ?? this.semanticInfo, + neutralSubtle: neutralSubtle ?? this.neutralSubtle, + backgroundGeneric: backgroundGeneric ?? this.backgroundGeneric, + backgroundCard: backgroundCard ?? this.backgroundCard, + backgroundFloat: backgroundFloat ?? this.backgroundFloat, + backgroundModal: backgroundModal ?? this.backgroundModal, + backgroundInput: backgroundInput ?? this.backgroundInput, + backgroundTransparent: + backgroundTransparent ?? this.backgroundTransparent, + backgroundInputDisabled: + backgroundInputDisabled ?? this.backgroundInputDisabled, + buttonPrimary: buttonPrimary ?? this.buttonPrimary, + buttonPrimaryFocus: buttonPrimaryFocus ?? this.buttonPrimaryFocus, + buttonSecondary: buttonSecondary ?? this.buttonSecondary, + buttonSecondaryOnDark: + buttonSecondaryOnDark ?? this.buttonSecondaryOnDark, + buttonSecondaryFocus: buttonSecondaryFocus ?? this.buttonSecondaryFocus, + buttonPrimaryDisabled: + buttonPrimaryDisabled ?? this.buttonPrimaryDisabled, + buttonSecondaryDisabled: + buttonSecondaryDisabled ?? this.buttonSecondaryDisabled, + buttonGhost: buttonGhost ?? this.buttonGhost, + lineBrand: lineBrand ?? this.lineBrand, + lineGeneric: lineGeneric ?? this.lineGeneric, + lineGenericSubtle: lineGenericSubtle ?? this.lineGenericSubtle, + lineInput: lineInput ?? this.lineInput, + lineInputFocus: lineInputFocus ?? this.lineInputFocus, + textPrimary: textPrimary ?? this.textPrimary, + textSecondary: textSecondary ?? this.textSecondary, + textHint: textHint ?? this.textHint, + textDarkPrimary: textDarkPrimary ?? this.textDarkPrimary, + textDarkSecondary: textDarkSecondary ?? this.textDarkSecondary, + textDarkHint: textDarkHint ?? this.textDarkHint, + textLightPrimary: textLightPrimary ?? this.textLightPrimary, + textLightSecondary: textLightSecondary ?? this.textLightSecondary, + textLightHint: textLightHint ?? this.textLightHint, + textInvertedPrimary: textInvertedPrimary ?? this.textInvertedPrimary, + textInvertedSecondary: + textInvertedSecondary ?? this.textInvertedSecondary, + textInvertedHint: textInvertedHint ?? this.textInvertedHint, + textBrand: textBrand ?? this.textBrand, + textLink: textLink ?? this.textLink, + textLinkVisited: textLinkVisited ?? this.textLinkVisited, + shadowHeavy: shadowHeavy ?? this.shadowHeavy, + ); + } + + PersonalizationColors lerp(PersonalizationColors other, double t) { + return PersonalizationColors( + brandPrimary: Color.lerp(brandPrimary, other.brandPrimary, t)!, + neutral50: Color.lerp(neutral50, other.neutral50, t)!, + neutral100: Color.lerp(neutral100, other.neutral100, t)!, + semanticWarning: Color.lerp(semanticWarning, other.semanticWarning, t)!, + semanticDanger: Color.lerp(semanticDanger, other.semanticDanger, t)!, + semanticInfo: Color.lerp(semanticInfo, other.semanticInfo, t)!, + neutralSubtle: Color.lerp(neutralSubtle, other.neutralSubtle, t)!, + backgroundGeneric: Color.lerp( + backgroundGeneric, + other.backgroundGeneric, + t, + )!, + backgroundCard: Color.lerp(backgroundCard, other.backgroundCard, t)!, + backgroundFloat: Color.lerp(backgroundFloat, other.backgroundFloat, t)!, + backgroundModal: Color.lerp(backgroundModal, other.backgroundModal, t)!, + backgroundInput: Color.lerp(backgroundInput, other.backgroundInput, t)!, + backgroundTransparent: Color.lerp( + backgroundTransparent, + other.backgroundTransparent, + t, + )!, + backgroundInputDisabled: Color.lerp( + backgroundInputDisabled, + other.backgroundInputDisabled, + t, + )!, + buttonPrimary: Color.lerp(buttonPrimary, other.buttonPrimary, t)!, + buttonPrimaryFocus: Color.lerp( + buttonPrimaryFocus, + other.buttonPrimaryFocus, + t, + )!, + buttonSecondary: Color.lerp(buttonSecondary, other.buttonSecondary, t)!, + buttonSecondaryOnDark: Color.lerp( + buttonSecondaryOnDark, + other.buttonSecondaryOnDark, + t, + )!, + buttonSecondaryFocus: Color.lerp( + buttonSecondaryFocus, + other.buttonSecondaryFocus, + t, + )!, + buttonPrimaryDisabled: Color.lerp( + buttonPrimaryDisabled, + other.buttonPrimaryDisabled, + t, + )!, + buttonSecondaryDisabled: Color.lerp( + buttonSecondaryDisabled, + other.buttonSecondaryDisabled, + t, + )!, + buttonGhost: Color.lerp(buttonGhost, other.buttonGhost, t)!, + lineBrand: Color.lerp(lineBrand, other.lineBrand, t)!, + lineGeneric: Color.lerp(lineGeneric, other.lineGeneric, t)!, + lineGenericSubtle: Color.lerp( + lineGenericSubtle, + other.lineGenericSubtle, + t, + )!, + lineInput: Color.lerp(lineInput, other.lineInput, t)!, + lineInputFocus: Color.lerp(lineInputFocus, other.lineInputFocus, t)!, + textPrimary: Color.lerp(textPrimary, other.textPrimary, t)!, + textSecondary: Color.lerp(textSecondary, other.textSecondary, t)!, + textHint: Color.lerp(textHint, other.textHint, t)!, + textDarkPrimary: Color.lerp(textDarkPrimary, other.textDarkPrimary, t)!, + textDarkSecondary: Color.lerp( + textDarkSecondary, + other.textDarkSecondary, + t, + )!, + textDarkHint: Color.lerp(textDarkHint, other.textDarkHint, t)!, + textLightPrimary: Color.lerp( + textLightPrimary, + other.textLightPrimary, + t, + )!, + textLightSecondary: Color.lerp( + textLightSecondary, + other.textLightSecondary, + t, + )!, + textLightHint: Color.lerp(textLightHint, other.textLightHint, t)!, + textInvertedPrimary: Color.lerp( + textInvertedPrimary, + other.textInvertedPrimary, + t, + )!, + textInvertedSecondary: Color.lerp( + textInvertedSecondary, + other.textInvertedSecondary, + t, + )!, + textInvertedHint: Color.lerp( + textInvertedHint, + other.textInvertedHint, + t, + )!, + textBrand: Color.lerp(textBrand, other.textBrand, t)!, + textLink: Color.lerp(textLink, other.textLink, t)!, + textLinkVisited: Color.lerp(textLinkVisited, other.textLinkVisited, t)!, + shadowHeavy: Color.lerp(shadowHeavy, other.shadowHeavy, t)!, + ); + } +} diff --git a/lib/src/ui/personalization_elevation.dart b/lib/src/ui/personalization_elevation.dart new file mode 100644 index 0000000..1d823bf --- /dev/null +++ b/lib/src/ui/personalization_elevation.dart @@ -0,0 +1,58 @@ +import 'package:flutter/painting.dart'; + +/// Высоты дизайн-системы. +/// +/// Figma Mobile SDK UI Kit (SSwS49L1fG1psWA7xbakV6), стили Elevation 1–3. +/// +/// Единственная платформа, где обе тени макета ложатся без потерь: +/// [BoxShadow] складывается списком. +/// +/// Цвет 0x14 — светлое значение токена Shadow/Heavy. В тёмной схеме он 0x80 +/// ([PersonalizationColors.shadowHeavy]): тени, которая должна следовать схеме, +/// цвет подставляют оттуда через [BoxShadow.copyWith]. +abstract final class PersonalizationElevation { + /// None + static const List none = []; + + /// Elevation 1 + static const List e1 = [ + BoxShadow( + color: Color(0x14000000), // чёрный, 0.08 + offset: Offset(0, 2), + blurRadius: 4, + ), + BoxShadow( + color: Color(0x14000000), // чёрный, 0.08 + offset: Offset(0, 1), + blurRadius: 2, + ), + ]; + + /// Elevation 2 + static const List e2 = [ + BoxShadow( + color: Color(0x14000000), // чёрный, 0.08 + offset: Offset(0, 10), + blurRadius: 10, + ), + BoxShadow( + color: Color(0x14000000), // чёрный, 0.08 + offset: Offset(0, 3), + blurRadius: 6, + ), + ]; + + /// Elevation 3 + static const List e3 = [ + BoxShadow( + color: Color(0x14000000), // чёрный, 0.08 + offset: Offset(0, 23), + blurRadius: 23, + ), + BoxShadow( + color: Color(0x14000000), // чёрный, 0.08 + offset: Offset(0, 6), + blurRadius: 13, + ), + ]; +} diff --git a/lib/src/ui/personalization_icons.dart b/lib/src/ui/personalization_icons.dart new file mode 100644 index 0000000..a197cdf --- /dev/null +++ b/lib/src/ui/personalization_icons.dart @@ -0,0 +1,71 @@ +/// Пути к иконкам дизайн-системы внутри пакета. +/// +/// Источник: Figma Mobile SDK UI Kit (SSwS49L1fG1psWA7xbakV6), +/// страница Icons, секция 157:5185. +/// +/// Ассеты в формате SVG: Flutter не рисует его без сторонней библиотеки, +/// поэтому пакет отдаёт только пути, а отрисовка остаётся за потребителем +/// (например flutter_svg). Зависимостей это не добавляет. +abstract final class PersonalizationIcons { + static const String angleDown = + 'packages/rees46_sdk/assets/icons/angle-down.svg'; + static const String angleLargeRight = + 'packages/rees46_sdk/assets/icons/angle-large-right.svg'; + static const String angleUp = 'packages/rees46_sdk/assets/icons/angle-up.svg'; + static const String arrowLeft = + 'packages/rees46_sdk/assets/icons/arrow-left.svg'; + static const String arrowRotateCw = + 'packages/rees46_sdk/assets/icons/arrow-rotate-cw.svg'; + static const String arrowsUpDown = + 'packages/rees46_sdk/assets/icons/arrows-up-down.svg'; + static const String checkRosetteFill = + 'packages/rees46_sdk/assets/icons/check-rosette-fill.svg'; + static const String copy = 'packages/rees46_sdk/assets/icons/copy.svg'; + static const String crossLarge = + 'packages/rees46_sdk/assets/icons/cross-large.svg'; + static const String cross = 'packages/rees46_sdk/assets/icons/cross.svg'; + static const String equalizerHorizontal = + 'packages/rees46_sdk/assets/icons/equalizer-horizontal.svg'; + static const String grid2x2Fill = + 'packages/rees46_sdk/assets/icons/grid-2x2-fill.svg'; + static const String grid2x2 = 'packages/rees46_sdk/assets/icons/grid-2x2.svg'; + static const String listFill = + 'packages/rees46_sdk/assets/icons/list-fill.svg'; + static const String list = 'packages/rees46_sdk/assets/icons/list.svg'; + static const String magnifier = + 'packages/rees46_sdk/assets/icons/magnifier.svg'; + static const String rosette = 'packages/rees46_sdk/assets/icons/rosette.svg'; + static const String spacingMd = + 'packages/rees46_sdk/assets/icons/spacing-md.svg'; + + /// Звук видео-слайда сторис: включён / выключен. Страница Stories (1:32). + static const String speaker = 'packages/rees46_sdk/assets/icons/speaker.svg'; + static const String speakerOff = + 'packages/rees46_sdk/assets/icons/speaker-off.svg'; + static const String starFill = + 'packages/rees46_sdk/assets/icons/star-fill.svg'; + + static const List all = [ + angleDown, + angleLargeRight, + angleUp, + arrowLeft, + arrowRotateCw, + arrowsUpDown, + checkRosetteFill, + copy, + crossLarge, + cross, + equalizerHorizontal, + grid2x2Fill, + grid2x2, + listFill, + list, + magnifier, + rosette, + spacingMd, + speaker, + speakerOff, + starFill, + ]; +} diff --git a/lib/src/ui/personalization_radius.dart b/lib/src/ui/personalization_radius.dart new file mode 100644 index 0000000..bba013a --- /dev/null +++ b/lib/src/ui/personalization_radius.dart @@ -0,0 +1,55 @@ +/// Радиусы скругления дизайн-системы. +/// +/// Figma Mobile SDK UI Kit (SSwS49L1fG1psWA7xbakV6), коллекция переменных Radius. +/// +/// `rounded` — pill: значение заведомо больше любой стороны. +abstract final class PersonalizationRadius { + /// XS + static const double xs = 2; + + /// SM + static const double sm = 4; + + /// MD + static const double md = 6; + + /// LG + static const double lg = 8; + + /// XL + static const double xl = 10; + + /// 2XL + static const double xl2 = 12; + + /// 3XL + static const double xl3 = 14; + + /// 4XL + static const double xl4 = 16; + + /// 5XL + static const double xl5 = 20; + + /// 6XL + static const double xl6 = 24; + + /// 7XL + static const double xl7 = 32; + + /// Rounded + static const double rounded = 999; + + /// Семантические радиусы из коллекции Radius. К Button LG/MD/SM привязаны Button, + /// Input, Badge, Tag, к Segmented Button — Button Group, к Modal — попап. + /// Дизайнер меняет их отдельно от шкалы, поэтому и здесь они отдельно. + static const double buttonLg = 12; + static const double buttonMd = 10; + static const double buttonSm = 8; + static const double segmentedLg = 10; + static const double segmentedMd = 8; + static const double segmentedSm = 6; + static const double card = 16; + static const double toast = 999; + static const double modal = 24; +} diff --git a/lib/src/ui/personalization_spacing.dart b/lib/src/ui/personalization_spacing.dart new file mode 100644 index 0000000..2e72322 --- /dev/null +++ b/lib/src/ui/personalization_spacing.dart @@ -0,0 +1,65 @@ +/// Отступы дизайн-системы. +/// +/// Figma Mobile SDK UI Kit (SSwS49L1fG1psWA7xbakV6), коллекция переменных Spacings. +/// +/// Шкала независима от типографической: здесь MD вместо Base, ступеней 11 — до 7XL. +abstract final class PersonalizationSpacing { + /// XS + static const double xs = 2; + + /// SM + static const double sm = 4; + + /// MD + static const double md = 8; + + /// LG + static const double lg = 12; + + /// XL + static const double xl = 16; + + /// 2XL + static const double xl2 = 20; + + /// 3XL + static const double xl3 = 24; + + /// 4XL + static const double xl4 = 32; + + /// 5XL + static const double xl5 = 48; + + /// 6XL + static const double xl6 = 56; + + /// 7XL + static const double xl7 = 64; + + // Семантические отступы: поля и зазоры блоков, модалки и полноэкранного окна. + + /// Padding X + static const double paddingX = 16; + + /// Padding Y + static const double paddingY = 16; + + /// Gap X + static const double gapX = 16; + + /// Gap Y + static const double gapY = 16; + + /// Padding Modal + static const double paddingModal = 20; + + /// Gap Modal + static const double gapModal = 20; + + /// Padding Full Screen + static const double paddingFullScreen = 24; + + /// Gap Full Screen + static const double gapFullScreen = 24; +} diff --git a/lib/src/ui/personalization_theme.dart b/lib/src/ui/personalization_theme.dart new file mode 100644 index 0000000..bc45796 --- /dev/null +++ b/lib/src/ui/personalization_theme.dart @@ -0,0 +1,231 @@ +import 'package:flutter/material.dart'; + +import 'personalization_colors.dart'; +import 'personalization_radius.dart'; + +/// Шрифт дизайн-системы: семейства под обычное и усиленное начертание. +/// +/// Inter в SDK не поставляется — по умолчанию используется системный шрифт. +/// Хост может подставить свой, в том числе из другого пакета. +@immutable +class PersonalizationFontFamily { + const PersonalizationFontFamily({ + this.regular, + this.emphasized, + this.package, + }); + + /// Семейство для FontWeight.w400. `null` — системный. + final String? regular; + + /// Семейство для FontWeight.w600. `null` — системный. + final String? emphasized; + + /// Пакет, из которого берутся шрифты, если они лежат не в приложении. + final String? package; + + /// Семейство под вес: только w600 считается усиленным, как в макете. + String? familyFor(FontWeight weight) => + weight == FontWeight.w600 ? emphasized : regular; + + static const PersonalizationFontFamily system = PersonalizationFontFamily(); +} + +/// Ступень шкалы радиусов. Нужна там, где компонент держит метрики в `const` +/// таблице и не может обратиться к теме на уровне файла. +enum PersonalizationRadiusToken { + xs, + sm, + md, + lg, + xl, + xl2, + xl3, + xl4, + xl5, + xl6, + xl7, + rounded, + buttonLg, + buttonMd, + buttonSm, + segmentedLg, + segmentedMd, + segmentedSm, + card, + toast, + modal, +} + +/// Радиусы темы. Значения по умолчанию — шкала из макета. +@immutable +class PersonalizationRadiusScale { + const PersonalizationRadiusScale({ + this.xs = PersonalizationRadius.xs, + this.sm = PersonalizationRadius.sm, + this.md = PersonalizationRadius.md, + this.lg = PersonalizationRadius.lg, + this.xl = PersonalizationRadius.xl, + this.xl2 = PersonalizationRadius.xl2, + this.xl3 = PersonalizationRadius.xl3, + this.xl4 = PersonalizationRadius.xl4, + this.xl5 = PersonalizationRadius.xl5, + this.xl6 = PersonalizationRadius.xl6, + this.xl7 = PersonalizationRadius.xl7, + this.rounded = PersonalizationRadius.rounded, + this.buttonLg = PersonalizationRadius.buttonLg, + this.buttonMd = PersonalizationRadius.buttonMd, + this.buttonSm = PersonalizationRadius.buttonSm, + this.segmentedLg = PersonalizationRadius.segmentedLg, + this.segmentedMd = PersonalizationRadius.segmentedMd, + this.segmentedSm = PersonalizationRadius.segmentedSm, + this.card = PersonalizationRadius.card, + this.toast = PersonalizationRadius.toast, + this.modal = PersonalizationRadius.modal, + }); + + final double xs, sm, md, lg, xl, xl2, xl3, xl4, xl5, xl6, xl7, rounded; + + /// Семантические радиусы, см. [PersonalizationRadius]. + final double buttonLg, + buttonMd, + buttonSm, + segmentedLg, + segmentedMd, + segmentedSm; + final double card, toast, modal; + + /// Значение ступени из действующей темы. + double resolve(PersonalizationRadiusToken token) => switch (token) { + PersonalizationRadiusToken.xs => xs, + PersonalizationRadiusToken.sm => sm, + PersonalizationRadiusToken.md => md, + PersonalizationRadiusToken.lg => lg, + PersonalizationRadiusToken.xl => xl, + PersonalizationRadiusToken.xl2 => xl2, + PersonalizationRadiusToken.xl3 => xl3, + PersonalizationRadiusToken.xl4 => xl4, + PersonalizationRadiusToken.xl5 => xl5, + PersonalizationRadiusToken.xl6 => xl6, + PersonalizationRadiusToken.xl7 => xl7, + PersonalizationRadiusToken.rounded => rounded, + PersonalizationRadiusToken.buttonLg => buttonLg, + PersonalizationRadiusToken.buttonMd => buttonMd, + PersonalizationRadiusToken.buttonSm => buttonSm, + PersonalizationRadiusToken.segmentedLg => segmentedLg, + PersonalizationRadiusToken.segmentedMd => segmentedMd, + PersonalizationRadiusToken.segmentedSm => segmentedSm, + PersonalizationRadiusToken.card => card, + PersonalizationRadiusToken.toast => toast, + PersonalizationRadiusToken.modal => modal, + }; + + PersonalizationRadiusScale lerp(PersonalizationRadiusScale other, double t) => + PersonalizationRadiusScale( + xs: lerpDouble(xs, other.xs, t), + sm: lerpDouble(sm, other.sm, t), + md: lerpDouble(md, other.md, t), + lg: lerpDouble(lg, other.lg, t), + xl: lerpDouble(xl, other.xl, t), + xl2: lerpDouble(xl2, other.xl2, t), + xl3: lerpDouble(xl3, other.xl3, t), + xl4: lerpDouble(xl4, other.xl4, t), + xl5: lerpDouble(xl5, other.xl5, t), + xl6: lerpDouble(xl6, other.xl6, t), + xl7: lerpDouble(xl7, other.xl7, t), + rounded: lerpDouble(rounded, other.rounded, t), + buttonLg: lerpDouble(buttonLg, other.buttonLg, t), + buttonMd: lerpDouble(buttonMd, other.buttonMd, t), + buttonSm: lerpDouble(buttonSm, other.buttonSm, t), + segmentedLg: lerpDouble(segmentedLg, other.segmentedLg, t), + segmentedMd: lerpDouble(segmentedMd, other.segmentedMd, t), + segmentedSm: lerpDouble(segmentedSm, other.segmentedSm, t), + card: lerpDouble(card, other.card, t), + toast: lerpDouble(toast, other.toast, t), + modal: lerpDouble(modal, other.modal, t), + ); + + static double lerpDouble(double a, double b, double t) => a + (b - a) * t; +} + +/// Тема дизайн-системы: то, что хост может подменить под свой бренд. +/// +/// Подключается расширением к теме приложения: +/// +/// ```dart +/// MaterialApp( +/// theme: ThemeData(extensions: >[ +/// PersonalizationTheme.light.copyWith( +/// colors: PersonalizationColors.light.copyWith(brandPrimary: Color(0xFF7C3AED)), +/// fontFamily: PersonalizationFontFamily( +/// regular: 'Inter', emphasized: 'Inter', +/// ), +/// ), +/// ]), +/// darkTheme: ThemeData.dark().copyWith(extensions: >[ +/// PersonalizationTheme.dark, +/// ]), +/// ) +/// ``` +/// +/// Расширение можно переопределить и на поддереве через `Theme(data: ...)`: +/// разным магазинам в одном приложении можно дать разный брендинг. +/// +/// Темизуются цвета, радиусы и шрифт — поверхность брендирования. Отступы, тени +/// и кегли остаются константами: это шкала макета, менять её не предполагается. +@immutable +class PersonalizationTheme extends ThemeExtension { + const PersonalizationTheme({ + required this.colors, + this.radius = const PersonalizationRadiusScale(), + this.fontFamily = PersonalizationFontFamily.system, + }); + + final PersonalizationColors colors; + final PersonalizationRadiusScale radius; + final PersonalizationFontFamily fontFamily; + + static const PersonalizationTheme light = PersonalizationTheme( + colors: PersonalizationColors.light, + ); + + static const PersonalizationTheme dark = PersonalizationTheme( + colors: PersonalizationColors.dark, + ); + + /// Тема из контекста. Расширение не подключено — берётся набор по яркости темы + /// приложения, поэтому компоненты работают и у хоста, которому тема не нужна, и + /// в тёмной схеме не остаются светлыми. + static PersonalizationTheme of(BuildContext context) { + final theme = Theme.of(context); + return theme.extension() ?? + (theme.brightness == Brightness.dark ? dark : light); + } + + @override + PersonalizationTheme copyWith({ + PersonalizationColors? colors, + PersonalizationRadiusScale? radius, + PersonalizationFontFamily? fontFamily, + }) { + return PersonalizationTheme( + colors: colors ?? this.colors, + radius: radius ?? this.radius, + fontFamily: fontFamily ?? this.fontFamily, + ); + } + + @override + PersonalizationTheme lerp( + ThemeExtension? other, + double t, + ) { + if (other is! PersonalizationTheme) return this; + return PersonalizationTheme( + colors: colors.lerp(other.colors, t), + radius: radius.lerp(other.radius, t), + // Шрифт не интерполируется: переключается разом на середине перехода. + fontFamily: t < 0.5 ? fontFamily : other.fontFamily, + ); + } +} diff --git a/lib/src/ui/personalization_typography.dart b/lib/src/ui/personalization_typography.dart new file mode 100644 index 0000000..31ee1ac --- /dev/null +++ b/lib/src/ui/personalization_typography.dart @@ -0,0 +1,142 @@ +import 'package:flutter/widgets.dart'; + +/// Типографика дизайн-системы. +/// +/// Figma Mobile SDK UI Kit (SSwS49L1fG1psWA7xbakV6), страница Typography. +/// Сгенерировано скриптом; правки вносить в источник, не здесь. +/// +/// Inter в SDK не поставляется — `fontFamily` не задан, берётся системный. +/// `height` — отношение интерлиньяжа к кеглю, как того требует [TextStyle]. +abstract final class PersonalizationTypography { + // XS — 12/16 + static const TextStyle xsDefault = TextStyle( + fontSize: 12, + height: 1.3333, // 16 / 12 + fontWeight: FontWeight.w400, + letterSpacing: 0.05, + ); + static const TextStyle xsEmphasized = TextStyle( + fontSize: 12, + height: 1.3333, // 16 / 12 + fontWeight: FontWeight.w600, + letterSpacing: 0.05, + ); + + // SM — 14/20 + static const TextStyle smDefault = TextStyle( + fontSize: 14, + height: 1.4286, // 20 / 14 + fontWeight: FontWeight.w400, + letterSpacing: 0.05, + ); + static const TextStyle smEmphasized = TextStyle( + fontSize: 14, + height: 1.4286, // 20 / 14 + fontWeight: FontWeight.w600, + letterSpacing: 0.05, + ); + + // Base — 16/24 + static const TextStyle baseDefault = TextStyle( + fontSize: 16, + height: 1.5000, // 24 / 16 + fontWeight: FontWeight.w400, + ); + static const TextStyle baseEmphasized = TextStyle( + fontSize: 16, + height: 1.5000, // 24 / 16 + fontWeight: FontWeight.w600, + ); + + // LG — 18/28 + static const TextStyle lgDefault = TextStyle( + fontSize: 18, + height: 1.5556, // 28 / 18 + fontWeight: FontWeight.w400, + ); + static const TextStyle lgEmphasized = TextStyle( + fontSize: 18, + height: 1.5556, // 28 / 18 + fontWeight: FontWeight.w600, + ); + + // XL — 20/32 + static const TextStyle xlDefault = TextStyle( + fontSize: 20, + height: 1.6000, // 32 / 20 + fontWeight: FontWeight.w400, + ); + static const TextStyle xlEmphasized = TextStyle( + fontSize: 20, + height: 1.6000, // 32 / 20 + fontWeight: FontWeight.w600, + ); + + // 2XL — 24/36 + static const TextStyle xl2Default = TextStyle( + fontSize: 24, + height: 1.5000, // 36 / 24 + fontWeight: FontWeight.w400, + ); + static const TextStyle xl2Emphasized = TextStyle( + fontSize: 24, + height: 1.5000, // 36 / 24 + fontWeight: FontWeight.w600, + ); + + // 3XL — 30/40 + static const TextStyle xl3Default = TextStyle( + fontSize: 30, + height: 1.3333, // 40 / 30 + fontWeight: FontWeight.w400, + letterSpacing: -0.5, + ); + static const TextStyle xl3Emphasized = TextStyle( + fontSize: 30, + height: 1.3333, // 40 / 30 + fontWeight: FontWeight.w600, + letterSpacing: -0.5, + ); + + // 4XL — 36/52 + static const TextStyle xl4Default = TextStyle( + fontSize: 36, + height: 1.3333, // 48 / 36 + fontWeight: FontWeight.w400, + letterSpacing: -0.5, + ); + static const TextStyle xl4Emphasized = TextStyle( + fontSize: 36, + height: 1.3333, // 48 / 36 + fontWeight: FontWeight.w600, + letterSpacing: -0.5, + ); + + // 5XL — 48/64 + static const TextStyle xl5Default = TextStyle( + fontSize: 48, + height: 1.1667, // 56 / 48 + fontWeight: FontWeight.w400, + letterSpacing: -0.5, + ); + static const TextStyle xl5Emphasized = TextStyle( + fontSize: 48, + height: 1.1667, // 56 / 48 + fontWeight: FontWeight.w600, + letterSpacing: -0.5, + ); + + // 6XL — 60/72 + static const TextStyle xl6Default = TextStyle( + fontSize: 60, + height: 1.0667, // 64 / 60 + fontWeight: FontWeight.w400, + letterSpacing: -0.5, + ); + static const TextStyle xl6Emphasized = TextStyle( + fontSize: 60, + height: 1.0667, // 64 / 60 + fontWeight: FontWeight.w600, + letterSpacing: -0.5, + ); +} diff --git a/lib/src/ui/personalization_ui.dart b/lib/src/ui/personalization_ui.dart new file mode 100644 index 0000000..ba1442c --- /dev/null +++ b/lib/src/ui/personalization_ui.dart @@ -0,0 +1,81 @@ +/// UI-кит дизайн-системы: токены, тема и все собранные на них компоненты. +/// +/// Намеренно не экспортируется из `package:rees46_sdk/rees46_sdk.dart`. Кит ещё +/// собирается и ничем в SDK не используется, поэтому до релиза, который его +/// выпустит, он остаётся вне публичной поверхности. Пока единственный вход — +/// прямой импорт этого файла; анализатор помечает его как implementation +/// import, и это ожидаемо: +/// +/// ```dart +/// // ignore: implementation_imports +/// import 'package:rees46_sdk/src/ui/personalization_ui.dart'; +/// ``` +/// +/// Перед релизом эти экспорты переезжают в барель пакета, и кит становится +/// обычным публичным API. +library; + +export 'personalization_typography.dart'; +export 'personalization_spacing.dart'; +export 'personalization_radius.dart'; +export 'personalization_elevation.dart'; +export 'personalization_icons.dart'; +export 'personalization_colors.dart'; +export 'personalization_theme.dart'; + +export 'components/personalization_in_app_popup.dart'; +export 'components/personalization_badge.dart'; +export 'components/personalization_tag.dart'; +export 'components/personalization_checkbox.dart'; +export 'components/personalization_checkbox_with_label.dart'; +export 'components/personalization_loader.dart'; +export 'components/personalization_empty_state.dart'; +export 'components/personalization_button.dart'; +export 'components/personalization_button_group.dart'; +export 'components/personalization_input_field.dart'; +export 'components/personalization_title.dart'; +export 'components/personalization_link.dart'; +export 'components/personalization_accordion.dart'; +export 'components/personalization_list_label.dart'; +export 'components/personalization_dots.dart'; +export 'components/personalization_count.dart'; +export 'components/personalization_rating.dart'; +export 'components/personalization_search_results_title.dart'; +export 'components/personalization_product_image.dart'; +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_suggestion_row.dart'; +export 'components/personalization_instant_search.dart'; +export 'components/personalization_filters.dart'; +export 'components/personalization_catalog.dart'; +export 'components/personalization_toast.dart'; +// Кодировщик Code 128 (personalization_code128.dart) не экспортируется — это +// внутренность штрихкода. +export 'components/personalization_barcode.dart'; +export 'components/personalization_loyalty_card.dart'; +// Сторис V2. Заглушка-переливание (personalization_story_shimmer.dart) не +// экспортируется — это внутренность обложки и превью. +export 'components/personalization_story_cover.dart'; +export 'components/personalization_story_preview.dart'; +export 'components/personalization_stories_bar.dart'; +export 'components/personalization_story_progress.dart'; +export 'components/personalization_story_navigation.dart'; +export 'components/personalization_story_sound_button.dart'; +export 'components/personalization_story_price.dart'; +export 'components/personalization_story_timer.dart'; +export 'components/personalization_story_text_block.dart'; +export 'components/personalization_story_used_products.dart'; + +// Виджеты с данными SDK: сами резолвят инстанс по shopId, ходят в поиск и держат состояние. +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/stories_support.dart' show PersonalizationStoryImageProvider; +export 'widgets/personalization_story_viewer.dart'; +export 'widgets/personalization_stories.dart'; diff --git a/lib/src/ui/widgets/personalization_instant_search_field.dart b/lib/src/ui/widgets/personalization_instant_search_field.dart new file mode 100644 index 0000000..e6b7949 --- /dev/null +++ b/lib/src/ui/widgets/personalization_instant_search_field.dart @@ -0,0 +1,372 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import '../../multi_instance/rees46.dart'; +import '../../personalization_sdk.dart'; +import '../../search/search_params.dart'; +import '../../search/search_response.dart'; +import '../../tracking/tracking_models.dart'; +import '../components/personalization_instant_search.dart'; +import 'search_support.dart'; + +/// Мгновенный поиск с данными SDK: поле ввода, недавние запросы, подсказки, категории и +/// товары — виджет сам ходит в `searchInstant` / `searchBlank` и держит состояние. +/// +/// Паттерн InstantSearchField из Figma (страница 1:29): «компонент владеет вводом», +/// источник — `searchInstant(query)`. Визуальный слой — [PersonalizationInstantSearch]. +/// +/// Инстанс SDK: [sdk] явно, иначе [shopId] выбирает магазин при нескольких +/// зарегистрированных; без него берётся единственный (`REES46.getInstance`). Если магазин +/// не зарегистрирован, виджет остаётся пустым и пишет об этом в лог, а не роняет экран. +/// +/// Пока запрос короче [minChars] показывается пустое состояние: история запросов +/// (локальная, по магазину, в SharedPreferences), а из `searchBlank` — товары и +/// популярные категории; популярные фразы (`suggests`) подставляются тегами, только если +/// истории ещё нет. При вводе после [debounce] уходит `searchInstant`: фразы из `queries` +/// — тегами, категории и товары — строками. Ответ на устаревший запрос отбрасывается. +/// +/// Нажатие на товар или категорию запоминает источник `instant_search` в трекинге и +/// отдаёт объект хосту; отправка кладёт фразу в историю и вызывает [onSubmit] — экран +/// полной выдачи открывает хост, событие `search` трекает +/// `PersonalizationSearchResultsScreen`. +class PersonalizationInstantSearchField extends StatefulWidget { + const PersonalizationInstantSearchField({ + super.key, + this.sdk, + this.shopId, + this.debounce = const Duration(milliseconds: 300), + this.minChars = 2, + this.productsLimit = 5, + this.categoriesLimit = 3, + this.suggestionsLimit = 8, + this.recentLimit = 10, + this.recentCollapsed = 5, + this.showRecent = true, + this.showSuggestions = true, + this.showCategories = true, + this.showProducts = true, + this.showImages = true, + this.locations, + this.placeholder, + this.cancelText, + this.recentLabel, + this.clearText, + this.moreText, + this.categoriesLabel, + this.productsLabel, + this.onSubmit, + this.onCancel, + this.onProductTap, + this.onCategoryTap, + this.onError, + this.iconBuilder, + }); + + /// Явный инстанс; иначе резолв по [shopId]. + final PersonalizationSdk? sdk; + + /// Магазин при нескольких зарегистрированных; без него — единственный. + final String? shopId; + + final Duration debounce; + final int minChars; + final int productsLimit; + final int categoriesLimit; + final int suggestionsLimit; + final int recentLimit; + + /// Сколько недавних запросов видно до тега «ещё». + final int recentCollapsed; + + final bool showRecent; + final bool showSuggestions; + final bool showCategories; + final bool showProducts; + final bool showImages; + + /// Список id локаций через запятую. + final String? locations; + + final String? placeholder; + final String? cancelText; + final String? recentLabel; + final String? clearText; + + /// Подпись тега «ещё»; показывается, когда история длиннее [recentCollapsed]. + final String? moreText; + final String? categoriesLabel; + final String? productsLabel; + + final ValueChanged? onSubmit; + final VoidCallback? onCancel; + final ValueChanged? onProductTap; + final ValueChanged? onCategoryTap; + final ValueChanged? onError; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + @override + State createState() => + _PersonalizationInstantSearchFieldState(); +} + +class _PersonalizationInstantSearchFieldState + extends State { + final TextEditingController _controller = TextEditingController(); + PersonalizationSdk? _sdk; + RecentSearches? _recent; + List _recentItems = const []; + bool _recentExpanded = false; + SearchBlankResponse? _blank; + SearchInstantResponse? _instant; + int _seq = 0; + Timer? _debounce; + + @override + void initState() { + super.initState(); + _resolve(); + } + + @override + void didUpdateWidget(PersonalizationInstantSearchField oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.sdk != widget.sdk || oldWidget.shopId != widget.shopId) { + _resolve(); + } + } + + @override + void dispose() { + _debounce?.cancel(); + _controller.dispose(); + super.dispose(); + } + + void _resolve() { + PersonalizationSdk? sdk = widget.sdk; + if (sdk == null) { + try { + sdk = REES46.getInstance(widget.shopId); + } catch (error) { + debugPrint( + 'PersonalizationInstantSearchField: cannot resolve an SDK for ' + 'shopId=${widget.shopId} — $error', + ); + widget.onError?.call(error); + } + } + _sdk = sdk; + if (sdk == null) return; + _recent = RecentSearches( + shopKey: sdk.shopId ?? widget.shopId ?? 'default', + limit: widget.recentLimit, + ); + _recent!.load().then((items) { + if (mounted) setState(() => _recentItems = items); + }); + _loadBlank(sdk); + } + + Future _loadBlank(PersonalizationSdk sdk) async { + try { + final response = await sdk.searchBlank(); + // Пустое состояние не привязано к запросу: пригодится, когда поле очистят. + if (!mounted) return; + setState(() => _blank = response); + } catch (error) { + if (mounted) widget.onError?.call(error); + } + } + + bool get _typing => _controller.text.trim().length >= widget.minChars; + + void _typed(String text) { + _debounce?.cancel(); + if (text.trim().length < widget.minChars) { + _seq++; + setState(() => _instant = null); + return; + } + _debounce = Timer(widget.debounce, () => _runInstant(text.trim())); + } + + Future _runInstant(String text) async { + final sdk = _sdk; + if (sdk == null) return; + final seq = ++_seq; + try { + final response = await sdk.searchInstant( + text, + params: widget.locations == null + ? null + : SearchInstantParams(locations: widget.locations), + ); + if (!mounted || seq != _seq) return; + setState(() => _instant = response); + } catch (error) { + if (mounted && seq == _seq) widget.onError?.call(error); + } + } + + Future _submit(String text) async { + final trimmed = text.trim(); + if (trimmed.isEmpty) return; + _recentExpanded = false; + final recent = _recent; + if (recent != null) { + final items = await recent.add(trimmed); + if (mounted) setState(() => _recentItems = items); + } + widget.onSubmit?.call(trimmed); + } + + void _rememberSource() { + final text = _controller.text.trim(); + if (text.isEmpty) return; + _sdk?.tracking.setSource( + TrackingSource(type: TrackingSourceType.instantSearch, code: text), + ); + } + + @override + Widget build(BuildContext context) { + final typing = _typing; + final blank = _blank; + final instant = _instant; + + final recentItems = !typing && widget.showRecent + ? _recentItems + : const []; + final collapsed = + !_recentExpanded && recentItems.length > widget.recentCollapsed; + final recentShown = collapsed + ? recentItems.take(widget.recentCollapsed).toList() + : recentItems; + + // Популярные фразы сервера заменяют пустую историю. + List suggestions; + if (typing) { + suggestions = widget.showSuggestions + ? (instant?.queries ?? const []) + .map((item) => item.name) + .take(widget.suggestionsLimit) + .toList() + : const []; + } else { + suggestions = widget.showSuggestions && recentItems.isEmpty + ? (blank?.suggests ?? const []) + .map((item) => item.name) + .take(widget.suggestionsLimit) + .toList() + : const []; + } + + final categories = []; + final categoryTargets = {}; + if (widget.showCategories) { + if (typing) { + final all = instant?.categories ?? const []; + for (final category in all.take(widget.categoriesLimit)) { + categories.add( + PersonalizationSuggestion( + id: category.id, + title: category.name, + subtitle: parentName(category, all), + ), + ); + categoryTargets[category.id] = PersonalizationSearchCategory( + id: category.id, + name: category.name, + url: category.url, + ); + } + } else { + final popular = blank?.popularCategories ?? const []; + for (final item in popular.take(widget.categoriesLimit)) { + final id = item.url.isNotEmpty ? item.url : item.name; + categories.add(PersonalizationSuggestion(id: id, title: item.name)); + categoryTargets[id] = PersonalizationSearchCategory( + id: null, + name: item.name, + url: item.url.isEmpty ? null : item.url, + ); + } + } + } + + final products = []; + final productTargets = {}; + if (widget.showProducts) { + final source = typing ? instant?.products : blank?.products; + for (final product in (source ?? const []).take( + widget.productsLimit, + )) { + final card = toCardProduct(product, null); + products.add( + PersonalizationSuggestion( + id: card.id, + title: card.name, + subtitle: card.price, + image: widget.showImages ? card.image : null, + ), + ); + productTargets[card.id] = product; + } + } + + return PersonalizationInstantSearch( + controller: _controller, + placeholder: widget.placeholder, + cancelText: widget.cancelText, + onCancel: widget.onCancel, + onQueryChanged: _typed, + onSubmit: _submit, + recentLabel: widget.recentLabel, + clearText: widget.clearText, + onClearRecent: () => _recent?.clear().then((items) { + if (mounted) setState(() => _recentItems = items); + }), + recentSearches: recentShown, + moreText: collapsed ? widget.moreText : null, + onMoreRecent: () => setState(() => _recentExpanded = true), + onRecentTap: (item) { + _controller.text = item; + _submit(item); + }, + onRecentRemove: (item) => _recent?.remove(item).then((items) { + if (mounted) setState(() => _recentItems = items); + }), + suggestions: suggestions, + onSuggestionTap: (item) { + _controller.text = item; + _submit(item); + }, + categoriesLabel: widget.categoriesLabel, + categories: categories, + onCategoryTap: (suggestion) { + final target = categoryTargets[suggestion.id]; + if (target == null) return; + _rememberSource(); + widget.onCategoryTap?.call(target); + }, + productsLabel: widget.productsLabel, + products: products, + onProductTap: (suggestion) { + final target = productTargets[suggestion.id]; + if (target == null) return; + _rememberSource(); + widget.onProductTap?.call(target); + }, + showImages: widget.showImages, + 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 new file mode 100644 index 0000000..360bb58 --- /dev/null +++ b/lib/src/ui/widgets/personalization_search_results_screen.dart @@ -0,0 +1,698 @@ +import 'package:flutter/widgets.dart'; + +import '../../multi_instance/rees46.dart'; +import '../../personalization_sdk.dart'; +import '../../search/search_params.dart'; +import '../../search/search_response.dart'; +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'; + +/// Значения фильтров, ушедшие в запрос. +@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, + ); +} + +/// Экран полной выдачи с данными SDK: заголовок с числом найденного, плитка ⇄ список, +/// теги применённых фильтров, счётчик, «загрузить ещё» или бесконечная прокрутка, +/// пустое состояние и экран фильтров — виджет сам ходит в `searchFull` и держит состояние. +/// +/// Паттерн SearchResultsScreen из Figma (страница 1:30), источник — `searchFull(query)`. +/// Визуальный слой — [PersonalizationSearchResultsTitle] в заголовке +/// [PersonalizationCatalog]; фильтры — [PersonalizationFilters] поверх выдачи внутри этого +/// же виджета, так что экран занимает весь отведённый ему экран хоста. +/// +/// Инстанс SDK: [sdk] явно, иначе [shopId] или единственный зарегистрированный +/// (`REES46.getInstance`). +/// +/// Фасеты строятся из ответа: диапазон цены (`price_range`), бренды, цвета и размеры +/// (`industrial_filters`) и произвольные фасеты магазина (`filters`), из которых +/// показываются только те, где больше одного значения. Применённые значения идут тегами в +/// заголовок и параметрами в следующий запрос. Заголовок произвольного фасета — его имя +/// через [facetTitle]. +/// +/// Сортировки: кнопка в заголовке отдаёт [onSortTap] хосту (пикер в макете не нарисован), +/// выбранное хост кладёт в [sortBy] / [sortDir]. Каждый новый запрос трекается событием +/// `search`; нажатие на карточку запоминает источник `full_search` и отдаёт товар через +/// [onProductTap], кнопка карточки — через [onProductAction]. +class PersonalizationSearchResultsScreen extends StatefulWidget { + const PersonalizationSearchResultsScreen({ + super.key, + this.sdk, + this.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, + }); + + final PersonalizationSdk? sdk; + final String? shopId; + + /// Поисковая фраза; смена перезапрашивает первую страницу. + 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; + + @override + State createState() => + _PersonalizationSearchResultsScreenState(); +} + +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(); + + @override + void initState() { + super.initState(); + _scroll.addListener(_onScroll); + _resolve(); + } + + @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(); + } + } + + @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(); + } + + String get _text => widget.query.trim(); + + /// Первая страница заново. + 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; + } + 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(), + }, + ); + 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) { + if (_text.isNotEmpty) { + _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; + } + + @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, + ); + + 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, + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/src/ui/widgets/personalization_stories.dart b/lib/src/ui/widgets/personalization_stories.dart new file mode 100644 index 0000000..b853e1f --- /dev/null +++ b/lib/src/ui/widgets/personalization_stories.dart @@ -0,0 +1,546 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import '../../multi_instance/rees46.dart'; +import '../../multi_instance/sdk_exceptions.dart'; +import '../../personalization_sdk.dart'; +import '../../stories/stories_response.dart'; +import '../components/personalization_stories_bar.dart'; +import 'personalization_story_viewer.dart'; +import 'stories_playback.dart'; +import 'stories_seen_store.dart'; +import 'stories_support.dart'; + +/// Программное управление блоком сторис: открыть сторис, пауза, продолжение, перезагрузка. +/// +/// Передаётся в [PersonalizationStories.controller] или в [PersonalizationStories.show]. +/// - [open] и [openStory] до загрузки блока ждут её и открывают сторис после; при уже +/// открытом просмотре листают на эту сторис внутри него. Future завершается, когда +/// просмотр закроют. +/// - [pause] и [resume] действуют только на открытый просмотр, без него ничего не +/// делают; при закрытии просмотра пауза снимается. +class PersonalizationStoriesController { + _PersonalizationStoriesState? _bar; + final ValueNotifier _paused = ValueNotifier(false); + + /// Открытый просмотр; `null` — закрыт. + _StoriesSession? _session; + + /// Открытие, которое ждёт загрузки блока. + _QueuedOpen? _queued; + + /// Открыть сторис номер [index] ленты — со стартового слайда по общим правилам. Блок + /// ещё грузится — откроется после загрузки (новая просьба заменяет прежнюю); просмотр + /// уже открыт — перелистнёт в нём. Нет такой сторис — ничего. + Future open(int index) => _request(index: index); + + /// Открыть сторис с id [storyId] — как [open]; нет такой — ничего. + Future openStory(String storyId) => _request(storyId: storyId); + + /// Остановить открытый просмотр; без него — ничего. + void pause() { + if (_session != null) _paused.value = true; + } + + /// Продолжить после [pause]; без открытого просмотра — ничего. + void resume() { + if (_session != null) _paused.value = false; + } + + /// Заново загрузить блок. + Future reload() => _bar?._load() ?? Future.value(); + + Future _request({int? index, String? storyId}) { + final session = _session; + if (session != null) return session.turn(index: index, storyId: storyId); + final bar = _bar; + if (bar != null && !bar._loading) { + return bar._openStory(index: index, storyId: storyId); + } + final previous = _queued; + final queued = _queued = _QueuedOpen(index, storyId); + previous?.done.complete(); + return queued.done.future; + } + + /// Блок загрузился или не загрузился: отложенное открытие — сейчас. + void _flush() { + final queued = _queued; + if (queued == null) return; + _queued = null; + queued.done.complete( + _request(index: queued.index, storyId: queued.storyId), + ); + } + + /// Блок ушёл из дерева: отложенное открытие не случится. + void _drop() { + final queued = _queued; + _queued = null; + queued?.done.complete(); + } + + _StoriesSession _begin(List stories) => + _session = _StoriesSession(stories); + + void _end(_StoriesSession session) { + session.end(); + if (_session != session) return; + _session = null; + _paused.value = false; + } +} + +/// Открытие сторис, которое ждёт загрузки блока. +class _QueuedOpen { + _QueuedOpen(this.index, this.storyId); + + final int? index; + final String? storyId; + final Completer done = Completer(); +} + +/// Открытый просмотр: его сторис, просьбы перелистнуть и конец. +class _StoriesSession { + _StoriesSession(this.stories); + + final List stories; + + /// Индексы сторис, на которые перелистнуть. Не broadcast: просьба до первой сборки + /// просмотра ждёт его подписки. + final StreamController turns = StreamController(); + final Completer _closed = Completer(); + + /// Перелистнуть на сторис [index] или с id [storyId]; нет такой — ничего. Завершается, + /// когда просмотр закроют. + Future turn({int? index, String? storyId}) { + final target = storyId != null + ? stories.indexWhere((story) => story.id == storyId) + : index ?? -1; + if (target < 0 || target >= stories.length || turns.isClosed) { + return Future.value(); + } + turns.add(target); + return _closed.future; + } + + void end() { + unawaited(turns.close()); + if (!_closed.isCompleted) _closed.complete(); + } +} + +/// Блок сторис с данными SDK: лента превью, по нажатию — полноэкранный просмотр. +/// +/// Паттерн «Блок сторис на странице» из Figma (страница Stories, 1:32), источник — +/// `stories/{code}`. Визуальный слой — [PersonalizationStoriesBar] и +/// [PersonalizationStoryViewer]. Без ленты сторис показывает [show]. +/// +/// Инстанс SDK: [sdk] явно, иначе [shopId] выбирает магазин при нескольких +/// зарегистрированных; без него берётся единственный (`REES46.getInstance`). Магазин ещё +/// не зарегистрирован — виджет ждёт регистрации до 15 с ([registrationTimeout]). +/// +/// Пока блок грузится, в ленте заглушки. Пустой блок — виджет исчезает. Ошибка загрузки, +/// пустой [code], магазин не зарегистрирован за 15 с или неоднозначен, загрузка дольше +/// 15 с — виджет исчезает и зовёт [onError]; вечных заглушек нет. Сторис без слайдов +/// выпадают. +/// +/// Просмотренные слайды хранятся на устройстве по магазину и переживают перезапуск: +/// сторис просмотрена, когда так говорит сервер или просмотрены все её слайды; дуги +/// кольца горят по просмотренным слайдам; сторис открывается с первого +/// непросмотренного. Тексты и колбэки уходят в просмотр как есть. +class PersonalizationStories extends StatefulWidget { + const PersonalizationStories({ + super.key, + required this.code, + this.sdk, + this.shopId, + this.controller, + this.onLinkClick, + this.onProductClick, + this.onPromoCopied, + this.onError, + this.promoCopiedText = 'Copied', + this.promoCaption = 'Promo code', + this.productButtonText = 'More info', + this.showProductsText = 'Used products', + this.hideProductsText = 'Hide products', + this.retryText = 'Retry', + this.closeLabel = 'Close', + this.soundOnLabel = 'Sound on', + this.soundOffLabel = 'Sound off', + this.padding = const EdgeInsets.all(16), + this.imageProvider, + this.iconBuilder, + }); + + /// Код блока сторис. + final String code; + + /// Явный инстанс; иначе резолв по [shopId]. + final PersonalizationSdk? sdk; + + /// Магазин при нескольких зарегистрированных; без него — единственный. + final String? shopId; + + /// Программное управление; см. [PersonalizationStoriesController]. + final PersonalizationStoriesController? controller; + + /// См. [PersonalizationStoryViewer.onLinkClick]. + final ValueChanged? onLinkClick; + + /// См. [PersonalizationStoryViewer.onProductClick]. + final ValueChanged? onProductClick; + final ValueChanged? onPromoCopied; + final ValueChanged? onError; + + /// Тексты просмотра — см. одноимённые у [PersonalizationStoryViewer]. + final String promoCopiedText; + final String promoCaption; + final String productButtonText; + final String showProductsText; + final String hideProductsText; + final String retryText; + final String closeLabel; + final String soundOnLabel; + final String soundOffLabel; + + /// Поля ленты. + final EdgeInsetsGeometry padding; + + /// Картинка по адресу; не задан — загрузчик SDK ([PersonalizationStoryImageProvider]). + final PersonalizationStoryImageProvider? imageProvider; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + /// Сколько ждать блок, прежде чем сдаться и позвать [onError]. + static const Duration loadTimeout = Duration(seconds: 15); + + /// Сколько ждать регистрации SDK (`REES46.initialize` / `registerShops`), когда + /// инстанс не передан явно, прежде чем сдаться и позвать [onError]. + static const Duration registrationTimeout = Duration(seconds: 15); + + /// Показать сторис блока [code] без ленты: загрузить блок и открыть просмотр — со + /// сторис [startStoryId] (нет такой — с первой). Тексты, колбэки и [controller] — как + /// у виджета. Ошибка (пустой код, магазин не зарегистрирован за 15 с или неоднозначен, + /// загрузка не удалась или дольше 15 с, в блоке нет сторис) уходит в [onError], + /// просмотр не открывается, Future завершается. Иначе Future завершается, когда + /// просмотр закроют. + static Future show( + BuildContext context, { + required String code, + PersonalizationSdk? sdk, + String? shopId, + String? startStoryId, + 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 soundOnLabel = 'Sound on', + String soundOffLabel = 'Sound off', + PersonalizationStoryImageProvider? imageProvider, + Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder, + }) async { + // Носитель текстов и колбэков для просмотра; в дерево не вставляется. + final config = PersonalizationStories( + code: 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 PersonalizationSdk resolved; + final List stories; + try { + resolved = await _resolve(sdk, shopId); + stories = await _fetch(resolved, code); + if (stories.isEmpty) { + throw StateError('stories block "$code" has no stories'); + } + } catch (error) { + debugPrint('PersonalizationStories.show: $code — $error'); + onError?.call(error); + return; + } + if (!context.mounted) return; + final index = stories.indexWhere((story) => story.id == startStoryId); + await _present( + context, + config: config, + sdk: resolved, + stories: stories, + index: index < 0 ? 0 : index, + controller: controller, + ); + } + + @override + State createState() => _PersonalizationStoriesState(); +} + +/// Открыть просмотр [stories] со сторис [index] поверх корневого навигатора; тексты и +/// колбэки — из [config]. Пока просмотр открыт, [controller] ставит его на паузу и +/// листает. Завершается, когда просмотр закроют. +Future _present( + BuildContext context, { + required PersonalizationStories config, + required PersonalizationSdk? sdk, + required List stories, + required int index, + PersonalizationStoriesController? controller, + void Function(Story story, int slideIndex)? onSlideShown, +}) async { + final session = controller?._begin(stories); + final viewer = PersonalizationStoryViewer( + stories: stories, + initialStory: index, + seen: sdk == null + ? const >{} + : StoriesSeenStore.instance.seen(sdk), + code: config.code, + sdk: sdk, + paused: controller?._paused, + storyRequests: session?.turns.stream, + onSlideShown: onSlideShown, + onLinkClick: config.onLinkClick, + onProductClick: config.onProductClick, + onPromoCopied: config.onPromoCopied, + productButtonText: config.productButtonText, + promoCaption: config.promoCaption, + promoCopiedText: config.promoCopiedText, + showProductsText: config.showProductsText, + hideProductsText: config.hideProductsText, + retryText: config.retryText, + closeLabel: config.closeLabel, + soundOnLabel: config.soundOnLabel, + soundOffLabel: config.soundOffLabel, + imageProvider: config.imageProvider, + iconBuilder: config.iconBuilder, + ); + final navigator = Navigator.of(context, rootNavigator: true); + try { + // Тема едет с просмотром: хост мог задать её поддереву, а не приложению. + await navigator.push( + PersonalizationStoryViewer.route( + InheritedTheme.capture( + from: context, + to: navigator.context, + ).wrap(viewer), + ), + ); + } finally { + if (session != null) controller?._end(session); + } +} + +/// SDK по [sdk] или [shopId]. Магазин ещё не зарегистрирован — ждём регистрации до +/// [PersonalizationStories.registrationTimeout], проверяя раз в 100 мс; не дождались — +/// [UnknownShopIdException]. Неоднозначный выбор ([AmbiguousShopException]) — сразу. +/// [alive] вернул `false` — ждать больше незачем, та же ошибка. +Future _resolve( + PersonalizationSdk? sdk, + String? shopId, { + bool Function()? alive, +}) async { + if (sdk != null) return sdk; + const poll = Duration(milliseconds: 100); + for (var waited = Duration.zero; ; waited += poll) { + try { + return REES46.getInstance(shopId); + } on UnknownShopIdException { + final waiting = alive?.call() ?? true; + if (!waiting || waited >= PersonalizationStories.registrationTimeout) { + rethrow; + } + } + await Future.delayed(poll); + } +} + +/// Блок [code] со сторис, у которых есть слайды, и просмотренное магазина — не дольше +/// [PersonalizationStories.loadTimeout]. +Future> _fetch(PersonalizationSdk sdk, String code) async { + if (code.isEmpty) { + throw ArgumentError.value(code, 'code', 'must be non-empty'); + } + // Просмотренное читается вместе с блоком; ошибка блока приходит как есть. + final results = await Future.wait(>[ + sdk.getStories(code), + StoriesSeenStore.instance.load(sdk), + ]).timeout(PersonalizationStories.loadTimeout); + final block = results.first as StoriesBlock; + return playableStories(block.stories); +} + +class _PersonalizationStoriesState extends State { + PersonalizationSdk? _sdk; + List _stories = const []; + bool _loading = true; + int _seq = 0; + bool _presenting = false; + + @override + void initState() { + super.initState(); + widget.controller?._bar = this; + _load(); + } + + @override + void didUpdateWidget(PersonalizationStories oldWidget) { + super.didUpdateWidget(oldWidget); + final controllerChanged = oldWidget.controller != widget.controller; + if (controllerChanged) { + if (oldWidget.controller?._bar == this) oldWidget.controller?._bar = null; + widget.controller?._bar = this; + } + if (oldWidget.sdk != widget.sdk || + oldWidget.shopId != widget.shopId || + oldWidget.code != widget.code) { + _load(); + } else if (controllerChanged) { + // Новый контроллер мог ждать загрузки, а блок уже загружен. После кадра: открытие + // просмотра посреди сборки запрещено. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && !_loading) widget.controller?._flush(); + }); + } + } + + @override + void dispose() { + final controller = widget.controller; + if (controller?._bar == this) { + controller?._bar = null; + controller?._drop(); + } + super.dispose(); + } + + Future _load() async { + final seq = ++_seq; + setState(() => _loading = true); + try { + final sdk = await _resolve( + widget.sdk, + widget.shopId, + alive: () => mounted && seq == _seq, + ); + final stories = await _fetch(sdk, widget.code); + if (!mounted || seq != _seq) return; + setState(() { + _sdk = sdk; + _loading = false; + _stories = stories; + }); + widget.controller?._flush(); + } catch (error) { + if (!mounted || seq != _seq) return; + debugPrint('PersonalizationStories: ${widget.code} — $error'); + setState(() { + _loading = false; + _stories = const []; + }); + widget.controller?._flush(); + // После кадра: ошибка бывает и до первой сборки, а хост в ответ может, например, + // показать снекбар — посреди сборки это запрещено. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) widget.onError?.call(error); + }); + } + } + + /// Открыть сторис номер [index] или с id [storyId]; нет такой — ничего. + Future _openStory({int? index, String? storyId}) => _open( + storyId != null + ? _stories.indexWhere((story) => story.id == storyId) + : index ?? -1, + ); + + Future _open(int index) async { + final sdk = _sdk; + if (_presenting || index < 0 || index >= _stories.length) return; + _presenting = true; + try { + await _present( + context, + config: widget, + sdk: sdk, + stories: _stories, + index: index, + controller: widget.controller, + onSlideShown: (_, _) { + if (mounted) setState(() {}); + }, + ); + } finally { + _presenting = false; + } + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return PersonalizationStoriesBar(loading: true, padding: widget.padding); + } + final stories = _stories; + final sdk = _sdk; + if (stories.isEmpty || sdk == null) return const SizedBox.shrink(); + final seen = StoriesSeenStore.instance.seen(sdk); + return PersonalizationStoriesBar( + padding: widget.padding, + items: [ + for (final story in stories) + _item(story, seen[story.id] ?? const {}), + ], + onItemTap: (item) => + _open(stories.indexWhere((story) => story.id == item.id)), + iconBuilder: widget.iconBuilder, + ); + } + + PersonalizationStoryItem _item(Story story, Set seen) => + PersonalizationStoryItem( + id: story.id, + label: story.name, + image: storyImage(story.avatar, widget.imageProvider), + pinned: story.pinned, + viewed: StoriesPlayback.isViewed(story, seen), + segments: story.slides.length, + seenSegments: { + for (var i = 0; i < story.slides.length; i++) + if (seen.contains(story.slides[i].id)) i, + }, + ); +} diff --git a/lib/src/ui/widgets/personalization_story_viewer.dart b/lib/src/ui/widgets/personalization_story_viewer.dart new file mode 100644 index 0000000..7e8483f --- /dev/null +++ b/lib/src/ui/widgets/personalization_story_viewer.dart @@ -0,0 +1,845 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/widgets.dart'; +import 'package:video_player/video_player.dart'; + +import '../../personalization_sdk.dart'; +import '../../stories/stories_response.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_seen_store.dart'; +import 'stories_slide_view.dart'; +import 'stories_sound.dart'; +import 'stories_support.dart'; + +/// Полноэкранный просмотр сторис: слайды по таймеру, листание, товары, ссылки. +/// +/// Источник: Figma Mobile SDK UI Kit, страница Stories (1:32), фреймы Card/Story +/// (Product, Promo, Discount, Action, Slide, Text) 402×874. Как рисуется слайд — см. +/// [StorySlideView]; логика без UI — [StoriesPlayback]. +/// +/// Поведение (общие правила всех платформ): +/// - касание левой трети — назад, правой — вперёд, середина ничего не делает; в RTL края +/// меняются местами. Удержание от 200 мс — пауза, отпускание её снимает и никуда не +/// листает. Назад на первом слайде первой сторис перезапускает слайд — прогресс и видео +/// с нуля, без перезагрузки и повторного `view`; вперёд на последнем слайде последней — +/// закрывает просмотр; +/// - свайп вбок листает сторис; заход на сторис (просмотр слайда, трекинг `view`) — только +/// когда страница осела, подглядывание соседней не считается. Свайп вниз дальше 120 или +/// быстрее 800 в секунду закрывает, иначе слайд пружинит назад; пока тянут — пауза; +/// - раскрытая шторка товаров ставит паузу и блокирует листание; тап мимо неё и системное +/// «назад» её закрывают; смена слайда её сбрасывает; +/// - пауза и когда приложение свёрнуто или потеряло фокус, и когда просмотр закрыт другим +/// экраном, и по [paused] от хоста; время слайда в паузе не идёт; +/// - часы слайда стартуют, когда медиа готово; не загрузилось или не успело за 10 с — пауза +/// и кнопка [retryText]; видео ещё и само повторяет загрузку через 15 с. Оба отсчёта в +/// фоне и под другим экраном стоят и потом досчитывают остаток; +/// - видео длится по своей реальной длине, прогресс идёт за воспроизведением и стоит на +/// подгрузке; видео не ждёт загрузки целиком: играет по сети, пока кэш на диске +/// ([StoriesMediaCache]) заполняется в фоне, и из файла в следующий раз; следующий слайд +/// подгружается заранее. Звук выключен при первом открытии, выбор помнится до конца +/// процесса, кнопка громкости «вверх» включает звук ([StoriesSound]); +/// - GIF на фоне слайда (узнаётся по байтам) играет по своим задержкам, а слайд длится +/// время из админки или один круг GIF — что дольше. Стоит слайд — стоит и GIF на +/// текущем кадре; перезапуск и новый заход начинают его с первого кадра без новой +/// загрузки ([StoryGifPlayer]). Обложки, постеры и картинки товаров показывают первый +/// кадр. С картинками хоста ([imageProvider]) GIF рисует хост, слайд — время админки. +/// +/// Трекинг через [sdk] с кодом [code]: `view` — на каждый слайд, ставший текущим на +/// осевшей странице; `click` — кнопка, товар карусели, копирование промокода. Id, которые +/// не целые положительные числа (`39_0`), не трекаются. Просмотренные слайды с [sdk] +/// запоминаются на устройстве по магазину ([StoriesSeenStore]); хосту о показе слайда +/// сообщает [onSlideShown]. +/// +/// Кнопки и товары карусели сначала закрывают просмотр, потом зовут [onLinkClick] / +/// [onProductClick]; не заданы — ссылку открывает система через SDK. Кнопка без ссылки +/// на медиа-слайде ничего не открывает и просмотр не закрывает — только `click`. +/// +/// Открывается маршрутом [route] или встраивается как обычный виджет с [onClose]. +class PersonalizationStoryViewer extends StatefulWidget { + const PersonalizationStoryViewer({ + super.key, + required this.stories, + this.initialStory = 0, + this.seen = const >{}, + this.code, + this.sdk, + this.paused, + this.storyRequests, + this.onSlideShown, + this.onClose, + this.onLinkClick, + this.onProductClick, + this.onPromoCopied, + this.productButtonText = 'More info', + this.promoCaption = 'Promo code', + this.promoCopiedText = 'Copied', + this.showProductsText = 'Used products', + this.hideProductsText = 'Hide products', + this.retryText = 'Retry', + this.closeLabel = 'Close', + this.soundOnLabel = 'Sound on', + this.soundOffLabel = 'Sound off', + this.imageProvider, + this.iconBuilder, + }); + + /// Сторис блока; сторис без слайдов пропускаются. + final List stories; + + /// С какой сторис начать — индекс в [stories]. + final int initialStory; + + /// Уже просмотренные слайды: id слайдов по id сторис. По ним выбирается стартовый слайд + /// сторис (первый непросмотренный). С [sdk] к ним добавляется сохранённое на устройстве. + final Map> seen; + + /// Код блока для трекинга. + final String? code; + + /// Инстанс для трекинга, хранения просмотренного и системных ссылок; `null` — без них. + final PersonalizationSdk? sdk; + + /// Пауза от хоста: пока `true`, слайд стоит. + final ValueListenable? paused; + + /// Просьбы хоста перелистнуть открытый просмотр на сторис — индекс в [stories]. + /// Сторис без слайдов и текущая просьбы пропускают. + final Stream? storyRequests; + + /// Слайд [slideIndex] сторис [story] стал текущим. + final void Function(Story story, int slideIndex)? onSlideShown; + + /// Закрыть просмотр; не задан — `Navigator.maybePop`. + final VoidCallback? onClose; + + /// Ссылка кнопки; не задан — ссылку открывает система. + final ValueChanged? onLinkClick; + + /// Товар: кнопка товарного слайда без своей ссылки (или [productButtonText]) или + /// карусель; картинка товара не нажимается. Не задан — открывается ссылка товара. + final ValueChanged? onProductClick; + + /// Промокод скопирован. + final ValueChanged? onPromoCopied; + + /// Подпись кнопки товарного слайда, когда у слайда своих кнопок нет. + final String productButtonText; + + /// Подпись над промокодом, когда в админке у товара нет своей. + final String promoCaption; + + /// Текст тоста после копирования промокода; тост всегда сверху. + final String promoCopiedText; + + /// Подписи переключателя товаров, когда их не прислал сервер. + final String showProductsText; + final String hideProductsText; + + /// Подпись кнопки повтора загрузки медиа. + final String retryText; + + /// Подписи для скринридера: крестик и кнопка звука — её текущее состояние (звук + /// включён / выключен). + final String closeLabel; + final String soundOnLabel; + final String soundOffLabel; + + /// Картинка по адресу; не задан — загрузчик SDK ([PersonalizationStoryImageProvider]). + final PersonalizationStoryImageProvider? imageProvider; + + final Widget Function( + BuildContext context, + String asset, + double size, + Color color, + )? + iconBuilder; + + /// Маршрут просмотра: во весь экран, с появлением. Непрозрачен только сам просмотр — + /// при свайпе вниз под ним виден экран хоста. + static Route route(Widget viewer) => PageRouteBuilder( + opaque: false, + transitionDuration: const Duration(milliseconds: 250), + reverseTransitionDuration: const Duration(milliseconds: 200), + pageBuilder: (context, animation, secondaryAnimation) => viewer, + transitionsBuilder: (context, animation, secondaryAnimation, child) { + final curved = CurvedAnimation(parent: animation, curve: Curves.easeOut); + return FadeTransition( + opacity: curved, + child: ScaleTransition( + scale: Tween(begin: 0.96, end: 1).animate(curved), + child: child, + ), + ); + }, + ); + + @override + State createState() => + _PersonalizationStoryViewerState(); +} + +class _PersonalizationStoryViewerState extends State + with SingleTickerProviderStateMixin, WidgetsBindingObserver { + late final StoriesPlayback _playback = StoriesPlayback( + stories: widget.stories, + initialStory: widget.initialStory, + seen: _initialSeen(), + ); + late final PageController _pages = PageController( + initialPage: _playback.storyIndex, + ); + late final Ticker _ticker = createTicker(_onTick); + Duration _lastTick = Duration.zero; + + /// Доля прошедшего времени слайда — для прогресса; перестраивает только шапку. + final ValueNotifier _progress = ValueNotifier(0); + + /// Насколько просмотр стянут вниз; перестраивает только сдвиг, не страницы. + final ValueNotifier _drag = ValueNotifier(0); + + StreamSubscription? _requests; + VideoPlayerController? _video; + bool _videoReady = false; + bool _videoPlaying = false; + + /// GIF фона текущего слайда; кадр у него есть — когда готов. + StoryGifPlayer? _gif; + + /// 10 с на готовность медиа и 15 с до самоповтора видео; в фоне замирают. + StoriesTimer? _timeout; + StoriesTimer? _autoRetry; + bool _closing = false; + + static const Duration _turn = Duration(milliseconds: 300); + static const Duration _readyTimeout = Duration(seconds: 10); + static const Duration _videoRetry = Duration(seconds: 15); + static const double _closeDistance = 120; + static const double _closeVelocity = 800; + + Map> _initialSeen() { + final sdk = widget.sdk; + final stored = sdk == null + ? const >{} + : StoriesSeenStore.instance.seen(sdk); + return >{ + for (final entry in stored.entries) entry.key: entry.value, + for (final entry in widget.seen.entries) + entry.key: {...?stored[entry.key], ...entry.value}, + }; + } + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + StoriesSound.instance.attach(); + StoriesSound.instance.muted.addListener(_onMuted); + widget.paused?.addListener(_onHostPause); + _onHostPause(); + _requests = widget.storyRequests?.listen(_onStoryRequest); + _onLifecycle(WidgetsBinding.instance.lifecycleState); + // Первая страница осела сразу: заход после кадра — загрузка картинки читает контекст. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && !_playback.isEmpty) _settled(_playback.storyIndex); + }); + } + + @override + void didUpdateWidget(PersonalizationStoryViewer oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.paused != widget.paused) { + oldWidget.paused?.removeListener(_onHostPause); + widget.paused?.addListener(_onHostPause); + _onHostPause(); + } + if (oldWidget.storyRequests != widget.storyRequests) { + _requests?.cancel(); + _requests = widget.storyRequests?.listen(_onStoryRequest); + } + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // Просмотр закрыт непрозрачным экраном — навигатор глушит тикеры его поддерева. + _setPaused( + StoriesPauseReason.covered, + !TickerMode.valuesOf(context).enabled, + ); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) => + _onLifecycle(state); + + void _onLifecycle(AppLifecycleState? state) => _setPaused( + StoriesPauseReason.background, + state != null && state != AppLifecycleState.resumed, + ); + + void _onHostPause() => + _setPaused(StoriesPauseReason.host, widget.paused?.value ?? false); + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + widget.paused?.removeListener(_onHostPause); + _requests?.cancel(); + StoriesSound.instance.muted.removeListener(_onMuted); + _timeout?.cancel(); + _autoRetry?.cancel(); + _ticker.dispose(); + _disposeVideo(); + _disposeGif(); + StoriesSound.instance.detach(); + _pages.dispose(); + _progress.dispose(); + _drag.dispose(); + super.dispose(); + } + + /// Поставить или снять паузу [reason]; часы и видео меняются только на переходе. + void _setPaused(StoriesPauseReason reason, bool paused) { + final changed = paused ? _playback.pause(reason) : _playback.resume(reason); + if (reason == StoriesPauseReason.background || + reason == StoriesPauseReason.covered) { + _freezeTimers(); + } + if (changed) _sync(); + } + + /// Просмотра не видно: приложение в фоне или сверху другой экран. + bool get _hidden => + _playback.pausedBy(StoriesPauseReason.background) || + _playback.pausedBy(StoriesPauseReason.covered); + + /// Пока просмотра не видно, таймеры готовности и самоповтора стоят; потом + /// досчитывают остаток. + void _freezeTimers() { + for (final timer in [_timeout, _autoRetry]) { + if (timer == null) continue; + _hidden ? timer.freeze() : timer.resume(); + } + } + + StoriesTimer _timer(Duration duration, void Function() onFire) => + StoriesTimer(duration, onFire, frozen: _hidden); + + /// Часы и видео идут, только пока слайд не стоит. Вызывается на переходах, не на кадре. + void _sync() { + final running = _playback.running; + if (running && !_ticker.isActive) { + _lastTick = Duration.zero; + _ticker.start(); + } else if (!running && _ticker.isActive) { + _ticker.stop(); + } + final video = _video; + if (video == null || !_videoReady || running == _videoPlaying) return; + _videoPlaying = running; + running ? video.play() : video.pause(); + } + + void _onTick(Duration elapsed) { + final delta = elapsed - _lastTick; + _lastTick = elapsed; + final video = _video?.value; + // У видео время идёт, только пока оно играет, а не подгружается. + if (_playback.followsVideo && + (video == null || !video.isPlaying || video.isBuffering)) { + return; + } + // GIF идёт теми же шагами, что часы слайда: стоят часы — стоит и он. + _gif?.advance( + delta > StoriesPlayback.maxTick ? StoriesPlayback.maxTick : delta, + ); + final ended = _playback.tick(delta); + _progress.value = _playback.progress; + if (ended) _step(_playback.next()); + } + + // --- Навигация ---------------------------------------------------------------------- + + /// Страница осела на [index]: заход на сторис или просто конец листания. + void _settled(int index) { + if (_playback.settle(index)) { + _entered(); + } else { + _sync(); + } + setState(() {}); + } + + /// Исполнить шаг машины. + void _step(StoriesStep step) { + switch (step) { + case StoriesStep.none: + return; + case StoriesStep.slide: + _entered(); + case StoriesStep.restart: + // Тот же заход: медиа не перезагружается, `view` не повторяется. + _progress.value = 0; + if (_videoReady) _video?.seekTo(Duration.zero); + _gif?.restart(); + case StoriesStep.turn: + _sync(); + final target = _playback.turnTarget!; + if (_pages.hasClients) { + _pages.animateToPage( + target, + duration: _turn, + curve: Curves.easeInOut, + ); + } else { + _settled(target); + } + case StoriesStep.close: + _close(); + } + if (mounted) setState(() {}); + } + + /// Хост просит сторис [index] исходного списка: листаем к ней, шторка сворачивается. + void _onStoryRequest(int index) { + if (_closing || index < 0 || index >= widget.stories.length) return; + final target = _playback.stories.indexOf(widget.stories[index]); + if (target >= 0) _step(_playback.turnTo(target)); + } + + void _close() { + if (_closing) return; + _closing = true; + _ticker.stop(); + _video?.pause(); + final onClose = widget.onClose; + if (onClose != null) { + onClose(); + return; + } + // Не maybePop: при раскрытой шторке PopScope держит маршрут, а закрыть просмотр + // нужно и из карусели товаров. + final navigator = Navigator.of(context); + if (navigator.canPop()) navigator.pop(); + } + + /// Закрыть просмотр, потом [action] — переход по ссылке или к товару. + void _closeThen(VoidCallback action) { + _close(); + action(); + } + + /// Новый заход на слайд: прогресс с нуля, медиа, просмотренное, трекинг, хост. + void _entered() { + final story = _playback.story; + final slide = _playback.slide; + final index = _playback.slideIndex; + final generation = _playback.generation; + _progress.value = 0; + _load(generation); + final sdk = widget.sdk; + if (sdk != null) { + StoriesSeenStore.instance.mark(sdk, story.id, slide.id); + if (storyTrackableId(story.id) && storyTrackableId(slide.id)) { + sdk.tracking + .storyView(storyId: story.id, slideId: slide.id, code: widget.code) + .catchError((Object error) { + debugPrint('PersonalizationStoryViewer: storyView — $error'); + }); + } + } + // Хосту — после кадра: заход бывает посреди сборки, а хост в ответ перестраивает + // свой экран под маршрутом. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && generation == _playback.generation) { + widget.onSlideShown?.call(story, index); + } + }); + } + + void _clicked() { + final sdk = widget.sdk; + final story = _playback.story; + final slide = _playback.slide; + if (sdk == null || + !storyTrackableId(story.id) || + !storyTrackableId(slide.id)) { + return; + } + sdk.tracking + .storyClick(storyId: story.id, slideId: slide.id, code: widget.code) + .catchError((Object error) { + debugPrint('PersonalizationStoryViewer: storyClick — $error'); + }); + } + + // --- Медиа -------------------------------------------------------------------------- + + /// Загрузка медиа захода [generation]. Готово — часы пошли; ошибка или 10 с без + /// готовности — пауза и «Повторить». Ответы прошлых заходов отбрасываются. + void _load(int generation) { + _timeout?.cancel(); + _autoRetry?.cancel(); + _disposeVideo(); + _disposeGif(); + _sync(); + final slide = _playback.slide; + switch (storyMediaOf(slide)) { + case StoryMedia.none: + _ready(generation); + case StoryMedia.image: + _timeout = _timer(_readyTimeout, () => _failed(generation)); + _loadImage(slide.background, generation); + case StoryMedia.video: + _timeout = _timer(_readyTimeout, () => _failed(generation)); + _loadVideo(slide.background, generation); + } + } + + /// Картинка хоста — как есть, время слайда из админки. Своя — байты один раз: GIF + /// играет [StoryGifPlayer] (готов с первым кадром, слайд не короче круга), прочее — + /// фото как у [NetworkImage]. + Future _loadImage(String url, int generation) async { + final custom = widget.imageProvider; + if (custom != null) return _precache(custom(url), generation); + try { + final bytes = await StoriesImageBytes.instance.load(url, keep: true); + if (!_current(generation)) return; + final gif = StoryGif.parse(bytes); + if (gif == null) return _precache(StoryImage(url), generation); + final player = StoryGifPlayer(bytes, gif, limit: _slideLimit()); + _gif = player; + await player.start(); + if (!_current(generation) || _gif != player) return; + _playback.useGifLoop(gif.loop); + _ready(generation); + } catch (error) { + debugPrint('PersonalizationStoryViewer: image $url — $error'); + _failed(generation); + } + } + + void _precache(ImageProvider image, int generation) { + var failed = false; + precacheImage( + image, + context, + onError: (_, _) => failed = true, + ).then((_) => failed ? _failed(generation) : _ready(generation)); + } + + /// Площадь слайда в пикселях: больше неё кадры GIF не держатся. Слайд — во весь экран. + Size? _slideLimit() { + final size = View.maybeOf(context)?.physicalSize; + return size == null || size.isEmpty ? null : size; + } + + void _disposeGif() { + _gif?.dispose(); + _gif = null; + } + + /// Видео из кэша, а нет файла — сразу по сети, пока кэш заполняется в фоне: загрузка + /// целиком не ждётся. Готово — когда плеер готов играть. + Future _loadVideo(String url, int generation) async { + try { + await StoriesSound.instance.beforeVideo(); + final cache = StoriesMediaCache.instance; + final file = await cache.cached(url); + if (!_current(generation)) return; + if (file == null) cache.fill(url); + final options = VideoPlayerOptions(mixWithOthers: true); + final video = file != null + ? VideoPlayerController.file(file, videoPlayerOptions: options) + : VideoPlayerController.networkUrl( + Uri.parse(url), + videoPlayerOptions: options, + ); + _video = video; + await video.initialize(); + if (!_current(generation) || _video != video) return; + await video.setLooping(false); + await video.setVolume(StoriesSound.instance.muted.value ? 0 : 1); + await StoriesSound.instance.afterVideo(); + if (!_current(generation) || _video != video) return; + video.addListener(_onVideo); + _playback.useVideoDuration(video.value.duration); + _videoReady = true; + _videoPlaying = false; + _ready(generation); + } catch (error) { + debugPrint('PersonalizationStoryViewer: video $url — $error'); + _failed(generation); + } + } + + bool _current(int generation) => + mounted && generation == _playback.generation; + + void _ready(int generation) { + if (!_current(generation) || _playback.pausedBy(StoriesPauseReason.error)) { + return; + } + _timeout?.cancel(); + _playback.mediaReady(generation); + _sync(); + _preloadNext(); + setState(() {}); + } + + void _failed(int generation) { + if (!_current(generation)) return; + _timeout?.cancel(); + _playback.mediaFailed(generation); + _sync(); + if (storyMediaOf(_playback.slide) == StoryMedia.video) { + // Видео повторяет загрузку и само. + _autoRetry?.cancel(); + _autoRetry = _timer(_videoRetry, _retry); + } + setState(() {}); + } + + void _retry() { + final slide = _playback.slide; + if (storyMediaOf(slide) == StoryMedia.image) { + storyImage(slide.background, widget.imageProvider)?.evict(); + StoriesImageBytes.instance.evict(slide.background); + } + final generation = _playback.retry(); + _progress.value = 0; + _load(generation); + setState(() {}); + } + + void _onVideo() { + final video = _video; + if (video == null) return; + final value = video.value; + if (value.hasError) { + video.removeListener(_onVideo); + return _failed(_playback.generation); + } + _playback.syncVideoPosition(value.position); + _progress.value = _playback.progress; + final ended = + value.isCompleted || + (value.duration > Duration.zero && value.position >= value.duration); + if (ended && _playback.running) _step(_playback.next()); + } + + void _disposeVideo() { + final video = _video; + _video = null; + _videoReady = false; + _videoPlaying = false; + if (video == null) return; + video.removeListener(_onVideo); + video.dispose(); + } + + void _onMuted() { + _video?.setVolume(StoriesSound.instance.muted.value ? 0 : 1); + if (mounted) setState(() {}); + } + + /// Следующий слайд — тот же сторис или стартовый следующей — грузится заранее. + void _preloadNext() { + final stories = _playback.stories; + final story = _playback.storyIndex; + final StorySlide next; + if (_playback.slideIndex < _playback.story.slides.length - 1) { + next = _playback.story.slides[_playback.slideIndex + 1]; + } else if (story < stories.length - 1) { + next = stories[story + 1].slides[_playback.startSlideFor(story + 1)]; + } else { + return; + } + switch (storyMediaOf(next)) { + case StoryMedia.none: + break; + case StoryMedia.image: + // Байты своего загрузчика остаются в памяти: GIF следующего слайда не качается + // второй раз, а его первый кадр уже готов. + if (widget.imageProvider == null) { + StoriesImageBytes.instance + .load(next.background, keep: true) + .then((_) {}, onError: (Object _) {}); + } + final image = storyImage(next.background, widget.imageProvider); + if (image != null) precacheImage(image, context, onError: (_, _) {}); + case StoryMedia.video: + StoriesMediaCache.instance.preload(next.background); + final poster = storyImage(next.preview, widget.imageProvider); + if (poster != null) precacheImage(poster, context, onError: (_, _) {}); + } + } + + // --- Действия ----------------------------------------------------------------------- + + /// Касание: левая треть — назад, правая — вперёд, середина — ничего; в RTL зеркально. + void _tap(double dx, double width) { + final rtl = Directionality.of(context) == TextDirection.rtl; + if (dx < width / 3) { + _step(rtl ? _playback.next() : _playback.previous()); + } else if (dx > width * 2 / 3) { + _step(rtl ? _playback.previous() : _playback.next()); + } + } + + void _sheet(bool open) { + final changed = open ? _playback.openSheet() : _playback.closeSheet(); + if (!changed) return; + _sync(); + setState(() {}); + } + + /// Кнопка слайда: своя ссылка, у товарного слайда без неё — товар. Кнопка без ссылки на + /// медиа-слайде — только `click`: просмотр остаётся открытым. + void _button(StoryButtonElement button) { + _clicked(); + final product = storyProductElement(_playback.slide)?.item; + final own = storyButtonLink(button); + if (own.isNotEmpty) return _closeThen(() => _openLink(own)); + if (product != null) _closeThen(() => _goTo(product)); + } + + void _product(StoryProduct product) { + _clicked(); + _closeThen(() => _goTo(product)); + } + + void _promo(String code) { + _clicked(); + widget.onPromoCopied?.call(code); + } + + void _goTo(StoryProduct product) { + final onProduct = widget.onProductClick; + if (onProduct != null) return onProduct(product); + _openUrl(storyProductLink(product)); + } + + void _openLink(String url) { + if (url.isEmpty) return; + final onLink = widget.onLinkClick; + if (onLink != null) return onLink(url); + _openUrl(url); + } + + void _openUrl(String url) { + if (url.isEmpty) return; + widget.sdk?.openUrl(url).catchError((Object error) { + debugPrint('PersonalizationStoryViewer: cannot open $url — $error'); + return false; + }); + } + + // --- Сборка ------------------------------------------------------------------------- + + bool _onScroll(ScrollNotification notification) { + if (notification.depth != 0) return false; + if (notification is ScrollStartNotification && + notification.dragDetails != null) { + _setPaused(StoriesPauseReason.drag, true); + } else if (notification is ScrollEndNotification && _pages.hasClients) { + _settled(_pages.page?.round() ?? _playback.storyIndex); + } + return false; + } + + void _dragEnd(double velocity) { + if (_drag.value > _closeDistance || velocity > _closeVelocity) { + _close(); + return; + } + _drag.value = 0; + _setPaused(StoriesPauseReason.drag, false); + } + + @override + Widget build(BuildContext context) { + if (_playback.isEmpty) return const ColoredBox(color: Color(0xFF000000)); + final sheet = _playback.sheetOpen; + return PopScope( + // Системное «назад» сперва сворачивает шторку товаров. + canPop: !sheet, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) _sheet(false); + }, + // В корневом маршруте нет Material: без этого Text взял бы аварийный стиль + // приложения — с жёлтым подчёркиванием. + child: DefaultTextStyle( + style: const TextStyle(), + child: GestureDetector( + onVerticalDragStart: sheet + ? null + : (_) => _setPaused(StoriesPauseReason.drag, true), + onVerticalDragUpdate: sheet + ? null + : (details) => + _drag.value = math.max(0, _drag.value + details.delta.dy), + onVerticalDragEnd: sheet + ? null + : (details) => _dragEnd(details.primaryVelocity ?? 0), + onVerticalDragCancel: sheet ? null : () => _dragEnd(0), + child: ValueListenableBuilder( + valueListenable: _drag, + builder: (context, drag, child) => Transform.translate( + offset: Offset(0, drag), + child: Transform.scale( + scale: 1 - math.min(drag / 2000, 0.1), + child: child, + ), + ), + child: NotificationListener( + onNotification: _onScroll, + child: PageView.builder( + controller: _pages, + physics: sheet ? const NeverScrollableScrollPhysics() : null, + itemCount: _playback.stories.length, + itemBuilder: _page, + ), + ), + ), + ), + ), + ); + } + + Widget _page(BuildContext context, int index) { + final story = _playback.stories[index]; + final live = _playback.entered && index == _playback.storyIndex; + return StorySlideView( + key: ValueKey('story-${story.id}-$index'), + story: story, + slideIndex: live ? _playback.slideIndex : _playback.startSlideFor(index), + config: widget, + live: live, + generation: live ? _playback.generation : 0, + progress: live ? _progress : null, + video: live && _videoReady ? _video : null, + gif: live ? _gif : null, + muted: StoriesSound.instance.muted.value, + sheetOpen: live && _playback.sheetOpen, + failed: live && _playback.pausedBy(StoriesPauseReason.error), + onTap: _tap, + onHold: (held) => _setPaused(StoriesPauseReason.hold, held), + onClose: _close, + onToggleMute: StoriesSound.instance.toggle, + onSheet: _sheet, + onButton: _button, + onProduct: _product, + onPromoCopied: _promo, + onRetry: _retry, + ); + } +} diff --git a/lib/src/ui/widgets/search_support.dart b/lib/src/ui/widgets/search_support.dart new file mode 100644 index 0000000..32be5d9 --- /dev/null +++ b/lib/src/ui/widgets/search_support.dart @@ -0,0 +1,115 @@ +import 'package:flutter/widgets.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../search/search_response.dart'; +import '../components/personalization_product.dart'; + +/// Категория, на которую можно перейти из поиска: из подсказок instant-поиска (есть id) +/// или из популярных категорий пустого запроса (только имя и ссылка). +@immutable +class PersonalizationSearchCategory { + const PersonalizationSearchCategory({ + required this.id, + required this.name, + required this.url, + }); + + final String? id; + final String name; + final String? url; +} + +/// Недавние запросы пользователя — локальная история виджета поиска, по магазину. +/// +/// Сервер тоже помнит последние запросы (`last_queries` в `search/blank`), но не умеет +/// забывать по одному, а в макете у каждого тега крестик и есть «Clear». Поэтому история +/// живёт в SharedPreferences под ключом с id магазина. +class RecentSearches { + RecentSearches({required String shopKey, required this.limit}) + : _key = 'personalization.ui.recentSearches.$shopKey'; + + final String _key; + final int limit; + + Future> load() async { + final preferences = await SharedPreferences.getInstance(); + return preferences.getStringList(_key) ?? const []; + } + + /// Кладёт запрос в начало, убирая дубль, и режет по лимиту. + Future> add(String query) async { + final trimmed = query.trim(); + final items = await load(); + if (trimmed.isEmpty) return items; + final next = [ + trimmed, + ...items.where((item) => item.toLowerCase() != trimmed.toLowerCase()), + ]; + return _save(next.take(limit).toList()); + } + + Future> remove(String query) async => + _save((await load()).where((item) => item != query).toList()); + + Future> clear() => _save(const []); + + Future> _save(List items) async { + final preferences = await SharedPreferences.getInstance(); + await preferences.setStringList(_key, items); + return items; + } +} + +/// Товар ответа поиска → данные карточки кита. Строки берутся уже отформатированными +/// сервером (`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; + if (parentId == null || parentId.isEmpty) return null; + for (final item in all) { + if (item.id == parentId) return item.name; + } + return null; +} diff --git a/lib/src/ui/widgets/stories_gif.dart b/lib/src/ui/widgets/stories_gif.dart new file mode 100644 index 0000000..b8325b6 --- /dev/null +++ b/lib/src/ui/widgets/stories_gif.dart @@ -0,0 +1,128 @@ +import 'package:flutter/foundation.dart'; + +/// GIF по его байтам: размер и задержки кадров — без декодирования картинки. +/// +/// GIF узнаётся только по подписи `GIF87a` / `GIF89a` в начале байтов — не по адресу и +/// не по типу слайда. Задержка кадра — из его Graphic Control Extension; меньше 20 мс (и +/// 0, и кадр без расширения) считается 100 мс — как в браузерах. Один круг анимации +/// ([loop]) — сумма задержек всех кадров. Правила общие для всех платформ. +@immutable +class StoryGif { + const StoryGif._({ + required this.width, + required this.height, + required this.delays, + required bool complete, + }) : _complete = complete; + + /// Размер холста GIF в пикселях. + final int width; + final int height; + + /// Задержки кадров по порядку, уже с поправкой на короткие ([frameDelay]). + final List delays; + + /// Разбор дошёл до конца без ошибок. + final bool _complete; + + /// Короче этого задержка кадра не бывает: такая считается [shortDelay]. + static const Duration minDelay = Duration(milliseconds: 20); + + /// Задержка вместо слишком короткой. + static const Duration shortDelay = Duration(milliseconds: 100); + + /// Длина одного круга анимации; `null` — неизвестна: байты битые или кадров нет. + Duration? get loop { + if (!_complete || delays.isEmpty) return null; + return delays.fold(Duration.zero, (sum, delay) => sum + delay); + } + + /// Задержка кадра по правилу браузеров: меньше 20 мс (и 0) — 100 мс. + static Duration frameDelay(Duration delay) => + delay < minDelay ? shortDelay : delay; + + /// Байты начинаются с подписи GIF. + static bool isGif(List bytes) { + if (bytes.length < 6) return false; + // «GIF8», затем «7a» или «9a». + return bytes[0] == 0x47 && + bytes[1] == 0x49 && + bytes[2] == 0x46 && + bytes[3] == 0x38 && + (bytes[4] == 0x37 || bytes[4] == 0x39) && + bytes[5] == 0x61; + } + + /// Разобрать [bytes]; не GIF — `null`. Битый GIF разбирается до первой ошибки, а его + /// круг неизвестен ([loop] — `null`). + static StoryGif? parse(List bytes) { + if (!isGif(bytes)) return null; + final delays = []; + if (bytes.length < 13) { + return StoryGif._(width: 0, height: 0, delays: delays, complete: false); + } + final width = bytes[6] | bytes[7] << 8; + final height = bytes[8] | bytes[9] << 8; + // Заголовок 6 байт, описание экрана 7 байт, за ним общая палитра. + var at = 13 + _paletteSize(bytes[10]); + var delay = Duration.zero; + var complete = true; + while (at < bytes.length) { + final block = bytes[at++]; + if (block == 0x3B) break; // Конец файла. + if (block == 0x21) { + // Расширение: метка, затем подблоки до пустого. + if (at >= bytes.length) { + complete = false; + break; + } + final label = bytes[at++]; + // Graphic Control Extension: размер 4, флаги, задержка в сотых секунды (LE). + if (label == 0xF9 && at + 3 < bytes.length && bytes[at] >= 4) { + final hundredths = bytes[at + 2] | bytes[at + 3] << 8; + delay = Duration(milliseconds: hundredths * 10); + } + at = _skipSubBlocks(bytes, at); + } else if (block == 0x2C) { + // Кадр: 9 байт описания, своя палитра, размер кода LZW, подблоки данных. + if (at + 9 > bytes.length) { + complete = false; + break; + } + at += 9 + _paletteSize(bytes[at + 8]) + 1; + at = _skipSubBlocks(bytes, at); + if (at >= 0) { + delays.add(frameDelay(delay)); + delay = Duration.zero; + } + } else { + at = -1; // Неизвестный блок. + } + if (at < 0) { + complete = false; + break; + } + } + return StoryGif._( + width: width, + height: height, + delays: List.unmodifiable(delays), + complete: complete, + ); + } + + /// Байт палитры по флагам: есть палитра — 3 × 2^(N+1). + static int _paletteSize(int flags) => + flags & 0x80 == 0 ? 0 : 3 * (1 << ((flags & 0x07) + 1)); + + /// Позиция после подблоков, начиная с [at]; байты кончились раньше — `-1`. + static int _skipSubBlocks(List bytes, int at) { + var position = at; + while (position < bytes.length) { + final size = bytes[position++]; + if (size == 0) return position; + position += size; + } + return -1; + } +} diff --git a/lib/src/ui/widgets/stories_gif_player.dart b/lib/src/ui/widgets/stories_gif_player.dart new file mode 100644 index 0000000..94cc775 --- /dev/null +++ b/lib/src/ui/widgets/stories_gif_player.dart @@ -0,0 +1,189 @@ +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; + +import 'stories_gif.dart'; + +/// Проигрыватель GIF фона слайда: кадры по своим задержкам ([StoryGif.delays]), по +/// кругу, пока слайд идёт. +/// +/// - [start] декодирует первый кадр — с ним слайд готов, и его часы могут идти; +/// - время даёт просмотр ([advance]) теми же шагами, что часы слайда: стоят часы — стоит +/// и GIF на текущем кадре, а продолжение идёт с него же и с остатком его задержки; +/// - [restart] — с первого кадра из тех же байтов в памяти, без новой загрузки; +/// - кодек отдаёт кадры по одному: в памяти только показанный кадр и следующий. Кадр +/// крупнее [limit] (площадь слайда в пикселях) уменьшается до неё — движок +/// анимированные картинки при декодировании не ужимает. +class StoryGifPlayer extends ChangeNotifier { + StoryGifPlayer(this.bytes, this.gif, {this.limit}); + + /// Байты GIF — из них же кодек создаётся заново при [restart]. + final Uint8List bytes; + final StoryGif gif; + + /// Больше этого кадр не держится; `null` — без ограничения. + final ui.Size? limit; + + /// Как из байтов получить кодек. Тесты подменяют. + @visibleForTesting + static Future Function(Uint8List bytes) codecOf = + ui.instantiateImageCodec; + + ui.Codec? _codec; + ui.Image? _frame; + ui.Image? _next; + Duration _nextDuration = Duration.zero; + int _index = 0; + + /// Сколько ещё показывать текущий кадр; меньше нуля — следующий уже опаздывает. + Duration _left = Duration.zero; + + /// Номер запуска: декодирование прошлого запуска (до [restart] или [dispose]) + /// отбрасывается. + int _run = 0; + bool _disposed = false; + + /// Показанный кадр; `null` — первый ещё не готов. + ui.Image? get frame => _frame; + + /// Номер показанного кадра. + int get index => _index; + + /// Задержка кадра [index]: из разбора байтов, а если кодек насчитал другое число + /// кадров — из самого кодека, с той же поправкой на короткие. + Duration _delay(int index, Duration decoded) { + final codec = _codec; + if (codec != null && + gif.delays.length == codec.frameCount && + index < gif.delays.length) { + return gif.delays[index]; + } + return StoryGif.frameDelay(decoded); + } + + /// Декодировать первый кадр. Ошибка декодирования — исключение: слайд покажет + /// «Повторить», как у битого фото. + Future start() => _open(++_run); + + /// С первого кадра: новый кодек из тех же байтов. Пока он готовится, виден прежний + /// кадр, а время первого кадра уже идёт — вровень с часами слайда. До первого кадра + /// перезапускать нечего: [start] его и покажет. + Future restart() async { + if (_disposed || _frame == null) return; + final run = ++_run; + _next?.dispose(); + _next = null; + _index = 0; + _left = gif.delays.isEmpty ? StoryGif.shortDelay : gif.delays.first; + try { + await _open(run); + } catch (error) { + debugPrint('StoryGifPlayer: restart — $error'); + } + } + + Future _open(int run) async { + final codec = await codecOf(bytes); + if (run != _run) { + codec.dispose(); + return; + } + _codec?.dispose(); + _codec = codec; + final first = await codec.getNextFrame(); + if (run != _run) { + first.image.dispose(); + return; + } + // После перезапуска время первого кадра уже идёт ([restart]); при старте — с нуля. + final starting = _frame == null; + _show(_fit(first.image), 0); + if (starting) _left = _delay(0, first.duration); + _decodeNext(run); + } + + /// Прошло [delta] времени слайда. + void advance(Duration delta) { + if (_disposed || _frame == null || (_codec?.frameCount ?? 0) < 2) return; + _left -= delta; + _flush(); + } + + /// Время текущего кадра вышло, а следующий готов — показать его. + void _flush() { + final next = _next; + if (next == null || _left > Duration.zero) return; + _next = null; + final index = (_index + 1) % _codec!.frameCount; + _show(next, index); + _left += _delay(index, _nextDuration); + _decodeNext(_run); + } + + void _decodeNext(int run) { + final codec = _codec; + if (codec == null || codec.frameCount < 2) return; + codec.getNextFrame().then( + (frame) { + if (run != _run) { + frame.image.dispose(); + return; + } + _next = _fit(frame.image); + _nextDuration = frame.duration; + _flush(); + }, + onError: (Object error) { + // Кадр не декодировался: GIF стоит на текущем, слайд идёт дальше по часам. + if (run == _run) debugPrint('StoryGifPlayer: frame — $error'); + }, + ); + } + + void _show(ui.Image image, int index) { + final previous = _frame; + _frame = image; + _index = index; + previous?.dispose(); + notifyListeners(); + } + + /// Кадр крупнее [limit] — уменьшенная копия, пропорции те же. + ui.Image _fit(ui.Image image) { + final limit = this.limit; + if (limit == null || limit.isEmpty) return image; + final scale = math.min( + limit.width / image.width, + limit.height / image.height, + ); + if (scale >= 1) return image; + final width = math.max(1, (image.width * scale).round()); + final height = math.max(1, (image.height * scale).round()); + final recorder = ui.PictureRecorder(); + ui.Canvas(recorder).drawImageRect( + image, + ui.Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()), + ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()), + ui.Paint()..filterQuality = ui.FilterQuality.medium, + ); + final picture = recorder.endRecording(); + final small = picture.toImageSync(width, height); + picture.dispose(); + image.dispose(); + return small; + } + + @override + void dispose() { + _disposed = true; + _run++; + _frame?.dispose(); + _frame = null; + _next?.dispose(); + _next = null; + _codec?.dispose(); + _codec = null; + super.dispose(); + } +} diff --git a/lib/src/ui/widgets/stories_image.dart b/lib/src/ui/widgets/stories_image.dart new file mode 100644 index 0000000..2bad4ea --- /dev/null +++ b/lib/src/ui/widgets/stories_image.dart @@ -0,0 +1,193 @@ +import 'dart:async'; +import 'dart:collection'; +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/painting.dart'; + +import 'stories_gif.dart'; + +/// Байты картинок сторис из сети — так же, как их качает [NetworkImage]. Один адрес +/// качается одним запросом: повторный, пока идёт загрузка, ждёт её же. +/// +/// Байты фонов слайдов ([load] с `keep`) ещё и остаются в памяти — несколько последних +/// ([maxEntries], [maxBytes]): возврат на слайд начинает его GIF с первого кадра без +/// новой загрузки, а фото и GIF одного слайда не качаются дважды. Неудача не запоминается. +class StoriesImageBytes { + StoriesImageBytes({ + this.maxEntries = 4, + this.maxBytes = 48 * 1024 * 1024, + Future Function(Uri uri)? fetch, + }) : _fetch = fetch ?? _download; + + /// Загрузчик процесса. Тесты подменяют его. + static StoriesImageBytes instance = StoriesImageBytes(); + + final int maxEntries; + final int maxBytes; + final Future Function(Uri uri) _fetch; + final Map> _loading = >{}; + final Set _keep = {}; + + /// Оставленные байты: последний — самый свежий. + final LinkedHashMap _kept = + LinkedHashMap(); + + // Как у NetworkImage: сжатие снимает consolidateHttpClientResponseBytes. + static final HttpClient _client = HttpClient()..autoUncompress = false; + + static Future _download(Uri uri) async { + final request = await _client.getUrl(uri); + final response = await request.close(); + if (response.statusCode != HttpStatus.ok) { + await response.drain>([]); + throw NetworkImageLoadException( + statusCode: response.statusCode, + uri: uri, + ); + } + final bytes = await consolidateHttpClientResponseBytes(response); + if (bytes.lengthInBytes == 0) { + throw Exception('PersonalizationStories: empty image $uri'); + } + return bytes; + } + + /// Байты [url]: из памяти, из идущей загрузки или скачанные сейчас. [keep] — оставить + /// их в памяти после загрузки (фон слайда). + Future load(String url, {bool keep = false}) { + final kept = _kept.remove(url); + if (kept != null) { + _kept[url] = kept; + return Future.value(kept); + } + if (keep) _keep.add(url); + final loading = _loading[url]; + if (loading != null) return loading; + final future = _fetch(Uri.base.resolve(url)) + .then((bytes) { + if (_keep.remove(url)) _put(url, bytes); + return bytes; + }) + .whenComplete(() { + _loading.remove(url); + _keep.remove(url); + }); + _loading[url] = future; + return future; + } + + /// Забыть байты [url] — «Повторить» качает заново. + void evict(String url) => _kept.remove(url); + + void _put(String url, Uint8List bytes) { + _kept[url] = bytes; + var total = _kept.values.fold(0, (sum, kept) => sum + kept.length); + while (_kept.isNotEmpty && + (_kept.length > maxEntries || total > maxBytes)) { + final oldest = _kept.keys.first; + total -= _kept.remove(oldest)!.length; + } + } +} + +/// Картинка сторис по адресу, когда хост не дал своего провайдера: качается как у +/// [NetworkImage] (через [StoriesImageBytes]), но GIF показывается только первым кадром и +/// не анимируется — так рисуются обложки, превью, постеры видео и картинки товаров. +/// Анимирует GIF только фон слайда ([StoryGifPlayer]). Прочие форматы — как у +/// [NetworkImage]. +@immutable +class StoryImage extends ImageProvider { + const StoryImage(this.url); + + final String url; + + @override + Future obtainKey(ImageConfiguration configuration) => + SynchronousFuture(this); + + @override + ImageStreamCompleter loadImage(StoryImage key, ImageDecoderCallback decode) => + MultiFrameImageStreamCompleter( + codec: _codec(key, decode), + scale: 1, + debugLabel: url, + informationCollector: () => [ + DiagnosticsProperty('Image provider', this), + DiagnosticsProperty('Image key', key), + ], + ); + + Future _codec(StoryImage key, ImageDecoderCallback decode) async { + try { + final bytes = await StoriesImageBytes.instance.load(url); + final codec = await decode(await ui.ImmutableBuffer.fromUint8List(bytes)); + return StoryGif.isGif(bytes) ? firstFrame(codec) : codec; + } catch (_) { + // Как у NetworkImage: неудача не остаётся в кэше — следующий показ грузит заново. + scheduleMicrotask(() => PaintingBinding.instance.imageCache.evict(key)); + rethrow; + } + } + + /// Кодек, у которого из [codec] остаётся один первый кадр. + @visibleForTesting + static ui.Codec firstFrame(ui.Codec codec) => _FirstFrame(codec); + + @override + bool operator ==(Object other) => other is StoryImage && other.url == url; + + @override + int get hashCode => url.hashCode; + + @override + String toString() => '${objectRuntimeType(this, 'StoryImage')}("$url")'; +} + +/// Кодек с одним кадром — первым: GIF стоит на месте. Декодер после первого кадра +/// закрывается — в памяти остаётся только сам кадр. +class _FirstFrame implements ui.Codec { + _FirstFrame(this._codec); + + ui.Codec? _codec; + Future? _first; + + @override + int get frameCount => 1; + + @override + int get repetitionCount => 0; + + @override + Future getNextFrame() async { + final first = await (_first ??= _decodeFirst()); + return _Frame(first.clone()); + } + + Future _decodeFirst() async { + final codec = _codec!; + final frame = await codec.getNextFrame(); + codec.dispose(); + _codec = null; + return frame.image; + } + + @override + void dispose() { + _codec?.dispose(); + _codec = null; + _first?.then((image) => image.dispose(), onError: (Object _) {}); + _first = null; + } +} + +class _Frame implements ui.FrameInfo { + _Frame(this.image); + + @override + final ui.Image image; + + @override + Duration get duration => Duration.zero; +} diff --git a/lib/src/ui/widgets/stories_media_cache.dart b/lib/src/ui/widgets/stories_media_cache.dart new file mode 100644 index 0000000..3744e88 --- /dev/null +++ b/lib/src/ui/widgets/stories_media_cache.dart @@ -0,0 +1,196 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; + +import '../../pigeon/personalization_api.g.dart' as pigeon; + +/// Дисковый кэш видео сторис: LRU на 50 МБ в папке `personalization_stories` кэша +/// приложения, один на процесс — общий для всех просмотров. +/// +/// Видео не ждёт кэша: просмотр берёт готовый файл ([cached]), а нет его — играет по +/// сети и тем временем заполняет кэш в фоне ([fill]); в следующий раз видео идёт из файла. +/// Каждый адрес качается одним потоком: повторный запрос, пока файл ещё качается, ждёт ту +/// же загрузку. Файл сначала пишется во временный `.part` и только целиком +/// переименовывается, поэтому оборванная загрузка в кэш не попадает. Файл больше лимита +/// бросается на первом лишнем байте (тело не дочитывается) и до конца процесса больше не +/// качается. После загрузки самые давно открытые файлы удаляются, пока кэш не уложится в +/// лимит. Без зависимостей: `dart:io`. +class StoriesMediaCache { + StoriesMediaCache({ + this.maxBytes = 50 * 1024 * 1024, + Future Function()? directory, + }) : _directory = directory ?? _platformDirectory; + + /// Кэш процесса. Тесты подменяют его. + static StoriesMediaCache instance = StoriesMediaCache(); + + final int maxBytes; + final Future Function() _directory; + final Map> _downloads = >{}; + + /// Адреса, которые в кэш не помещаются: второй раз их не качаем. + final Set _oversized = {}; + + /// Когда файл открывали в этом процессе. Время изменения файла — отметка для + /// следующих запусков, но система пишет его с точностью до секунды. + final Map _opened = {}; + Future? _root; + + static const String folder = 'personalization_stories'; + + static Future _platformDirectory() async { + String base; + try { + base = await pigeon.PersonalizationHostApi().getCacheDirectory(); + } catch (_) { + base = Directory.systemTemp.path; + } + return Directory('$base/$folder').create(recursive: true); + } + + /// Видео можно положить в кэш файлом: HLS (`.m3u8`) — набор кусков, его плеер + /// грузит сам. + static bool cacheable(String url) { + final path = Uri.tryParse(url)?.path.toLowerCase() ?? ''; + return url.isNotEmpty && !path.endsWith('.m3u8'); + } + + /// Готовый файл [url] из кэша; нет — `null`. Ничего не качает. + Future cached(String url) async { + if (!cacheable(url)) return null; + try { + final file = await _file(url); + if (!await file.exists()) return null; + await _touch(file); + return file; + } catch (error) { + debugPrint('PersonalizationStories: cache lookup $url — $error'); + return null; + } + } + + /// Файл [url] из кэша или загруженный сейчас; `null` — не вышло (тогда плеер берёт + /// адрес из сети). + Future fetch(String url) { + if (!cacheable(url) || _oversized.contains(url)) { + return Future.value(); + } + // Блок, а не стрелка: `remove` вернул бы саму загрузку, и whenComplete ждал бы её + // же — вечно. + return _downloads[url] ??= _fetch(url).whenComplete(() { + _downloads.remove(url); + }); + } + + /// Положить [url] в кэш в фоне — пока видео играет по сети или для следующего слайда. + void fill(String url) => unawaited(fetch(url)); + + /// То же, что [fill]: заранее для следующего слайда. + void preload(String url) => fill(url); + + Future _file(String url) async { + final root = await (_root ??= _directory()); + return File('${root.path}/${_name(url)}'); + } + + /// Отметка для LRU: открытый файл — свежий. + Future _touch(File file) async { + final now = DateTime.now(); + _opened[file.path] = now; + await file.setLastModified(now); + } + + Future _fetch(String url) async { + try { + final file = await _file(url); + if (await file.exists()) { + await _touch(file); + return file; + } + final part = File('${file.path}.part'); + if (!await _download(url, part)) return null; + await part.rename(file.path); + _opened[file.path] = DateTime.now(); + await _trim(file.parent, keep: file.path); + return file; + } catch (error) { + debugPrint('PersonalizationStories: cannot cache $url — $error'); + return null; + } + } + + /// Скачать [url] в [part]. Ответ не 200 или файл больше лимита — `false`, соединение + /// рвётся сразу, без дочитывания тела. + Future _download(String url, File part) async { + final client = HttpClient(); + try { + final request = await client.getUrl(Uri.parse(url)); + final response = await request.close(); + if (response.statusCode != HttpStatus.ok) return false; + if (response.contentLength > maxBytes) { + _oversized.add(url); + return false; + } + final sink = part.openWrite(); + var bytes = 0; + try { + // Длина бывает не известна заранее: считаем байты по ходу. + await for (final chunk in response) { + bytes += chunk.length; + if (bytes > maxBytes) break; + sink.add(chunk); + } + } finally { + await sink.close(); + } + if (bytes <= maxBytes) return true; + _oversized.add(url); + await part.delete(); + return false; + } finally { + // force: недочитанное тело не тянется до конца. + client.close(force: true); + } + } + + /// Удаляет самые давно открытые файлы, пока кэш больше лимита; [keep] не трогается. + Future _trim(Directory root, {required String keep}) async { + final files = <(File, FileStat)>[]; + await for (final entity in root.list()) { + if (entity is File && !entity.path.endsWith('.part')) { + files.add((entity, await entity.stat())); + } + } + var total = files.fold(0, (sum, item) => sum + item.$2.size); + DateTime opened((File, FileStat) item) => + _opened[item.$1.path] ?? item.$2.modified; + files.sort((a, b) => opened(a).compareTo(opened(b))); + for (final (file, stat) in files) { + if (total <= maxBytes) break; + if (file.path == keep) continue; + try { + await file.delete(); + _opened.remove(file.path); + total -= stat.size; + } catch (_) {} + } + } + + /// Имя файла: хэш адреса (FNV-1a, 64 бита) и расширение из пути — по нему AVPlayer + /// узнаёт формат локального файла. + static String _name(String url) { + var hash = 0xcbf29ce484222325; + for (final byte in utf8.encode(url)) { + hash ^= byte; + hash = (hash * 0x100000001b3) & 0xFFFFFFFFFFFFFFFF; + } + final path = Uri.tryParse(url)?.path ?? ''; + final dot = path.lastIndexOf('.'); + final extension = dot >= 0 && path.length - dot <= 5 + ? path.substring(dot).toLowerCase() + : '.mp4'; + return '${hash.toUnsigned(64).toRadixString(16)}$extension'; + } +} diff --git a/lib/src/ui/widgets/stories_playback.dart b/lib/src/ui/widgets/stories_playback.dart new file mode 100644 index 0000000..cef47b9 --- /dev/null +++ b/lib/src/ui/widgets/stories_playback.dart @@ -0,0 +1,393 @@ +import 'dart:async'; + +import '../../stories/stories_response.dart'; + +/// Почему стоит текущий слайд. Часы слайда идут, только когда причин нет. +enum StoriesPauseReason { + /// Палец держат на слайде (удержание от 200 мс). + hold, + + /// Тянут: свайп вниз, листание сторис пальцем или программное перелистывание. + drag, + + /// Раскрыта шторка товаров. + sheet, + + /// Приложение свёрнуто или потеряло фокус, погас экран. + background, + + /// Просмотр закрыт другим экраном. + covered, + + /// Пауза от хоста (`PersonalizationStoriesController.pause`). + host, + + /// Медиа слайда ещё грузится. + loading, + + /// Медиа не загрузилось — на слайде кнопка «Повторить». + error, +} + +/// Что сделать просмотру после шага. +enum StoriesStep { + /// Ничего не поменялось (например, шаг заблокирован шторкой). + none, + + /// Новый заход на слайд текущей сторис — другой. + slide, + + /// Тот же слайд с начала: прогресс с нуля, видео — к началу. Это не новый заход: + /// медиа не перезагружается, `view` и просмотренное не повторяются. + restart, + + /// Перелистнуть страницу на сторис [StoriesPlayback.turnTarget]; заход на неё + /// случится, когда страница осядет ([StoriesPlayback.settle]). + turn, + + /// Закрыть просмотр. + close, +} + +/// Логика просмотра сторис без UI: какая сторис и какой слайд текущие, с какого слайда +/// открывать сторис, почему слайд стоит, открыта ли шторка, сколько прошло времени. +/// +/// Правила (общие для всех платформ): +/// - слайд просмотрен в момент, когда он стал текущим на осевшей странице — не при +/// подглядывании соседней сторис наполовину свайпа ([settle]); +/// - сторис просмотрена, когда так считает сервер (`viewed`) или просмотрены все её +/// слайды ([isViewed]); +/// - сторис открывается: с первого непросмотренного слайда, если часть просмотрена; с +/// `start_position` сервера, если ничего; с начала, если просмотрена вся +/// ([startSlideOf]); +/// - назад на первом слайде первой сторис перезапускает слайд (только время — с нуля, +/// без нового захода), вперёд на последнем слайде последней — закрывает просмотр; +/// - пока раскрыта шторка товаров, слайды и сторис не листаются; любая смена слайда +/// шторку закрывает; +/// - время слайда копится только из реально прошедших промежутков и только пока ничто +/// его не держит — от масштаба анимаций системы оно не зависит. +/// +/// Сторис без слайдов отбрасываются при создании. +class StoriesPlayback { + StoriesPlayback({ + required List stories, + int initialStory = 0, + Map> seen = const >{}, + }) : stories = List.unmodifiable( + stories.where((story) => story.slides.isNotEmpty), + ), + _seen = >{ + for (final entry in seen.entries) entry.key: {...entry.value}, + } { + // Начальный индекс дан по исходному списку: сторис без слайдов перед ним выпали. + var kept = 0; + for (var i = 0; i < stories.length && i < initialStory; i++) { + if (stories[i].slides.isNotEmpty) kept++; + } + _story = this.stories.isEmpty ? 0 : kept.clamp(0, this.stories.length - 1); + } + + /// Сторис со слайдами в порядке ленты. + final List stories; + + final Map> _seen; + final Set _reasons = {}; + late int _story; + int _slide = 0; + int _generation = 0; + bool _entered = false; + bool _sheet = false; + int? _turnTarget; + Duration _elapsed = Duration.zero; + Duration _duration = Duration.zero; + bool _byVideo = false; + + /// Самый длинный промежуток, который часы примут за раз: если кадры не шли (фон, + /// зависание), слайд не проскакивает. + static const Duration maxTick = Duration(seconds: 1); + + bool get isEmpty => stories.isEmpty; + int get storyIndex => _story; + int get slideIndex => _slide; + Story get story => stories[_story]; + StorySlide get slide => story.slides[_slide]; + + /// Номер захода на слайд: растёт при каждом заходе и при «Повторить». Загрузки + /// прошлых заходов по нему отбрасываются. + int get generation => _generation; + + /// Был ли заход хоть на один слайд (первая страница осела). + bool get entered => _entered; + bool get sheetOpen => _sheet; + + /// Часы идут: заход был, и ничто слайд не держит. + bool get running => _entered && _reasons.isEmpty; + Set get reasons => + Set.unmodifiable(_reasons); + bool pausedBy(StoriesPauseReason reason) => _reasons.contains(reason); + + /// Куда листать после [StoriesStep.turn]; `null` — не листаем. + int? get turnTarget => _turnTarget; + + /// Просмотренные слайды сторис [storyId]. + Set seenOf(String storyId) => + Set.unmodifiable(_seen[storyId] ?? const {}); + + /// Сколько прошло на текущем слайде. + Duration get elapsed => _elapsed; + + /// Длительность текущего слайда: из админки, у видео — реальная длина ролика, у GIF — + /// не меньше одного круга ([useGifLoop]). + Duration get duration => _duration; + + /// Слайд длится столько, сколько ролик: конец — по концу видео, а не по часам. + bool get followsVideo => _byVideo; + + /// Доля прошедшего времени слайда, 0…1. + double get progress => _duration <= Duration.zero + ? 0 + : (_elapsed.inMicroseconds / _duration.inMicroseconds).clamp(0.0, 1.0); + + /// Сторис просмотрена: так говорит сервер или просмотрены все её слайды. + static bool isViewed(Story story, Set seen) => + story.viewed || + (story.slides.isNotEmpty && + story.slides.every((slide) => seen.contains(slide.id))); + + /// С какого слайда открыть [story]: просмотрена — с начала; просмотрена частично — + /// с первого непросмотренного по порядку; не начата — с `start_position` сервера. + static int startSlideOf(Story story, Set seen) { + final slides = story.slides; + if (slides.isEmpty || isViewed(story, seen)) return 0; + if (slides.any((slide) => seen.contains(slide.id))) { + final unseen = slides.indexWhere((slide) => !seen.contains(slide.id)); + return unseen < 0 ? 0 : unseen; + } + return story.startPosition.clamp(0, slides.length - 1); + } + + /// Стартовый слайд сторис [index] по текущему состоянию просмотренного. + int startSlideFor(int index) { + final story = stories[index]; + return startSlideOf(story, _seen[story.id] ?? const {}); + } + + /// Страница осела на сторис [index] (листанием, программно или при открытии). + /// `true` — начался заход на её стартовый слайд; та же сторис — `false`, только + /// снимается пауза листания. + bool settle(int index) { + _reasons.remove(StoriesPauseReason.drag); + _turnTarget = null; + if (stories.isEmpty) return false; + final target = index.clamp(0, stories.length - 1); + if (_entered && target == _story) return false; + _story = target; + _slide = startSlideFor(target); + _enter(); + return true; + } + + /// Вперёд: следующий слайд, следующая сторис или закрыть. + StoriesStep next() { + if (!_entered || _sheet || _turnTarget != null) return StoriesStep.none; + if (_slide < story.slides.length - 1) { + _slide++; + _enter(); + return StoriesStep.slide; + } + if (_story < stories.length - 1) { + _turnTo(_story + 1); + return StoriesStep.turn; + } + return StoriesStep.close; + } + + /// Назад: предыдущий слайд, предыдущая сторис или перезапуск первого слайда. + StoriesStep previous() { + if (!_entered || _sheet || _turnTarget != null) return StoriesStep.none; + if (_slide > 0) { + _slide--; + _enter(); + return StoriesStep.slide; + } + if (_story > 0) { + _turnTo(_story - 1); + return StoriesStep.turn; + } + _elapsed = Duration.zero; + return StoriesStep.restart; + } + + /// Перелистнуть на сторис [index] программно (по id из хоста). Та же — `none`. + StoriesStep turnTo(int index) { + if (stories.isEmpty) return StoriesStep.none; + final target = index.clamp(0, stories.length - 1); + if (_entered && target == _story) return StoriesStep.none; + _sheet = false; + _reasons.remove(StoriesPauseReason.sheet); + _turnTo(target); + return StoriesStep.turn; + } + + void _turnTo(int index) { + _turnTarget = index; + _reasons.add(StoriesPauseReason.drag); + } + + /// Поставить на паузу по [reason]. `true` — состояние «идёт» поменялось. + bool pause(StoriesPauseReason reason) { + final was = running; + _reasons.add(reason); + return was != running; + } + + /// Снять паузу по [reason]. `true` — состояние «идёт» поменялось. + bool resume(StoriesPauseReason reason) { + final was = running; + _reasons.remove(reason); + return was != running; + } + + /// Раскрыть шторку товаров: слайд на паузе, листание заблокировано. + bool openSheet() { + if (!_entered || _sheet) return false; + _sheet = true; + _reasons.add(StoriesPauseReason.sheet); + return true; + } + + /// Свернуть шторку товаров. + bool closeSheet() { + if (!_sheet) return false; + _sheet = false; + _reasons.remove(StoriesPauseReason.sheet); + return true; + } + + /// Медиа захода [generation] готово: часы могут идти. + void mediaReady(int generation) { + if (generation != _generation) return; + _reasons + ..remove(StoriesPauseReason.loading) + ..remove(StoriesPauseReason.error); + } + + /// Медиа захода [generation] не загрузилось (или не успело за отведённое время). + void mediaFailed(int generation) { + if (generation != _generation) return; + _reasons + ..remove(StoriesPauseReason.loading) + ..add(StoriesPauseReason.error); + } + + /// «Повторить»: тот же слайд заново грузит медиа. Новый номер захода отбрасывает + /// прошлые загрузки; просмотренным слайд уже отмечен. + int retry() { + _generation++; + _elapsed = Duration.zero; + _duration = slide.duration; + _byVideo = false; + _reasons + ..remove(StoriesPauseReason.error) + ..add(StoriesPauseReason.loading); + return _generation; + } + + /// Реальная длина видео текущего слайда; неизвестная (0) оставляет время админки. + void useVideoDuration(Duration duration) { + if (duration <= Duration.zero) return; + _duration = duration; + _byVideo = true; + } + + /// Длина одного круга GIF текущего слайда: слайд длится время из админки или круг — что + /// дольше; короткий GIF крутится до конца слайда, длинный проходит ровно один круг. + /// Неизвестная длина (`null`: битый GIF, картинка хоста) — время из админки. + void useGifLoop(Duration? loop) { + final server = slide.duration; + _duration = loop != null && loop > server ? loop : server; + } + + /// Позиция видео: время слайда идёт за воспроизведением. + void syncVideoPosition(Duration position) { + if (!_byVideo) return; + _elapsed = position > _duration ? _duration : position; + } + + /// Прошло [delta] реального времени. `true` — слайд кончился по часам (у видео + /// с известной длиной конец даёт само видео). + bool tick(Duration delta) { + if (!running || delta <= Duration.zero) return false; + _elapsed += delta > maxTick ? maxTick : delta; + if (_elapsed < _duration) return false; + _elapsed = _duration; + return !_byVideo; + } + + void _enter() { + _entered = true; + _generation++; + _sheet = false; + _elapsed = Duration.zero; + _duration = slide.duration; + _byVideo = false; + _reasons + ..remove(StoriesPauseReason.sheet) + ..remove(StoriesPauseReason.error) + ..add(StoriesPauseReason.loading); + (_seen[story.id] ??= {}).add(slide.id); + } +} + +/// Таймер просмотра, который замирает: пока приложение в фоне или просмотр закрыт другим +/// экраном, время не идёт, а после возврата досчитывается остаток ([freeze], [resume]). +/// +/// Считает шагами по [step] — так он идёт и на подменённых часах тестов; на заморозке +/// теряется не больше шага. +class StoriesTimer { + /// Через [duration] — [onFire]; [frozen] — создать замороженным. + StoriesTimer(Duration duration, void Function() onFire, {bool frozen = false}) + : _left = duration, + _onFire = onFire { + if (!frozen) _run(); + } + + static const Duration step = Duration(milliseconds: 100); + + final void Function() _onFire; + Duration _left; + Timer? _timer; + bool _done = false; + + /// Сколько осталось. + Duration get remaining => _left; + + /// Таймер ещё не сработал и не отменён. + bool get isActive => !_done; + + /// Остановить отсчёт, сохранив остаток. + void freeze() { + _timer?.cancel(); + _timer = null; + } + + /// Продолжить отсчёт с остатка. + void resume() { + if (_done || _timer != null) return; + _run(); + } + + void cancel() { + _done = true; + freeze(); + } + + void _run() { + _timer = Timer.periodic(step, (_) { + _left -= step; + if (_left > Duration.zero) return; + cancel(); + _onFire(); + }); + } +} diff --git a/lib/src/ui/widgets/stories_seen_store.dart b/lib/src/ui/widgets/stories_seen_store.dart new file mode 100644 index 0000000..5b720bb --- /dev/null +++ b/lib/src/ui/widgets/stories_seen_store.dart @@ -0,0 +1,69 @@ +import 'package:flutter/foundation.dart'; + +import '../../multi_instance/rees46.dart'; +import '../../personalization_sdk.dart'; + +/// Просмотренные слайды сторис по магазину: id слайдов по id сторис. +/// +/// Хранит их плагин на устройстве (SharedPreferences / UserDefaults) — между запусками +/// приложения. Здесь — копия на процесс: магазин читается с устройства один раз, дальше +/// все просмотры и ленты одного магазина видят одно состояние, а каждая отметка сразу +/// уходит и в хранилище. Хранилище недоступно (тесты, ошибка канала) — состояние живёт +/// только в памяти. +class StoriesSeenStore { + /// Хранилище процесса. Тесты подменяют его. + static StoriesSeenStore instance = StoriesSeenStore(); + + final Map>> _byShop = + >>{}; + final Map> _loads = >{}; + + /// Ключ магазина: его shopId; у хэндла без него — единственный живой магазин. + 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 : ''; + } + + /// Просмотренное магазина [sdk] — после первого чтения с устройства. + Future>> load(PersonalizationSdk sdk) async { + final shop = shopOf(sdk); + await (_loads[shop] ??= _read(sdk, shop)); + return seen(sdk); + } + + Future _read(PersonalizationSdk sdk, String shop) async { + final current = _byShop.putIfAbsent(shop, () => >{}); + // Разбор тоже под try: кривые данные хранилища не должны ронять ленту. + try { + final stored = await sdk.getStoriesSeen(shop); + for (final entry in stored.entries) { + (current[entry.key] ??= {}).addAll(entry.value); + } + } catch (error) { + debugPrint('PersonalizationStories: seen slides unavailable — $error'); + } + } + + /// Что известно сейчас, без чтения с устройства. + Map> seen(PersonalizationSdk sdk) => + >{ + for (final entry + in (_byShop[shopOf(sdk)] ?? const >{}).entries) + entry.key: Set.unmodifiable(entry.value), + }; + + /// Слайд [slideId] сторис [storyId] просмотрен. + void mark(PersonalizationSdk sdk, String storyId, String slideId) { + final shop = shopOf(sdk); + final slides = (_byShop.putIfAbsent( + shop, + () => >{}, + )[storyId] ??= {}); + if (!slides.add(slideId)) return; + sdk.setStorySlideSeen(shop, storyId, slideId).catchError((Object error) { + debugPrint('PersonalizationStories: cannot store a seen slide — $error'); + }); + } +} diff --git a/lib/src/ui/widgets/stories_slide_view.dart b/lib/src/ui/widgets/stories_slide_view.dart new file mode 100644 index 0000000..a105698 --- /dev/null +++ b/lib/src/ui/widgets/stories_slide_view.dart @@ -0,0 +1,531 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:video_player/video_player.dart'; + +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_price.dart'; +import '../components/personalization_story_sound_button.dart'; +import '../components/personalization_story_used_products.dart'; +import '../components/personalization_toast.dart'; +import '../personalization_colors.dart'; +import '../personalization_theme.dart'; +import 'personalization_story_viewer.dart'; +import 'stories_gif_player.dart'; +import 'stories_support.dart'; + +/// Один слайд просмотра сторис: фон, затемнение, содержимое, касания. +/// +/// - Фото и видео вписываются целиком (contain), поля — `background_color` слайда, без +/// него чёрные; такой слайд всегда в тёмных токенах кита. Слайд без медиа — на +/// Background/Card темы приложения, цвет админки не берётся. +/// - Затемнение сверху и снизу на каждом слайде: 50% у голого медиа, иначе 30% +/// ([storyScrimOpacity]), до прозрачного к 21% и от 86% высоты. +/// - Товарный слайд — карточка товара кита, все кнопки слайда (Primary LG друг под +/// другом), «Используемые товары» и звук у видео; текстовые блоки на нём не рисуются, +/// но промокод текстового блока, если у товара своего нет, показывает блок цены. +/// - Медиа-слайд — непустые текстовые блоки на `y_offset`% высоты, кнопки внизу, +/// «Используемые товары», звук у видео. +/// - GIF фона живого слайда рисует [StoryGifPlayer]; у соседних страниц и до готовности +/// — первый кадр. +/// - Медиа не загрузилось — по центру кнопка кита [PersonalizationStoryViewer.retryText]. +/// +/// Живой ([live]) — только текущий слайд осевшей страницы: у него часы, видео, касания и +/// шторка. Соседние страницы показывают свой стартовый слайд неподвижно. +class StorySlideView extends StatelessWidget { + const StorySlideView({ + super.key, + required this.story, + required this.slideIndex, + required this.config, + this.live = false, + this.generation = 0, + this.progress, + this.video, + this.gif, + this.muted = true, + this.sheetOpen = false, + this.failed = false, + this.onTap, + this.onHold, + this.onClose, + this.onToggleMute, + this.onSheet, + this.onButton, + this.onProduct, + this.onPromoCopied, + this.onRetry, + }); + + final Story story; + final int slideIndex; + + /// Тексты, картинки и иконки — из просмотра. + final PersonalizationStoryViewer config; + final bool live; + + /// Номер захода: картинка фона пересоздаётся на каждый — без кадра прошлого слайда. + final int generation; + final ValueListenable? progress; + + /// Готовое видео живого слайда; `null` — постер. + final VideoPlayerController? video; + + /// GIF живого слайда; с кадром — рисуется он, иначе картинка по адресу (у GIF — его + /// первый кадр). + final StoryGifPlayer? gif; + final bool muted; + final bool sheetOpen; + final bool failed; + + /// Касание по горизонтали [dx] при ширине [width]. + final void Function(double dx, double width)? onTap; + final ValueChanged? onHold; + final VoidCallback? onClose; + final VoidCallback? onToggleMute; + final ValueChanged? onSheet; + final ValueChanged? onButton; + final ValueChanged? onProduct; + final ValueChanged? onPromoCopied; + final VoidCallback? onRetry; + + /// Удержание дольше этого — пауза, а не касание. + static const Duration holdDelay = Duration(milliseconds: 200); + + StorySlide get slide => story.slides[slideIndex]; + + @override + Widget build(BuildContext context) { + final slide = this.slide; + final media = storyMediaOf(slide) != StoryMedia.none; + final base = Theme.of(context); + return Theme( + data: media ? _mediaTheme(base) : base, + child: Builder(builder: (context) => _body(context, slide, media)), + ); + } + + /// Тема слайдов с медиа: тёмные токены кита. Тема хоста уже тёмная — берётся она, + /// иначе тёмный набор кита с брендом, радиусами и шрифтом хоста. + static ThemeData _mediaTheme(ThemeData base) { + final host = base.extension(); + final PersonalizationTheme dark; + if (host != null && base.brightness == Brightness.dark) { + dark = host; + } else { + final source = host ?? PersonalizationTheme.light; + final brand = source.colors; + dark = PersonalizationTheme.dark.copyWith( + radius: source.radius, + fontFamily: source.fontFamily, + colors: PersonalizationColors.dark.copyWith( + brandPrimary: brand.brandPrimary, + buttonPrimary: brand.buttonPrimary, + buttonPrimaryDisabled: brand.buttonPrimaryDisabled, + lineBrand: brand.lineBrand, + textBrand: brand.textBrand, + ), + ); + } + return base.copyWith( + extensions: [ + for (final extension in base.extensions.values) + if (extension is! PersonalizationTheme) extension, + dark, + ], + ); + } + + Widget _body(BuildContext context, StorySlide slide, bool media) { + final colors = PersonalizationTheme.of(context).colors; + final light = colors.textPrimary.computeLuminance() > 0.5; + final product = storyProductElement(slide); + final content = SafeArea( + child: product != null + ? _productContent(context, slide, product) + : _mediaContent(context, slide), + ); + return AnnotatedRegion( + value: light ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark, + child: LayoutBuilder( + builder: (context, constraints) => _gestures( + width: constraints.maxWidth, + child: ColoredBox( + color: media ? storyLetterbox(slide) : colors.backgroundCard, + child: Stack( + fit: StackFit.expand, + children: [ + if (media) _background(slide), + _scrim(slide), + content, + if (failed) Center(child: _retryButton()), + ], + ), + ), + ), + ), + ); + } + + /// Касания по третям и удержание от 200 мс; у неживой страницы — никаких. + Widget _gestures({required double width, required Widget child}) { + if (!live) return child; + 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)); + }, + ), + }, + child: child, + ); + } + + Widget _background(StorySlide slide) { + final video = this.video; + if (video != null && video.value.isInitialized) { + final size = video.value.size; + return FittedBox( + fit: BoxFit.contain, + child: SizedBox( + width: size.width, + height: size.height, + child: VideoPlayer(video), + ), + ); + } + final gif = this.gif; + if (gif != null && gif.frame != null) { + // Кадры GIF меняет проигрыватель — перерисовывается только картинка. + return ListenableBuilder( + listenable: gif, + builder: (context, _) => + RawImage(image: gif.frame, fit: BoxFit.contain), + ); + } + final url = storyMediaOf(slide) == StoryMedia.video + ? slide.preview + : slide.background; + final image = storyImage(url, config.imageProvider); + if (image == null) return const SizedBox.shrink(); + // Своя картинка на каждый заход: без gaplessPlayback под текстом нового слайда не + // остаётся фото прошлого. + return Image( + key: ValueKey('${slide.id}-$generation'), + image: image, + fit: BoxFit.contain, + errorBuilder: (context, error, stackTrace) => const SizedBox.shrink(), + ); + } + + Widget _scrim(StorySlide slide) { + final shade = const Color( + 0xFF000000, + ).withValues(alpha: storyScrimOpacity(slide)); + const clear = Color(0x00000000); + return IgnorePointer( + child: DecoratedBox( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [shade, clear, clear, shade], + stops: const [0, 0.21, 0.86, 1], + ), + ), + ), + ); + } + + Widget _retryButton() => PersonalizationButton( + label: config.retryText, + size: PersonalizationButtonSize.md, + iconBuilder: config.iconBuilder, + onPressed: onRetry, + ); + + Widget _navigation() { + Widget header(double value) => PersonalizationStoryNavigation( + count: story.slides.length, + current: slideIndex, + progress: value, + onClose: onClose, + closeLabel: config.closeLabel, + iconBuilder: config.iconBuilder, + ); + final progress = this.progress; + if (progress == null) return header(0); + return ValueListenableBuilder( + valueListenable: progress, + builder: (context, value, _) => header(value), + ); + } + + /// Шапка поверх всего слайда, и подложки шторки тоже: крестик закрывает просмотр и + /// при раскрытой шторке; мимо крестика касание доходит до подложки. + Widget _header() => + Positioned(left: 16, top: 16, right: 16, child: _navigation()); + + /// Кнопка звука — только у видео. + Widget? _sound(StorySlide slide) { + if (storyMediaOf(slide) != StoryMedia.video) return null; + return PersonalizationStorySoundButton( + muted: muted, + onPressed: onToggleMute, + soundOnLabel: config.soundOnLabel, + soundOffLabel: config.soundOffLabel, + iconBuilder: config.iconBuilder, + ); + } + + // --- Содержимое --------------------------------------------------------------------- + + Widget _primaryButtons(List buttons) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final button in buttons) + Padding( + padding: const EdgeInsets.only(top: 16), + child: PersonalizationButton( + label: button.title, + iconBuilder: config.iconBuilder, + onPressed: live ? () => onButton?.call(button) : null, + ), + ), + ], + ); + + /// Нижняя строка: «Используемые товары» со звуком в начале или только звук. Под + /// раскрытой шторкой — подложка: тап мимо шторки её закрывает и никуда не листает; + /// крестик шапки над ней и закрывает просмотр. + List _bottomRow(StorySlide slide) { + final products = storyProducts(slide); + final sound = _sound(slide); + if (products == null && sound == null) return const []; + final Widget row; + if (products == null) { + row = SizedBox( + height: 64, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: sound, + ), + ), + ); + } else { + final byId = { + for (final product in products.products) product.id: product, + }; + row = PersonalizationStoryUsedProducts( + products: [ + for (final product in products.products) + storyCardProduct(product, config.imageProvider), + ], + showText: products.showLabel.isNotEmpty + ? products.showLabel + : config.showProductsText, + hideText: products.hideLabel.isNotEmpty + ? products.hideLabel + : config.hideProductsText, + expanded: sheetOpen, + onExpandedChanged: live ? onSheet : null, + onProductTap: (card) { + final product = byId[card.id]; + if (live && product != null) onProduct?.call(product); + }, + leading: sound, + iconBuilder: config.iconBuilder, + ); + } + return [ + if (sheetOpen) + Positioned.fill( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => onSheet?.call(false), + onLongPress: () {}, + onVerticalDragStart: (_) {}, + onHorizontalDragStart: (_) {}, + ), + ), + Positioned(left: 0, right: 0, bottom: 0, child: row), + ]; + } + + bool _hasRow(StorySlide slide) => + storyProducts(slide) != null || _sound(slide) != null; + + 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, + child: _textBlock(context, text), + ), + Positioned( + left: 16, + right: 16, + bottom: _hasRow(slide) ? 64 : 16, + child: _primaryButtons(buttons), + ), + ..._bottomRow(slide), + _header(), + ], + ), + ); + } + + Widget _textBlock(BuildContext context, StoryTextBlockElement element) { + final block = storyTextBlock(element); + final code = element.promocode; + if (code == null || !live) return block; + // Блок с промокодом копирует его: тост сверху и `click` в трекинг. + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + Clipboard.setData(ClipboardData(text: code)); + PersonalizationToast.show( + context, + config.promoCopiedText, + position: PersonalizationToastPosition.top, + ); + onPromoCopied?.call(code); + }, + child: block, + ); + } + + /// Товарный слайд: шапка (бренд SemiBold 20, название SemiBold 16, межстрочный 140%, + /// шаг 8), белая карточка картинки (скругление 12, поля 16, квадрат по ширине — на + /// низком экране ужимается), цена, кнопки слайда; без своих кнопок — одна + /// [PersonalizationStoryViewer.productButtonText], ведёт к товару. Товар открывают + /// только кнопки: шапка и картинка не нажимаются, касание по ним листает, как по слайду. + Widget _productContent( + BuildContext context, + StorySlide slide, + StoryProductElement element, + ) { + final product = element.item!; + final theme = PersonalizationTheme.of(context); + final colors = theme.colors; + // Промокод текстового блока слайда идёт в блок цены: сам блок здесь не рисуется. + final price = storyPriceOf(product, slidePromo: storySlidePromocode(slide)); + final image = storyImage(product.image, config.imageProvider); + final buttons = storyButtons(slide); + + TextStyle header(double size) => TextStyle( + fontSize: size, + height: 1.4, + fontWeight: FontWeight.w600, + letterSpacing: 0, + fontFamily: theme.fontFamily.familyFor(FontWeight.w600), + package: theme.fontFamily.package, + color: colors.textPrimary, + ); + + final column = Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, _hasRow(slide) ? 64 : 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Место шапки: сама она поверх всего ([_header]). + const SizedBox(height: PersonalizationStoryNavigation.height), + const SizedBox(height: 16), + if (product.brand.isNotEmpty) ...[ + Text( + product.brand, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: header(20), + ), + const SizedBox(height: 8), + ], + Text( + product.name, + maxLines: 4, + overflow: TextOverflow.ellipsis, + style: header(16), + ), + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + // Картинка не нажимается: касание по ней — касание слайда (листает по + // третям, удержание — пауза). + child: Center( + child: AspectRatio( + aspectRatio: 1, + child: DecoratedBox( + decoration: BoxDecoration( + color: const Color(0xFFFFFFFF), + borderRadius: BorderRadius.circular(12), + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: image == null + ? null + : Image(image: image, fit: BoxFit.contain), + ), + ), + ), + ), + ), + ), + PersonalizationStoryPrice( + type: price.type, + price: price.price, + oldPrice: price.oldPrice, + discount: price.discount, + promoCode: price.promoCode, + promoCaption: storyPromoCaption(element, config.promoCaption), + copiedText: config.promoCopiedText, + onPromoCopied: live ? onPromoCopied : null, + iconBuilder: config.iconBuilder, + ), + if (buttons.isNotEmpty) + _primaryButtons(buttons) + else + Padding( + padding: const EdgeInsets.only(top: 16), + child: PersonalizationButton( + label: config.productButtonText, + iconBuilder: config.iconBuilder, + onPressed: live ? () => onProduct?.call(product) : null, + ), + ), + ], + ), + ); + return Stack( + fit: StackFit.expand, + children: [column, ..._bottomRow(slide), _header()], + ); + } +} diff --git a/lib/src/ui/widgets/stories_sound.dart b/lib/src/ui/widgets/stories_sound.dart new file mode 100644 index 0000000..d8367bb --- /dev/null +++ b/lib/src/ui/widgets/stories_sound.dart @@ -0,0 +1,89 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import '../../pigeon/personalization_api.g.dart' as pigeon; + +/// Звук сторис на весь процесс. +/// +/// - При первом открытии звук выключен; выбор пользователя помнится до конца процесса и +/// переходит на следующие открытия ([muted]). +/// - Кнопка громкости «вверх» включает звук: на Android клавиша сама доходит до +/// Flutter ([HardwareKeyboard]), на iOS плагин следит за громкостью аудиосессии и +/// сообщает о росте через `PersonalizationStoriesFlutterApi`. +/// - iOS: пока идёт видео, сессия `ambient` без звука (музыка пользователя не +/// прерывается) и `playback` со звуком; при закрытии просмотра возвращается сессия +/// приложения. Android: видео играет с `mixWithOthers` и фокус не забирает. +class StoriesSound implements pigeon.PersonalizationStoriesFlutterApi { + StoriesSound._(); + + static final StoriesSound instance = StoriesSound._(); + + /// Хост-API плагина. Тесты подменяют его. + @visibleForTesting + static pigeon.PersonalizationHostApi api = pigeon.PersonalizationHostApi(); + + /// Звук выключен. Общий для всех просмотров процесса. + final ValueNotifier muted = ValueNotifier(true); + + int _viewers = 0; + bool _session = false; + + /// Просмотр открылся: слушать кнопку громкости. + void attach() { + if (_viewers++ > 0) return; + HardwareKeyboard.instance.addHandler(_onKey); + pigeon.PersonalizationStoriesFlutterApi.setUp(this); + muted.addListener(_apply); + } + + /// Просмотр закрылся. Последний — вернуть сессию приложения. + void detach() { + if (_viewers == 0 || --_viewers > 0) return; + HardwareKeyboard.instance.removeHandler(_onKey); + pigeon.PersonalizationStoriesFlutterApi.setUp(null); + muted.removeListener(_apply); + if (_session) { + _session = false; + _call(api.endStoriesAudio); + } + } + + /// Перед созданием первого плеера: запомнить сессию приложения (iOS). + Future beforeVideo() async { + if (_session) return; + _session = true; + await _call(api.beginStoriesAudio); + } + + /// После готовности плеера: сессия по [muted] (iOS). Плеер при создании сам трогает + /// категорию, поэтому — после каждого. + Future afterVideo() => _session + ? _call(() => api.updateStoriesAudio(muted.value)) + : Future.value(); + + void toggle() => muted.value = !muted.value; + + @override + void onStoriesVolumeUp() => muted.value = false; + + bool _onKey(KeyEvent event) { + if (event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.audioVolumeUp) { + muted.value = false; + } + // Клавиша идёт дальше: громкость системы меняется как обычно. + return false; + } + + void _apply() { + if (_session) _call(() => api.updateStoriesAudio(muted.value)); + } + + static Future _call(Future Function() body) async { + try { + await body(); + } catch (error) { + debugPrint('PersonalizationStories: audio session — $error'); + } + } +} diff --git a/lib/src/ui/widgets/stories_support.dart b/lib/src/ui/widgets/stories_support.dart new file mode 100644 index 0000000..4d56365 --- /dev/null +++ b/lib/src/ui/widgets/stories_support.dart @@ -0,0 +1,317 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +import '../../stories/stories_response.dart'; +import '../components/personalization_product.dart'; +import '../components/personalization_story_price.dart'; +import '../components/personalization_story_text_block.dart'; +import 'stories_image.dart'; + +/// Как получить картинку по адресу из данных сторис. Не задан — свой загрузчик SDK: качает +/// как [NetworkImage], GIF анимирует только на фоне слайда и по нему же меряет длину +/// слайда, а обложки, превью, постеры и картинки товаров показывает первым кадром. Хост +/// подставляет свой провайдер, например с кэшем, — тогда GIF им и рисуется: SDK его не +/// анимирует, не останавливает и не меряет, слайд длится время из админки. +typedef PersonalizationStoryImageProvider = ImageProvider Function(String url); + +/// Картинка по адресу — провайдер хоста или [StoryImage] (GIF — первым кадром); пустой +/// адрес — `null`. +ImageProvider? storyImage( + String url, + PersonalizationStoryImageProvider? custom, +) { + if (url.isEmpty) return null; + return custom?.call(url) ?? StoryImage(url); +} + +/// Цвет из `#RRGGBB`, `#RGB` или `#AARRGGBB`; не разобрать — `null`. +Color? parseStoryColor(String value, {double opacity = 1}) { + var hex = value.trim(); + if (hex.startsWith('#')) hex = hex.substring(1); + if (hex.length == 3) hex = hex.split('').map((c) => '$c$c').join(); + if (hex.length == 6) hex = 'FF$hex'; + if (hex.length != 8) return null; + final argb = int.tryParse(hex, radix: 16); + if (argb == null) return null; + final color = Color(argb); + return color.withValues(alpha: color.a * opacity.clamp(0, 1)); +} + +/// Что слайд показывает фоном. +enum StoryMedia { + /// Ничего: фон Background/Card темы приложения. + none, + + /// Фото. + image, + + /// Видео; постер — `preview`. + video, +} + +/// Медиа слайда решает непустой `background`, а не тип слайда: товарный слайд с фото — +/// тоже медиа-слайд, а `image` без адреса — нет. +StoryMedia storyMediaOf(StorySlide slide) { + if (slide.background.trim().isEmpty) return StoryMedia.none; + return slide.type == StorySlideType.video + ? StoryMedia.video + : StoryMedia.image; +} + +/// Цвет полей вокруг вписанного медиа: `background_color` слайда, без него чёрный. Это +/// единственное место, где цвет админки идёт в дело: слайд без медиа всегда на +/// Background/Card. +Color storyLetterbox(StorySlide slide) => + parseStoryColor(slide.backgroundColor) ?? const Color(0xFF000000); + +/// Текстовые блоки, которые рисуются: пустые и из одних пробелов пропускаются. +List storyTextBlocks(StorySlide slide) => + [ + for (final element in slide.elements) + if (element is StoryTextBlockElement && element.text.trim().isNotEmpty) + element, + ]; + +/// Кнопки слайда с подписью — по порядку. +List storyButtons(StorySlide slide) => [ + for (final element in slide.elements) + if (element is StoryButtonElement && element.title.trim().isNotEmpty) + element, +]; + +/// Элемент товара товарного слайда (с самим товаром); нет — `null`. +StoryProductElement? storyProductElement(StorySlide slide) { + for (final element in slide.elements) { + if (element is StoryProductElement && element.item != null) return element; + } + return null; +} + +/// Элемент «Используемые товары» с непустым списком; нет — `null`. +StoryProductsElement? storyProducts(StorySlide slide) { + for (final element in slide.elements) { + if (element is StoryProductsElement && element.products.isNotEmpty) { + return element; + } + } + return null; +} + +/// Плотность затемнения сверху и снизу. Оно есть на каждом слайде: 50% — только у +/// медиа без товара и без непустых текстов (голое фото или видео), иначе 30%. +double storyScrimOpacity(StorySlide slide) => + storyMediaOf(slide) != StoryMedia.none && + storyProductElement(slide) == null && + storyTextBlocks(slide).isEmpty + ? 0.5 + : 0.3; + +/// Трекается ли id: только целые положительные числа. Динамические слайды (`39_0`) API +/// трекинга не принимает — они пропускаются молча на всех платформах. +bool storyTrackableId(String id) { + final trimmed = id.trim(); + if (!RegExp(r'^\d+$').hasMatch(trimmed)) return false; + final number = int.tryParse(trimmed); + return number != null && number > 0; +} + +/// Процент без лишних нулей: `10` → «10%», `12.5` → «12.5%». +String storyPercent(double value) { + final text = value == value.roundToDouble() + ? value.toStringAsFixed(0) + : value.toString(); + return '$text%'; +} + +/// Промокод текстового блока слайда для блока цены товара: код первого текстового блока, +/// где он не пустой. Пробелы и строка «null» — не код. На товарном слайде сами блоки не +/// рисуются, а их код показывает карточка товара, как в макете ([storyPriceOf]). +String? storySlidePromocode(StorySlide slide) { + for (final element in slide.elements) { + if (element is! StoryTextBlockElement) continue; + final code = element.promocode?.trim() ?? ''; + if (code.isNotEmpty && code != 'null') return code; + } + return null; +} + +/// Цена товара для [PersonalizationStoryPrice]: вид блока и его строки. +/// +/// - Промокод товара — вид promoCode: крупно цена с промокодом +/// (`price_with_promocode_formatted`, без неё обычная); зачёркнута старая цена, если +/// она есть, иначе обычная цена, если она отличается от цены с промокодом. +/// - Иначе промокод текстового блока слайда ([slidePromo], см. [storySlidePromocode]) — +/// тоже вид promoCode, но крупно обычная цена: цена с промокодом относится только к +/// промокоду товара. Зачёркнута только старая цена, если она есть. +/// - Иначе скидка больше нуля — вид discount с процентом `discount_percent` (дробный +/// остаётся дробным: «12.5%»). +/// - Иначе просто цена. +/// +/// Старая цена показывается, только если она численно больше цены; числа читаются +/// десятичными, не целыми. +({ + PersonalizationStoryPriceType type, + String price, + String? oldPrice, + String? discount, + String? promoCode, +}) +storyPriceOf(StoryProduct product, {String? slidePromo}) { + final regular = product.priceFormatted.isNotEmpty + ? product.priceFormatted + : _plainPrice(product); + final oldPrice = product.hasOldPrice ? product.oldPriceFormatted : null; + if (product.promocode.isNotEmpty) { + final promoPrice = product.priceWithPromocodeFormatted.isNotEmpty + ? product.priceWithPromocodeFormatted + : regular; + // Числом сравниваем, когда сервер прислал цену с промокодом числом; иначе — текстом. + final cheaper = product.priceWithPromocode > 0 + ? product.price > product.priceWithPromocode + : promoPrice != regular; + return ( + type: PersonalizationStoryPriceType.promoCode, + price: promoPrice, + oldPrice: oldPrice ?? (cheaper ? regular : null), + discount: null, + promoCode: product.promocode, + ); + } + if (slidePromo != null && slidePromo.isNotEmpty) { + return ( + type: PersonalizationStoryPriceType.promoCode, + price: regular, + oldPrice: oldPrice, + discount: null, + promoCode: slidePromo, + ); + } + if (product.discountPercent > 0) { + return ( + type: PersonalizationStoryPriceType.discount, + price: regular, + oldPrice: oldPrice, + discount: storyPercent(product.discountPercent), + promoCode: null, + ); + } + return ( + type: PersonalizationStoryPriceType.price, + price: regular, + oldPrice: oldPrice, + discount: null, + promoCode: null, + ); +} + +String _plainPrice(StoryProduct product) { + final amount = product.price == product.price.roundToDouble() + ? product.price.toStringAsFixed(0) + : product.price.toString(); + return '$amount ${product.currency}'.trim(); +} + +/// Подпись над промокодом: `title` элемента товара из админки; пустой — текст хоста. +String storyPromoCaption(StoryProductElement? element, String fallback) { + final title = element?.title.trim() ?? ''; + return title.isNotEmpty ? title : fallback; +} + +/// Товар сторис → данные карточки кита для карусели товаров слайда. +PersonalizationProduct storyCardProduct( + StoryProduct product, + PersonalizationStoryImageProvider? image, +) { + final hasOldPrice = product.hasOldPrice; + return PersonalizationProduct( + id: product.id, + name: product.name, + price: product.priceFormatted.isNotEmpty + ? product.priceFormatted + : _plainPrice(product), + image: storyImage(product.image, image), + brand: product.brand.isEmpty ? null : product.brand, + oldPrice: hasOldPrice ? product.oldPriceFormatted : null, + discount: hasOldPrice && product.discountPercent > 0 + ? '-${storyPercent(product.discountPercent)}' + : null, + ); +} + +/// Ссылка кнопки для текущей платформы: своя, иначе общая `link`. +String storyButtonLink(StoryButtonElement button) { + final own = switch (defaultTargetPlatform) { + TargetPlatform.android => button.linkAndroid, + TargetPlatform.iOS => button.linkIos, + _ => '', + }; + return own.isNotEmpty ? own : button.link; +} + +/// Ссылка товара для текущей платформы: диплинк, иначе `url`. +String storyProductLink(StoryProduct product) { + final own = switch (defaultTargetPlatform) { + TargetPlatform.android => product.deeplinkAndroid, + TargetPlatform.iOS => product.deeplinkIos, + _ => '', + }; + return own.isNotEmpty ? own : product.url; +} + +/// Куда ведёт кнопка товарного слайда: своя ссылка кнопки (платформенная, затем общая), +/// без неё — товар слайда (диплинк, затем `url`). +String storySlideButtonLink(StoryButtonElement button, StoryProduct? product) { + final own = storyButtonLink(button); + if (own.isNotEmpty || product == null) return own; + return storyProductLink(product); +} + +/// Выключка текстового блока: `left`/`start` — к началу строки, `center` — по центру, +/// `right`/`end` — к концу (для RTL зеркально). +TextAlign storyTextAlign(String value) => switch (value.trim().toLowerCase()) { + 'center' => TextAlign.center, + 'right' || 'end' => TextAlign.end, + _ => TextAlign.start, +}; + +/// Текстовый блок сервера → [PersonalizationStoryTextBlock]. +/// +/// Шрифт `serif` / `monospaced` — системные семейства с запасными для iOS, где имён +/// `serif` и `monospace` нет; `sans-serif` и пусто — шрифт темы. Межстрочный не задан — +/// заготовка макета для этого кегля ([PersonalizationStoryTextBlock.presetLineHeight]). +PersonalizationStoryTextBlock storyTextBlock(StoryTextBlockElement element) { + final (family, fallback) = switch (element.fontType) { + 'serif' => ('serif', const ['Georgia', 'Times New Roman']), + 'monospaced' => ('monospace', const ['Menlo', 'Courier']), + _ => (null, null), + }; + return PersonalizationStoryTextBlock( + text: element.text, + fontSize: element.fontSize, + lineHeight: element.lineSpacing > 0 + ? element.lineSpacing + : PersonalizationStoryTextBlock.presetLineHeight(element.fontSize), + color: parseStoryColor(element.textColor), + background: element.backgroundOpacity > 0 + ? parseStoryColor( + element.backgroundColor, + opacity: element.backgroundOpacity, + ) + : null, + textAlign: storyTextAlign(element.textAlign), + bold: element.bold, + italic: element.italic, + fontFamily: family, + fontFamilyFallback: fallback, + ); +} + +/// Сторис, которые можно показать: со слайдами (C16) и без повторов id — сервер иногда +/// отдаёт одну сторис дважды; остаётся первая, иначе просмотренность по id склеивается. +List playableStories(Iterable stories) { + final ids = {}; + return [ + for (final story in stories) + if (story.slides.isNotEmpty && ids.add(story.id)) story, + ]; +} diff --git a/pigeons/personalization_api.dart b/pigeons/personalization_api.dart index 9fa53ff..0cd0de3 100644 --- a/pigeons/personalization_api.dart +++ b/pigeons/personalization_api.dart @@ -315,6 +315,47 @@ abstract class PersonalizationHostApi { @async String getCollection(String collectionId, String? shopId); + /// Returns the stories block [code] (`stories/{code}`) as the server's JSON string, + /// untouched: `{ "id": ..., "stories": [...], "settings": {...} }`. Both platforms hand + /// over the same raw payload, so Dart parses one shape. + /// Dart layer parses the result into [StoriesBlock]. + @async + String getStories(String code, String? shopId); + + /// Opens [url] with the system handler (browser or the app that claims the link). + /// Returns false when nothing could open it. + @async + bool openUrl(String url); + + /// 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 + /// hands nested lists over as `List`, and a typed `List` here + /// generates a lazy cast that throws on the first read. + Map> getStoriesSeen(String shop); + + /// Records [slideId] of story [storyId] as seen for [shop]. + void setStorySlideSeen(String shop, String storyId, String slideId); + + /// The app's cache directory: Android `Context.cacheDir`, iOS `Library/Caches`. The + /// stories viewer keeps its video cache under it. + String getCacheDirectory(); + + /// Remembers the app's audio session before the stories viewer plays its first video, + /// so [endStoriesAudio] can put it back. iOS only; a no-op on Android, where a muted + /// video never takes the audio focus (`mixWithOthers`). + void beginStoriesAudio(); + + /// While the viewer plays video: muted — the `ambient` category, which never + /// interrupts other apps' audio; unmuted — `playback`. Also starts watching the + /// hardware volume (see [PersonalizationStoriesFlutterApi.onStoriesVolumeUp]). iOS + /// only; a no-op on Android. + void updateStoriesAudio(bool muted); + + /// The viewer closed: restores the session saved by [beginStoriesAudio] and stops + /// watching the volume. iOS only; a no-op on Android. + void endStoriesAudio(); + /// Routes a push to the shop it belongs to (payload `shop_id`) and tracks it /// via the native `REES46.handlePush`. [event] is the index of the Dart /// `PushEvent` enum: 0 = received, 1 = delivered, 2 = clicked. The native side @@ -421,3 +462,12 @@ abstract class PersonalizationFlutterApi { void onPushClicked(String? shopId, Map payload); } + +/// Native events of the stories viewer. Separate from [PersonalizationFlutterApi]: the +/// push dispatcher owns that channel, the UI kit owns this one. +@FlutterApi() +abstract class PersonalizationStoriesFlutterApi { + /// The hardware volume went up while the viewer plays video (iOS: the audio session's + /// `outputVolume` grew). Android delivers the volume key to Flutter itself. + void onStoriesVolumeUp(); +} diff --git a/pubspec.yaml b/pubspec.yaml index f01b334..0834a19 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -13,6 +13,10 @@ dependencies: flutter: sdk: flutter plugin_platform_interface: ^2.0.2 + # История поисковых запросов виджета мгновенного поиска. + shared_preferences: ^2.3.0 + # Видео-слайды сторис. + video_player: ^2.11.1 dev_dependencies: flutter_test: @@ -43,6 +47,11 @@ flutter: ios: pluginClass: Rees46FlutterSdkPlugin + # Иконки дизайн-системы. Отдаются как ассеты пакета: Flutter не рисует SVG + # без сторонней библиотеки, поэтому отрисовка остаётся за потребителем. + assets: + - assets/icons/ + # To add assets to your plugin package, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg diff --git a/test/stories/stories_response_test.dart b/test/stories/stories_response_test.dart new file mode 100644 index 0000000..d0a0c65 --- /dev/null +++ b/test/stories/stories_response_test.dart @@ -0,0 +1,344 @@ +import 'dart:convert'; + +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; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/stories/stories_response.dart'; + +/// A trimmed copy of a real `stories/{code}` answer (block 115bd0b6…, demo shop): a +/// dynamic product slide, a video slide, an image slide with a button and products, plus +/// a text block and a header the kit drops. +final Map _block = { + 'id': 35, + 'settings': {'color': '#212529'}, + 'stories': >[ + { + 'id': 39, + 'name': 'Test story', + 'avatar': 'https://cdn.example/avatar.jpg', + 'viewed': false, + 'start_position': 0, + 'pinned': false, + 'slides': >[ + { + 'id': '39_0', + 'duration': 10, + 'background': '', + 'preview': '', + 'type': '', + 'elements': >[ + { + 'type': 'button', + 'title': 'Buy', + 'link': 'https://shop.example/p/1?recommended_by=dynamic', + 'link_ios': 'https://shop.example/p/1', + 'link_android': 'https://shop.example/p/1', + 'background': '#3b82f6', + 'color': '#ffffff', + }, + { + 'type': 'product', + 'title': ' ', + 'item': { + 'id': '216908', + 'name': 'Надувной бассейн INTEX', + 'brand': 'INTEX', + 'picture': 'https://pictures.example/180/135478.jpg', + 'image_url': 'https://api.example/216908_1.jpg', + 'price': 19990, + 'price_formatted': '19 990 ₽', + 'oldprice': 27990, + 'oldprice_formatted': '27 990 ₽', + 'discount_percent': 28, + 'currency': '₽', + 'url': 'https://shop.example/p/1?recommended_by=stories', + 'deeplink_android': 'https://shop.example/p/1', + 'deeplink_ios': 'https://shop.example/p/1', + }, + }, + ], + }, + ], + }, + { + 'id': 40, + 'name': 'Test story', + 'avatar': 'https://cdn.example/avatar2.jpg', + 'viewed': true, + 'start_position': '1', + 'pinned': true, + 'slides': >[ + { + 'id': 36, + 'duration': 10, + 'background': 'https://cdn.example/clip.mp4', + 'preview': 'https://cdn.example/poster.jpg', + 'type': 'video', + }, + { + 'id': 37, + 'duration': 0, + 'background': 'https://cdn.example/slide.jpg', + 'background_color': '#000000', + 'preview': '', + 'type': 'image', + 'elements': >[ + { + 'link': 'https://demo.example/', + 'type': 'button', + 'color': '#ffffff', + 'title': 'Go gaming!', + 'link_ios': '', + 'text_bold': false, + 'background': '#3b82f6', + 'link_android': 'https://demo.example/', + }, + { + 'type': 'products', + 'labels': { + 'hide_carousel': 'Скрыть товары', + 'show_carousel': 'Товары для геймеров', + }, + 'products': >[ + { + 'id': 1, + 'name': 'Mouse', + 'price': '1990.0', + 'price_formatted': '1 990 ₽', + 'oldprice': 0, + }, + ], + }, + { + 'type': 'text_block', + 'text_input': 'Скидки до 10%', + 'font_size': '24', + 'font_type': 'serif', + 'bold': true, + 'italic': false, + 'text_align': 'center', + 'text_color': '#FFFFFF', + 'text_background_color': '#16AE13', + 'text_background_color_opacity': '40%', + 'text_line_spacing': '1.2', + 'y_offset': 12, + 'promocode': 'SALE10', + }, + {'type': 'header', 'title': 'dropped'}, + ], + }, + { + 'id': 38, + 'background': 'https://cdn.example/plain.jpg', + 'type': 'image', + }, + ], + }, + ], +}; + +class _FakeHostApi extends pigeon.PersonalizationHostApi { + final List<(String, String?)> requests = <(String, String?)>[]; + final Map>> seen = + >>{}; + + @override + Future getStories(String code, String? shopId) async { + requests.add((code, shopId)); + return jsonEncode(_block); + } + + @override + Future>> getStoriesSeen(String shop) async => + seen[shop] ?? >{}; + + @override + Future setStorySlideSeen( + String shop, + String storyId, + String slideId, + ) async { + (seen[shop] ??= >{}) + .putIfAbsent(storyId, () => []) + .add(slideId); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('StoriesBlock.fromJson', () { + final block = StoriesBlock.fromJson(_block); + + test('reads the block and its stories, ids as strings', () { + expect(block.id, '35'); + expect(block.stories.map((story) => story.id), ['39', '40']); + final second = block.stories[1]; + expect(second.viewed, isTrue); + expect(second.pinned, isTrue); + expect(second.startPosition, 1, reason: 'a string number is tolerated'); + expect(second.slides.map((slide) => slide.id), [ + '36', + '37', + '38', + ]); + }); + + test('slide types, backgrounds and durations', () { + final product = block.stories[0].slides[0]; + expect(product.type, StorySlideType.product); + expect(product.duration, const Duration(seconds: 10)); + + final video = block.stories[1].slides[0]; + expect(video.type, StorySlideType.video); + expect(video.background, 'https://cdn.example/clip.mp4'); + expect(video.preview, 'https://cdn.example/poster.jpg'); + expect(video.elements, isEmpty); + + final image = block.stories[1].slides[1]; + expect(image.type, StorySlideType.image); + expect(image.backgroundColor, '#000000'); + expect( + image.duration, + const Duration(seconds: StorySlide.defaultDurationSeconds), + reason: 'zero falls back to the default', + ); + expect( + block.stories[1].slides[2].duration, + const Duration(seconds: StorySlide.defaultDurationSeconds), + reason: 'missing falls back to the default', + ); + }); + + test('the dynamic product slide carries a button and the product', () { + final slide = block.stories[0].slides[0]; + final button = slide.elements.whereType().single; + expect(button.title, 'Buy'); + expect(button.linkAndroid, 'https://shop.example/p/1'); + expect(button.linkIos, 'https://shop.example/p/1'); + + final product = slide.product!; + expect(product.id, '216908'); + expect(product.brand, 'INTEX'); + expect(product.priceFormatted, '19 990 ₽'); + expect(product.oldPrice, 27990); + expect(product.hasOldPrice, isTrue); + expect(product.discountPercent, 28); + expect(product.promocode, isEmpty); + expect(product.image, 'https://pictures.example/180/135478.jpg'); + }); + + test('products, text block; header dropped', () { + final elements = block.stories[1].slides[1].elements; + expect(elements, hasLength(3), reason: 'header is not drawn by the kit'); + + final products = elements.whereType().single; + expect(products.showLabel, 'Товары для геймеров'); + expect(products.hideLabel, 'Скрыть товары'); + expect(products.products.single.id, '1'); + expect(products.products.single.price, 1990); + expect(products.products.single.hasOldPrice, isFalse); + + final text = elements.whereType().single; + expect(text.text, 'Скидки до 10%'); + expect(text.fontSize, 24); + expect(text.fontType, 'serif'); + expect(text.bold, isTrue); + expect(text.textAlign, 'center'); + expect(text.backgroundOpacity, closeTo(0.4, 1e-9)); + expect(text.lineSpacing, closeTo(1.2, 1e-9)); + expect(text.yOffset, 12); + expect(text.promocode, 'SALE10'); + }); + + test('a text block without fields takes the native defaults', () { + final text = StoryTextBlockElement.fromJson(const { + 'type': 'text_block', + }); + expect(text.fontSize, StoryTextBlockElement.defaultFontSize); + expect(text.backgroundOpacity, 0); + expect(text.promocode, isNull); + }); + }); + + test('parseStoryOpacity reads percents and fractions', () { + expect(parseStoryOpacity('0%'), 0); + expect(parseStoryOpacity('100%'), 1); + expect(parseStoryOpacity('50'), 0.5); + expect(parseStoryOpacity(' 25% '), 0.25); + expect(parseStoryOpacity(0.3), closeTo(0.3, 1e-9)); + expect(parseStoryOpacity(80), closeTo(0.8, 1e-9)); + expect(parseStoryOpacity(null), 0); + expect(parseStoryOpacity('bad'), 0); + }); + + test('getStories goes through the bridge with the handle\'s shop', () async { + final api = _FakeHostApi(); + final sdk = PersonalizationSdk(api: api, shopId: 'shop-a'); + + final block = await sdk.getStories('115bd0b67cf5989a1b60c841790b2af6'); + + expect(api.requests, <(String, String?)>[ + ('115bd0b67cf5989a1b60c841790b2af6', 'shop-a'), + ]); + expect(block.stories, hasLength(2)); + expect(() => sdk.getStories(''), throwsArgumentError); + }); + + test('seen slides go through the bridge, per shop', () async { + final api = _FakeHostApi(); + final sdk = PersonalizationSdk(api: api, shopId: 'shop-a'); + + await sdk.setStorySlideSeen('shop-a', '40', '36'); + await sdk.setStorySlideSeen('shop-a', '40', '37'); + + expect(await sdk.getStoriesSeen('shop-a'), >{ + '40': ['36', '37'], + }); + expect(await sdk.getStoriesSeen('shop-b'), isEmpty); + }); + + test('seen slides read over the real channel, whose lists arrive untyped', () async { + // The platform side answers through the standard codec: the inner lists decode + // as List, not List. A lazy cast of them threw on the first read + // once a slide had been seen ("List is not a subtype of List"). + const channel = + 'dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.getStoriesSeen'; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMessageHandler( + channel, + (_) async => const StandardMessageCodec().encodeMessage([ + { + '40': ['36', '37'], + }, + ]), + ); + addTearDown(() => messenger.setMockMessageHandler(channel, null)); + + final sdk = PersonalizationSdk( + api: pigeon.PersonalizationHostApi(), + shopId: 'shop-a', + ); + + final seen = await sdk.getStoriesSeen('shop-a'); + expect(seen.keys, ['40']); + expect(seen['40'], ['36', '37']); + }); + + test('numbers are read as decimals; the default duration is 10 s', () { + final product = StoryProduct.fromJson(const { + 'id': 1, + 'price': '99.9', + 'discount_percent': '12.5', + 'price_with_promocode': 89.5, + }); + expect(product.price, 99.9); + expect(product.discountPercent, 12.5); + expect(product.priceWithPromocode, 89.5); + expect(StorySlide.defaultDurationSeconds, 10); + }); +} diff --git a/test/ui/gif_fixture.dart b/test/ui/gif_fixture.dart new file mode 100644 index 0000000..2967754 --- /dev/null +++ b/test/ui/gif_fixture.dart @@ -0,0 +1,54 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import 'dart:ui' as ui; + +/// The fixture all four SDKs test with: 2×2, 3 frames, delays 10 / 0 / 50 hundredths +/// of a second → 100 + 100 + 500 = 700 ms per loop. +final Uint8List gifFixture = base64Decode( + 'R0lGODlhAgACAIEAAP8AAAD/AAAA/////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAgACAAA' + 'CAoRRACH5BAAAAAAALAAAAAACAAIAAAICjFMAIfkEADIAAAAsAAAAAAIAAgAAAgKUVQA7', +); + +/// A codec that needs no real decoding, so it runs on the fake clock of widget tests: +/// frame `i` is an image `i + 1` pixels wide and 1 pixel high, frames loop. +class FakeGifCodec implements ui.Codec { + FakeGifCodec(this.frameCount); + + @override + final int frameCount; + + int _next = 0; + + /// Frames handed out so far. + int decoded = 0; + bool disposed = false; + + @override + int get repetitionCount => -1; + + @override + Future getNextFrame() { + final index = _next; + _next = (_next + 1) % frameCount; + decoded++; + final recorder = ui.PictureRecorder(); + ui.Canvas(recorder); + final picture = recorder.endRecording(); + final image = picture.toImageSync(index + 1, 1); + picture.dispose(); + return Future.value(_Frame(image)); + } + + @override + void dispose() => disposed = true; +} + +class _Frame implements ui.FrameInfo { + _Frame(this.image); + + @override + final ui.Image image; + + @override + Duration get duration => Duration.zero; +} diff --git a/test/ui/personalization_barcode_test.dart b/test/ui/personalization_barcode_test.dart new file mode 100644 index 0000000..5e1a33e --- /dev/null +++ b/test/ui/personalization_barcode_test.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// The encoder is internal to the barcode and stays out of the kit barrel. +import 'package:rees46_sdk/src/ui/components/personalization_code128.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +String _bits(List modules) => + modules.map((bar) => bar ? '1' : '0').join(); + +Widget _host(Widget child) => MaterialApp( + home: Align(alignment: Alignment.topLeft, child: child), +); + +void main() { + group('Code 128 encoder', () { + test('letters and digits go to set B', () { + final values = PersonalizationCode128.values('PJJ123C')!; + // Start B, the data, then the checksum. + expect(values, [104, 48, 42, 42, 17, 18, 19, 35, 55]); + expect(PersonalizationCode128.checksum(values.sublist(0, 8)), 55); + + final bits = _bits(PersonalizationCode128.encode('PJJ123C')!); + expect(bits, hasLength(112)); + expect(bits.substring(0, 11), '11010010000'); + expect(bits.substring(bits.length - 13), '1100011101011'); + }); + + test('an even run of digits goes to set C in pairs', () { + expect(PersonalizationCode128.values('1234'), [105, 12, 34, 82]); + + final bits = _bits(PersonalizationCode128.encode('1234')!); + expect(bits, hasLength(57)); + expect(bits.substring(0, 11), '11010011100'); + expect(bits.substring(bits.length - 13), '1100011101011'); + }); + + test('an odd run of digits ends in set B through CODE B', () { + expect(PersonalizationCode128.values('123'), [105, 12, 100, 19, 65]); + expect(PersonalizationCode128.encode('123'), hasLength(68)); + }); + + test('a single digit is not worth set C', () { + expect(PersonalizationCode128.values('7')!.first, 104); + }); + + test('empty or non-ASCII input is not encodable', () { + expect(PersonalizationCode128.values(''), isNull); + expect(PersonalizationCode128.encode(''), isNull); + expect(PersonalizationCode128.encode('é'), isNull); + expect(PersonalizationCode128.encode('tab\there'), isNull); + }); + }); + + group('PersonalizationBarcode', () { + testWidgets('the module is a whole number of physical pixels', ( + tester, + ) async { + addTearDown(tester.view.reset); + // 112 modules into 232: 6 px at 3x, 4 px at 2x, 5 px at 2.625x. + const cases = <(double, double)>[(3, 6), (2, 4), (2.625, 5)]; + for (final (dpr, pixels) in cases) { + tester.view.devicePixelRatio = dpr; + await tester.pumpWidget( + _host(const PersonalizationBarcode(code: 'PJJ123C')), + ); + + final size = tester.getSize(find.byType(PersonalizationBarcode)); + expect(size.width, closeTo(112 * pixels / dpr, 1e-9), reason: '$dpr'); + expect(size.height, 42, reason: '$dpr'); + } + }); + + testWidgets('a narrower slot gets a smaller whole module', (tester) async { + addTearDown(tester.view.reset); + tester.view.devicePixelRatio = 3; + await tester.pumpWidget( + _host( + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 120), + child: const PersonalizationBarcode(code: 'PJJ123C'), + ), + ), + ); + + // floor(120 * 3 / 112) = 3 px — one logical unit per module. + expect(tester.getSize(find.byType(PersonalizationBarcode)).width, 112); + }); + + testWidgets('an unencodable code takes no space', (tester) async { + for (final code in ['', 'é']) { + await tester.pumpWidget(_host(PersonalizationBarcode(code: code))); + + expect( + tester.getSize(find.byType(PersonalizationBarcode)), + Size.zero, + reason: code, + ); + } + }); + + testWidgets('a screen reader reads the code', (tester) async { + final semantics = tester.ensureSemantics(); + await tester.pumpWidget( + _host(const PersonalizationBarcode(code: '2000012345678')), + ); + + expect(find.bySemanticsLabel('2000012345678'), findsOneWidget); + semantics.dispose(); + }); + }); +} diff --git a/test/ui/personalization_button_test.dart b/test/ui/personalization_button_test.dart new file mode 100644 index 0000000..4dcfc77 --- /dev/null +++ b/test/ui/personalization_button_test.dart @@ -0,0 +1,55 @@ +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: Center(child: child)); + +BorderRadiusGeometry? _radius(WidgetTester tester) { + final container = tester.widget( + find.descendant( + of: find.byType(PersonalizationButton), + matching: find.byType(Container), + ), + ); + return (container.decoration! as BoxDecoration).borderRadius; +} + +void main() { + testWidgets('a rounded icon button is a circle', (tester) async { + await tester.pumpWidget( + _host( + const PersonalizationButton( + size: PersonalizationButtonSize.md, + view: PersonalizationButtonView.secondary, + iconStart: PersonalizationIcons.crossLarge, + rounded: true, + ), + ), + ); + + expect( + _radius(tester), + BorderRadius.circular(PersonalizationRadius.rounded), + ); + final size = tester.getSize(find.byType(PersonalizationButton)); + expect(size.width, size.height); + }); + + testWidgets('without rounded the button keeps the radius of its size', ( + tester, + ) async { + await tester.pumpWidget( + _host( + const PersonalizationButton( + size: PersonalizationButtonSize.md, + iconStart: PersonalizationIcons.crossLarge, + ), + ), + ); + + expect( + _radius(tester), + BorderRadius.circular(PersonalizationRadius.buttonMd), + ); + }); +} diff --git a/test/ui/personalization_catalog_test.dart b/test/ui/personalization_catalog_test.dart new file mode 100644 index 0000000..183f573 --- /dev/null +++ b/test/ui/personalization_catalog_test.dart @@ -0,0 +1,230 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +// The catalogue is one scrolling list: header, cards and footer are its parts. Given a +// bounded height it builds cards for what is on screen only, however many it holds. + +Widget _host(Widget child, {double height = 600}) => MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, height: height, child: child), + ), +); + +List _products(int count) => [ + for (int i = 0; i < count; i++) + PersonalizationProduct(id: '$i', name: 'Item $i', price: '$i'), +]; + +const PersonalizationCatalogCount _count = PersonalizationCatalogCount( + prefix: 'Showing', + shown: 4, + separator: 'of', + total: 40, +); + +/// Every card that exists, on screen or in the cache area around it. +final Finder _cards = find.byType( + PersonalizationProductCard, + skipOffstage: false, +); + +Rect _card(WidgetTester tester, int index) => + tester.getRect(find.byType(PersonalizationProductCard).at(index)); + +void main() { + testWidgets('a long catalogue builds cards for the screen, not for every ' + 'product', (tester) async { + await tester.pumpWidget( + _host(PersonalizationCatalog(products: _products(200))), + ); + + final built = _cards.evaluate().length; + expect(built, inInclusiveRange(1, 30)); + }); + + testWidgets('scrolling to the end keeps a screenful of cards', ( + tester, + ) async { + final controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + _host( + PersonalizationCatalog( + products: _products(200), + controller: controller, + count: _count, + ), + ), + ); + + // The extent of a lazy list is an estimate: jump until it holds at the end. + for (int i = 0; i < 50; i++) { + controller.jumpTo(controller.position.maxScrollExtent); + await tester.pump(); + if (controller.position.pixels == controller.position.maxScrollExtent) { + break; + } + } + + expect(find.text('Item 199'), findsOneWidget); + expect(find.byType(PersonalizationCount), findsOneWidget); + expect(_cards.evaluate().length, inInclusiveRange(1, 30)); + }); + + testWidgets('inside another scroll it lays out whole and does not scroll ' + 'itself', (tester) async { + await tester.pumpWidget( + _host( + ListView( + children: [ + PersonalizationCatalog( + products: _products(40), + count: _count, + scrollable: false, + ), + ], + ), + ), + ); + + expect(_cards, findsNWidgets(40)); + expect( + find.byType(PersonalizationCount, skipOffstage: false), + findsOneWidget, + ); + final own = tester.widget( + find + .descendant( + of: find.byType(PersonalizationCatalog), + matching: find.byType(Scrollable), + ) + .first, + ); + expect(own.physics, isA()); + }); + + testWidgets('an unbounded height lays it out whole without the flag', ( + tester, + ) async { + await tester.pumpWidget( + _host( + SingleChildScrollView( + child: PersonalizationCatalog(products: _products(10)), + ), + ), + ); + + expect(tester.takeException(), isNull); + expect(_cards, findsNWidgets(10)); + }); + + testWidgets('blocks are 12 apart, grid cards 16 on both axes, a row shares ' + 'its height', (tester) async { + tester.view.physicalSize = const Size(400, 2000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + const header = SizedBox(key: Key('header'), height: 40); + await tester.pumpWidget( + _host( + const PersonalizationCatalog( + header: header, + products: [ + PersonalizationProduct( + id: '0', + brand: 'Brand', + name: 'A name long enough to take both lines of the card', + price: '1', + ), + PersonalizationProduct(id: '1', name: 'Short', price: '2'), + PersonalizationProduct(id: '2', name: 'Third', price: '3'), + ], + count: _count, + ), + height: 2000, + ), + ); + + final headerRect = tester.getRect(find.byKey(const Key('header'))); + expect(_card(tester, 0).top - headerRect.bottom, PersonalizationSpacing.lg); + expect( + _card(tester, 1).left - _card(tester, 0).right, + PersonalizationSpacing.xl, + ); + expect( + _card(tester, 2).top - _card(tester, 0).bottom, + PersonalizationSpacing.xl, + ); + expect(_card(tester, 0).height, _card(tester, 1).height); + expect( + tester.getRect(find.byType(PersonalizationCount)).top - + _card(tester, 2).bottom, + PersonalizationSpacing.lg, + ); + }); + + testWidgets('the list puts one card per row, 16 apart', (tester) async { + await tester.pumpWidget( + _host( + PersonalizationCatalog( + layout: PersonalizationProductsLayout.list, + products: _products(3), + ), + ), + ); + + expect(_card(tester, 0).width, 400); + expect( + _card(tester, 1).top - _card(tester, 0).bottom, + PersonalizationSpacing.xl, + ); + }); + + testWidgets('the loader takes the place of the count and load more', ( + tester, + ) async { + Widget catalog({required bool loading}) => _host( + PersonalizationCatalog( + products: _products(4), + count: _count, + loadMoreText: 'Load more', + onLoadMore: () {}, + loading: loading, + ), + ); + final loadMore = find.widgetWithText(PersonalizationButton, 'Load more'); + + await tester.pumpWidget(catalog(loading: false)); + expect(find.byType(PersonalizationCount), findsOneWidget); + expect(loadMore, findsOneWidget); + expect(find.byType(PersonalizationLoader), findsNothing); + + await tester.pumpWidget(catalog(loading: true)); + expect(find.byType(PersonalizationCount), findsNothing); + expect(loadMore, findsNothing); + expect(find.byType(PersonalizationLoader), findsOneWidget); + }); + + testWidgets('no products and an empty text show the empty state under the ' + 'header', (tester) async { + const header = SizedBox(key: Key('header'), height: 40); + await tester.pumpWidget( + _host( + const PersonalizationCatalog( + header: header, + products: [], + emptyText: 'Nothing found', + ), + ), + ); + + expect(find.byKey(const Key('header')), findsOneWidget); + expect(find.byType(PersonalizationEmptyState), findsOneWidget); + expect( + tester.getRect(find.byType(PersonalizationEmptyState)).top - + tester.getRect(find.byKey(const Key('header'))).bottom, + PersonalizationSpacing.lg, + ); + }); +} diff --git a/test/ui/personalization_in_app_popup_test.dart b/test/ui/personalization_in_app_popup_test.dart new file mode 100644 index 0000000..371530a --- /dev/null +++ b/test/ui/personalization_in_app_popup_test.dart @@ -0,0 +1,167 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +Widget _host(Widget popup, {ThemeData? theme}) => MaterialApp( + theme: theme, + home: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, height: 600, child: popup), + ), +); + +final Finder _cross = find.byWidgetPredicate( + (widget) => + widget is PersonalizationButton && + widget.iconStart == PersonalizationIcons.crossLarge, +); + +/// The shadow of the popup card: the nearest decoration above its clip. +List _shadows(WidgetTester tester) { + final clip = find + .descendant( + of: find.byType(PersonalizationInAppPopup), + matching: find.byType(ClipRRect), + ) + .first; + final box = tester.widget( + find.ancestor(of: clip, matching: find.byType(DecoratedBox)).first, + ); + return (box.decoration as BoxDecoration).boxShadow ?? const []; +} + +void main() { + testWidgets('the cross is a round overlay in the corner in every view', ( + tester, + ) async { + for (final presentation in PersonalizationInAppPopupPresentation.values) { + final pad = presentation == PersonalizationInAppPopupPresentation.modal + ? PersonalizationSpacing.paddingModal + : PersonalizationSpacing.paddingFullScreen; + for (final view in PersonalizationInAppPopupView.values) { + final reason = '$presentation, $view'; + await tester.pumpWidget( + _host( + PersonalizationInAppPopup( + view: view, + presentation: presentation, + title: 'Title', + text: 'Text', + actionText: 'Go', + closeText: 'Later', + ), + ), + ); + + expect(_cross, findsOneWidget, reason: reason); + expect( + tester.widget(_cross).rounded, + isTrue, + reason: reason, + ); + // Over the content, not a row of a column. + expect( + find.ancestor(of: _cross, matching: find.byType(Column)), + findsNothing, + reason: reason, + ); + final popup = tester.getRect(find.byType(PersonalizationInAppPopup)); + final cross = tester.getRect(_cross); + expect( + cross.topRight, + popup.topRight + Offset(-pad, pad), + reason: reason, + ); + expect(cross.width, cross.height, reason: reason); + } + } + }); + + testWidgets('the cross takes the dark palette over a photo', (tester) async { + for (final view in PersonalizationInAppPopupView.values) { + await tester.pumpWidget(_host(PersonalizationInAppPopup(view: view))); + + expect( + tester.widget(_cross).onDark, + view == PersonalizationInAppPopupView.image || + view == PersonalizationInAppPopupView.imageBackground, + reason: '$view', + ); + } + }); + + testWidgets('buttons are 12 apart in a modal and 16 in a fullscreen popup', ( + tester, + ) async { + const gaps = <(PersonalizationInAppPopupPresentation, double)>[ + (PersonalizationInAppPopupPresentation.modal, PersonalizationSpacing.lg), + ( + PersonalizationInAppPopupPresentation.fullscreen, + PersonalizationSpacing.xl, + ), + ]; + for (final (presentation, gap) in gaps) { + await tester.pumpWidget( + _host( + PersonalizationInAppPopup( + view: PersonalizationInAppPopupView.text, + presentation: presentation, + actionText: 'Go', + closeText: 'Later', + ), + ), + ); + + final action = find.widgetWithText(PersonalizationButton, 'Go'); + final close = find.widgetWithText(PersonalizationButton, 'Later'); + expect( + tester.getTopLeft(close).dy - tester.getBottomLeft(action).dy, + gap, + reason: '$presentation', + ); + } + }); + + testWidgets('a modal casts Elevation 3 in the scheme shadow colour', ( + tester, + ) async { + final schemes = <(ThemeData, PersonalizationColors)>[ + (ThemeData(), PersonalizationColors.light), + (ThemeData(brightness: Brightness.dark), PersonalizationColors.dark), + ]; + for (final (theme, colors) in schemes) { + await tester.pumpWidget( + _host( + const PersonalizationInAppPopup( + view: PersonalizationInAppPopupView.text, + ), + theme: theme, + ), + ); + // MaterialApp animates a theme change. + await tester.pumpAndSettle(); + + final shadows = _shadows(tester); + expect(shadows, hasLength(PersonalizationElevation.e3.length)); + for (int i = 0; i < shadows.length; i++) { + final expected = PersonalizationElevation.e3[i]; + expect(shadows[i].offset, expected.offset); + expect(shadows[i].blurRadius, expected.blurRadius); + expect(shadows[i].color, colors.shadowHeavy); + } + } + }); + + testWidgets('a fullscreen popup casts no shadow', (tester) async { + await tester.pumpWidget( + _host( + const PersonalizationInAppPopup( + view: PersonalizationInAppPopupView.text, + presentation: PersonalizationInAppPopupPresentation.fullscreen, + ), + ), + ); + + expect(_shadows(tester), isEmpty); + }); +} diff --git a/test/ui/personalization_loyalty_card_test.dart b/test/ui/personalization_loyalty_card_test.dart new file mode 100644 index 0000000..d919310 --- /dev/null +++ b/test/ui/personalization_loyalty_card_test.dart @@ -0,0 +1,311 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +/// A 1×1 transparent PNG: the tests only need an [ImageProvider] to exist. +final ImageProvider _pixel = MemoryImage( + Uint8List.fromList(const [ + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, // + 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, // + 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, // + 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, // + 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, // + 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, // + ]), +); + +const List _fields = [ + PersonalizationLoyaltyCardField(label: 'Владелец', value: 'Олег'), + PersonalizationLoyaltyCardField(label: 'Уровень', value: 'Базовый'), +]; + +/// The card in a vertical scroll view, as a host screen would place it: the +/// height is unbounded, the width is [width]. +Widget _host(Widget card, {double width = 370, ThemeData? theme}) => + MaterialApp( + theme: theme, + home: Scaffold( + body: SingleChildScrollView( + child: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: width, child: card), + ), + ), + ), + ); + +PersonalizationLoyaltyCard _full({ + int stamps = 0, + int stampsTotal = 5, + Widget Function(BuildContext, String, double, Color)? iconBuilder, +}) => PersonalizationLoyaltyCard( + logo: const SizedBox(width: 108), + balanceLabel: 'Бонусы', + balanceValue: '50 550', + stripe: _pixel, + emblem: _pixel, + stamps: stamps, + stampsTotal: stampsTotal, + fields: _fields, + code: '2000012345678', + iconBuilder: iconBuilder, +); + +Rect _card(WidgetTester tester) => + tester.getRect(find.byType(PersonalizationLoyaltyCard)); + +final Finder _stripe = find.byWidgetPredicate( + (widget) => widget is ColoredBox && widget.color == const Color(0xFF000000), +); + +void main() { + testWidgets('the minimum height keeps the 370×560 pass proportion', ( + tester, + ) async { + for (final width in [370, 300, 343]) { + await tester.pumpWidget( + _host(const PersonalizationLoyaltyCard(), width: width), + ); + + expect( + _card(tester).height, + closeTo(width * 560 / 370, 1e-9), + reason: '$width', + ); + } + }); + + testWidgets('the full card fits the proportion and pins the code low', ( + tester, + ) async { + await tester.pumpWidget(_host(_full())); + + final card = _card(tester); + expect(card.height, closeTo(560, 1e-9)); + // Code section: 24 below the white box, 20 inside it. + final barcode = tester.getRect(find.byType(PersonalizationBarcode)); + expect(barcode.bottom, closeTo(card.bottom - 24 - 20, 1e-9)); + expect(barcode.center.dx, closeTo(card.center.dx, 1)); + }); + + testWidgets('a card narrower than its content grows past the proportion', ( + tester, + ) async { + await tester.pumpWidget(_host(_full(), width: 200)); + + // Header 16 + 38 + 16, stripe 200 / 2.6, info 16 + 46 + 16, + // code 24 + 20 + 42 + 20 + 24. + expect(_card(tester).height, closeTo(70 + 200 / 2.6 + 78 + 130, 1e-6)); + expect(tester.takeException(), isNull); + }); + + testWidgets('sections without content are left out', (tester) async { + await tester.pumpWidget(_host(const PersonalizationLoyaltyCard())); + expect(find.byType(Text), findsNothing); + expect(_stripe, findsNothing); + expect(find.byType(PersonalizationBarcode), findsNothing); + + // Only the info fields: no header and no stripe above them. + await tester.pumpWidget( + _host(const PersonalizationLoyaltyCard(fields: _fields)), + ); + expect( + tester.getTopLeft(find.text('ВЛАДЕЛЕЦ')).dy, + _card(tester).top + PersonalizationSpacing.xl, + ); + + // A code the barcode cannot carry drops the section. + for (final code in ['', 'é']) { + await tester.pumpWidget(_host(PersonalizationLoyaltyCard(code: code))); + expect(find.byType(PersonalizationBarcode), findsNothing, reason: code); + } + + // The balance shows only the lines it has. + await tester.pumpWidget( + _host(const PersonalizationLoyaltyCard(balanceValue: '50 550')), + ); + expect(find.byType(Text), findsOneWidget); + expect(find.text('50 550'), findsOneWidget); + }); + + testWidgets('the stripe shows for a picture, an emblem or stamps', ( + tester, + ) async { + final cards = [ + PersonalizationLoyaltyCard(stripe: _pixel), + PersonalizationLoyaltyCard(emblem: _pixel), + const PersonalizationLoyaltyCard(stampsTotal: 3), + ]; + for (final card in cards) { + await tester.pumpWidget(_host(card)); + + expect(_stripe, findsOneWidget); + final stripe = tester.getRect( + find.ancestor(of: _stripe, matching: find.byType(SizedBox)).first, + ); + expect(stripe.width, 370); + expect(stripe.height, closeTo(370 / 2.6, 1e-9)); + } + }); + + testWidgets('stamps are clamped to the total, filled ones first', ( + tester, + ) async { + const light = PersonalizationColors.light; + const cases = <(int, int, int)>[ + // stamps, total, filled + (0, 5, 0), + (4, 5, 4), + (7, 5, 5), + (-2, 3, 0), + (2, -1, 0), + ]; + for (final (stamps, total, filled) in cases) { + final drawn = <(String, Color)>[]; + await tester.pumpWidget( + _host( + _full( + stamps: stamps, + stampsTotal: total, + iconBuilder: (context, asset, size, color) { + drawn.add((asset, color)); + return SizedBox.square(dimension: size); + }, + ), + ), + ); + + final reason = '$stamps of $total'; + final expected = total < 0 ? 0 : total; + expect(drawn, hasLength(expected), reason: reason); + for (final (index, (asset, color)) in drawn.indexed) { + final isFilled = index < filled; + expect( + asset, + isFilled + ? PersonalizationIcons.checkRosetteFill + : PersonalizationIcons.rosette, + reason: reason, + ); + // Constant light tokens: the stripe is dark in either theme. + expect( + color, + isFilled ? light.textLightSecondary : light.textLightHint, + reason: reason, + ); + } + } + }); + + testWidgets('without an iconBuilder the kit draws the stamps itself', ( + tester, + ) async { + await tester.pumpWidget( + _host(const PersonalizationLoyaltyCard(stamps: 2, stampsTotal: 5)), + ); + + final stamps = find.descendant( + of: find.byType(PersonalizationLoyaltyCard), + matching: find.byType(CustomPaint), + ); + expect(stamps, findsNWidgets(5)); + expect(tester.getSize(stamps.first), const Size(32, 32)); + }); + + testWidgets('info fields share the width equally', (tester) async { + await tester.pumpWidget( + _host(const PersonalizationLoyaltyCard(fields: _fields)), + ); + + const pad = PersonalizationSpacing.xl; + const gap = PersonalizationSpacing.gapModal; + const column = (370 - 2 * pad - gap) / 2; + expect(tester.getTopLeft(find.text('ВЛАДЕЛЕЦ')).dx, pad); + expect(tester.getTopLeft(find.text('УРОВЕНЬ')).dx, pad + column + gap); + }); + + testWidgets('the palette follows the theme and yields to overrides', ( + tester, + ) async { + final schemes = <(ThemeData, PersonalizationColors)>[ + (ThemeData(), PersonalizationColors.light), + (ThemeData(brightness: Brightness.dark), PersonalizationColors.dark), + ]; + for (final (theme, colors) in schemes) { + await tester.pumpWidget(_host(_full(), theme: theme)); + // MaterialApp animates a theme change. + await tester.pumpAndSettle(); + + final reason = '${theme.brightness}'; + expect( + find.byWidgetPredicate( + (widget) => + widget is ColoredBox && widget.color == colors.backgroundCard, + ), + findsOneWidget, + reason: reason, + ); + for (final text in ['БОНУСЫ', '50 550', 'ВЛАДЕЛЕЦ', 'Олег']) { + expect( + tester.widget(find.text(text)).style!.color, + colors.textPrimary, + reason: '$reason, $text', + ); + } + // The barcode keeps its white box in either theme. + final box = tester.widget( + find + .ancestor( + of: find.byType(PersonalizationBarcode), + matching: find.byType(DecoratedBox), + ) + .first, + ); + expect( + (box.decoration as BoxDecoration).color, + const Color(0xFFFFFFFF), + reason: reason, + ); + // Elevation 3 in the scheme's shadow colour. + final shadow = tester.widget( + find + .descendant( + of: find.byType(PersonalizationLoyaltyCard), + matching: find.byType(DecoratedBox), + ) + .first, + ); + final shadows = (shadow.decoration as BoxDecoration).boxShadow!; + expect(shadows, hasLength(PersonalizationElevation.e3.length)); + for (final (index, cast) in shadows.indexed) { + expect(cast.offset, PersonalizationElevation.e3[index].offset); + expect(cast.color, colors.shadowHeavy, reason: reason); + } + } + + const brand = Color(0xFF0087E8); + const white = Color(0xFFFFFFFF); + await tester.pumpWidget( + _host( + const PersonalizationLoyaltyCard( + balanceLabel: 'Бонусы', + balanceValue: '50 550', + fields: _fields, + cardColor: brand, + contentColor: white, + ), + ), + ); + await tester.pumpAndSettle(); + expect( + find.byWidgetPredicate( + (widget) => widget is ColoredBox && widget.color == brand, + ), + findsOneWidget, + ); + expect(tester.widget(find.text('БОНУСЫ')).style!.color, white); + expect(tester.widget(find.text('Базовый')).style!.color, white); + }); +} diff --git a/test/ui/personalization_search_results_screen_test.dart b/test/ui/personalization_search_results_screen_test.dart new file mode 100644 index 0000000..a91c43c --- /dev/null +++ b/test/ui/personalization_search_results_screen_test.dart @@ -0,0 +1,182 @@ +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/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. +class _FakeHostApi extends pigeon.PersonalizationHostApi { + static const int total = 200; + + /// Pages asked for, in order. + final List pages = []; + Completer? hold; + + @override + Future searchFull( + String query, + String? paramsJson, + String? shopId, + ) async { + final params = jsonDecode(paramsJson!) as Map; + final page = params['page'] as int; + final limit = params['limit'] as int; + pages.add(page); + await hold?.future; + final from = (page - 1) * limit; + return jsonEncode({ + 'products': >[ + for (int i = from; i < from + limit && i < total; i++) + {'id': '$i', 'name': 'Item $i', 'price': i}, + ], + 'products_total': total, + }); + } + + @override + Future trackSearch( + String query, + List? results, + String? shopId, + ) async {} +} + +Widget _host(Widget screen) => MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, height: 600, child: screen), + ), +); + +ScrollPosition _position(WidgetTester tester) => tester + .state( + find + .descendant( + of: find.byType(PersonalizationCatalog), + matching: find.byType(Scrollable), + ) + .first, + ) + .position; + +/// Physics that do not pull an emptied list back into range by themselves, as the +/// platform defaults do: the jump to the top has to come from the screen. +class _PlainScrollBehavior extends ScrollBehavior { + const _PlainScrollBehavior(); + + @override + ScrollPhysics getScrollPhysics(BuildContext context) => + const ClampingScrollPhysics(); +} + +/// Every card that exists, on screen or in the cache area around it. +int _cards() => find + .byType(PersonalizationProductCard, skipOffstage: false) + .evaluate() + .length; + +void main() { + late _FakeHostApi api; + late PersonalizationSdk sdk; + + setUp(() { + api = _FakeHostApi(); + sdk = PersonalizationSdk(api: api); + }); + + testWidgets('infinite scroll asks for the next page half a screen before ' + 'the end, once', (tester) async { + await tester.pumpWidget( + _host( + PersonalizationSearchResultsScreen( + sdk: sdk, + query: 'jacket', + infiniteScroll: true, + ), + ), + ); + await tester.pump(); + expect(api.pages, [1]); + + final position = _position(tester); + position.jumpTo(100); + await tester.pump(); + expect(api.pages, [1]); + + api.hold = Completer(); + position.jumpTo( + position.maxScrollExtent - position.viewportDimension / 2 + 1, + ); + await tester.pump(); + expect(api.pages, [1, 2]); + + // The page is still in flight: scrolling on does not ask for it again. + position.jumpTo(position.maxScrollExtent); + await tester.pump(); + expect(api.pages, [1, 2]); + + // Once it is in, the next approach to the end asks for the one after. + api.hold!.complete(); + api.hold = null; + await tester.pump(); + position.jumpTo(position.maxScrollExtent); + await tester.pump(); + expect(api.pages, [1, 2, 3]); + }); + + testWidgets('ten loaded pages keep a screenful of cards, not two hundred', ( + tester, + ) async { + await tester.pumpWidget( + _host( + PersonalizationSearchResultsScreen( + sdk: sdk, + query: 'jacket', + infiniteScroll: true, + ), + ), + ); + await tester.pump(); + + for (int i = 0; i < 100 && api.pages.length < 10; i++) { + final position = _position(tester); + position.jumpTo(position.maxScrollExtent); + await tester.pump(); + } + expect(api.pages, [for (int page = 1; page <= 10; page++) page]); + // Settle at the real end: the extent of a lazy list is an estimate. + for (int i = 0; i < 50; i++) { + final position = _position(tester); + position.jumpTo(position.maxScrollExtent); + await tester.pump(); + if (position.pixels == position.maxScrollExtent) break; + } + + expect(find.text('Item 199'), findsOneWidget); + expect(_cards(), inInclusiveRange(1, 30)); + }); + + testWidgets('a new query starts from the top', (tester) async { + Widget screen(String query) => _host( + ScrollConfiguration( + behavior: const _PlainScrollBehavior(), + child: PersonalizationSearchResultsScreen(sdk: sdk, query: query), + ), + ); + await tester.pumpWidget(screen('jacket')); + await tester.pump(); + _position(tester).jumpTo(1000); + await tester.pump(); + expect(_position(tester).pixels, 1000); + + await tester.pumpWidget(screen('coat')); + await tester.pump(); + + expect(_position(tester).pixels, 0); + expect(api.pages, [1, 1]); + }); +} diff --git a/test/ui/personalization_stories_test.dart b/test/ui/personalization_stories_test.dart new file mode 100644 index 0000000..6752b6e --- /dev/null +++ b/test/ui/personalization_stories_test.dart @@ -0,0 +1,1123 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/ui/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'; + +import 'gif_fixture.dart'; + +/// A 1×1 transparent PNG: slides and covers need an image that loads offline. +final ImageProvider _pixel = MemoryImage( + Uint8List.fromList(const [ + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, // + 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, // + 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, // + 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, // + 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, // + 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, // + ]), +); + +ImageProvider _offline(String url) => _pixel; + +/// An image that never arrives: its slide waits for the readiness timeout. +class _NeverImage extends ImageProvider<_NeverImage> { + @override + Future<_NeverImage> obtainKey(ImageConfiguration configuration) => + Future<_NeverImage>.value(this); + + @override + ImageStreamCompleter loadImage( + _NeverImage key, + ImageDecoderCallback decode, + ) => OneFrameImageStreamCompleter(Completer().future); +} + +/// A product slide (no background: no media to wait for) with numeric id [id]. +Map _productSlide( + Object id, + int product, { + Object? button, +}) => { + 'id': id, + 'duration': 1, + 'type': '', + 'elements': >[ + if (button != null) {'type': 'button', ...?button as Map?}, + { + 'type': 'product', + 'item': { + 'id': 'p$product', + 'name': 'Product $product', + 'price': 100, + 'price_formatted': '100 ₽', + 'picture': 'https://cdn.example/p$product.jpg', + 'url': 'https://shop.example/p$product', + }, + }, + ], +}; + +/// Story 1: slides 10 and 11; story 2: slide 20. One second each. +String _blockJson({Object slideOne = 10}) => jsonEncode({ + 'id': 1, + 'stories': >[ + { + 'id': 1, + 'name': 'Story 1', + 'avatar': 'https://cdn.example/1.jpg', + 'slides': [_productSlide(slideOne, 1), _productSlide(11, 1)], + }, + { + 'id': 2, + 'name': 'Story 2', + 'avatar': 'https://cdn.example/2.jpg', + 'slides': [_productSlide(20, 2)], + }, + {'id': 3, 'name': 'No slides', 'slides': []}, + ], +}); + +class _FakeHostApi extends pigeon.PersonalizationHostApi { + _FakeHostApi(this.answer); + + /// What `getStories` answers; `null` — the call fails. + final String? answer; + Completer? hold; + final List views = []; + final List clicks = []; + final List stored = []; + Map> seen = >{}; + + @override + Future getStories(String code, String? shopId) async { + await hold?.future; + final json = answer; + if (json == null) throw PlatformException(code: 'get_stories_failed'); + return json; + } + + @override + Future>> getStoriesSeen(String shop) async => seen; + + @override + Future setStorySlideSeen( + String shop, + String storyId, + String slideId, + ) async => stored.add('$storyId/$slideId'); + + @override + Future trackStoryView( + String storyId, + String slideId, + String? code, + String? shopId, + ) async => views.add('$storyId/$slideId/$code'); + + @override + Future trackStoryClick( + String storyId, + String slideId, + String? code, + String? shopId, + ) async => clicks.add('$storyId/$slideId/$code'); +} + +Widget _host(Widget child) => MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, child: child), + ), + ), +); + +PersonalizationStoryPreview _preview(WidgetTester tester, String label) => + tester.widget( + find.ancestor( + of: find.text(label), + matching: find.byType(PersonalizationStoryPreview), + ), + ); + +/// Taps the cover [label] and lets the viewer route come in. +Future _openStory(WidgetTester tester, String label) async { + await tester.tap(find.text(label)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pump(); +} + +/// Lets [time] pass in 100 ms frames: the slide clock takes at most a second per frame, +/// as a real device delivers frames far more often. +Future _wait(WidgetTester tester, Duration time) async { + for (var left = time; left > Duration.zero; left -= _frame) { + await tester.pump(left < _frame ? left : _frame); + } +} + +const Duration _frame = Duration(milliseconds: 100); + +/// Lets the viewer route go away. +Future _closed(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); +} + +void main() { + setUp(() => StoriesSeenStore.instance = StoriesSeenStore()); + + group('PersonalizationStoryViewer', () { + /// One story: two image slides, a text block on each, products on the first. + final story = Story.fromJson({ + 'id': 7, + 'name': 'Media', + 'avatar': '', + 'slides': >[ + for (final id in [70, 71]) + { + 'id': id, + 'duration': 5, + 'type': 'image', + 'background': 'https://cdn.example/$id.jpg', + 'elements': >[ + { + 'type': 'text_block', + 'text_input': 'Slide $id', + 'y_offset': 30, + }, + if (id == 70) + { + 'type': 'products', + 'products': >[ + {'id': 'm1', 'name': 'Mouse', 'price': 1}, + ], + }, + ], + }, + ], + }); + + Future<_FakeHostApi> open( + WidgetTester tester, { + List? stories, + VoidCallback? onClose, + ValueChanged? onLink, + ValueChanged? onProduct, + void Function(Story story, int slideIndex)? onSlideShown, + }) async { + final api = _FakeHostApi(null); + await tester.pumpWidget( + MaterialApp( + home: PersonalizationStoryViewer( + stories: stories ?? [story], + code: 'block', + sdk: PersonalizationSdk(api: api), + imageProvider: _offline, + onClose: onClose ?? () {}, + onLinkClick: onLink, + onProductClick: onProduct, + onSlideShown: onSlideShown, + ), + ), + ); + await tester.pump(); + // The slide's clock starts once its image is decoded, and decoding needs real + // async: let it finish, then pump the result in. + await tester.runAsync( + () => precacheImage( + _pixel, + tester.element(find.byType(PersonalizationStoryViewer)), + ), + ); + await tester.pump(); + await tester.pump(); + return api; + } + + Offset at(WidgetTester tester, double x) { + final size = tester.getSize(find.byType(PersonalizationStoryViewer)); + return Offset(size.width * x, size.height / 2); + } + + testWidgets('media slides take the dark tokens in a light app', ( + tester, + ) async { + await open(tester); + final text = tester.widget(find.text('Slide 70')); + expect(text.style!.color, PersonalizationColors.dark.textPrimary); + }); + + testWidgets('thirds: back, nothing, next; a hold pauses, never moves', ( + tester, + ) async { + final api = await open(tester); + expect(api.views, ['7/70/block']); + + await tester.tapAt(at(tester, 0.5)); + await tester.pump(); + expect(find.text('Slide 70'), findsOneWidget, reason: 'the centre'); + + await tester.tapAt(at(tester, 0.8)); + await tester.pump(); + expect(find.text('Slide 71'), findsOneWidget); + expect(api.views, ['7/70/block', '7/71/block']); + + await tester.tapAt(at(tester, 0.1)); + await tester.pump(); + expect(find.text('Slide 70'), findsOneWidget); + + // Held on the right third longer than the slide lasts: still there. + final hold = await tester.startGesture(at(tester, 0.8)); + await tester.pump(const Duration(milliseconds: 300)); + await _wait(tester, const Duration(seconds: 6)); + expect(find.text('Slide 70'), findsOneWidget); + await hold.up(); + await tester.pump(); + expect(find.text('Slide 70'), findsOneWidget, reason: 'release stays'); + await _wait(tester, const Duration(seconds: 5)); + await tester.pump(); + expect(find.text('Slide 71'), findsOneWidget); + }); + + testWidgets('back on the first slide restarts it without a new view', ( + tester, + ) async { + final shown = []; + final api = await open( + tester, + onSlideShown: (_, index) => shown.add(index), + ); + expect(shown, [0]); + await _wait(tester, const Duration(seconds: 3)); + await tester.tapAt(at(tester, 0.1)); + await tester.pump(); + expect(api.views, ['7/70/block']); + expect(shown, [0]); + + // The slide starts over: its five seconds run again. + await _wait(tester, const Duration(seconds: 4)); + expect(find.text('Slide 70'), findsOneWidget); + await _wait(tester, const Duration(seconds: 2)); + await tester.pump(); + expect(find.text('Slide 71'), findsOneWidget); + }); + + testWidgets('in the background the clock stands still', (tester) async { + await open(tester); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + await _wait(tester, const Duration(seconds: 30)); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + expect(find.text('Slide 70'), findsOneWidget); + await _wait(tester, const Duration(seconds: 6)); + await tester.pump(); + expect(find.text('Slide 71'), findsOneWidget); + }); + + testWidgets('the readiness timeout stands still in the background', ( + tester, + ) async { + final stuck = Story.fromJson({ + 'id': 9, + 'name': 'Stuck', + 'avatar': '', + 'slides': >[ + { + 'id': 90, + 'duration': 5, + 'type': 'image', + 'background': 'https://cdn.example/90.jpg', + 'elements': [], + }, + ], + }); + await tester.pumpWidget( + MaterialApp( + home: PersonalizationStoryViewer( + stories: [stuck], + imageProvider: (_) => _NeverImage(), + onClose: () {}, + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(seconds: 6)); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + await tester.pump(const Duration(seconds: 30)); + expect(find.text('Retry'), findsNothing); + + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(const Duration(seconds: 3)); + expect(find.text('Retry'), findsNothing, reason: '9 of 10 seconds'); + await tester.pump(const Duration(milliseconds: 1200)); + await tester.pump(); + expect(find.text('Retry'), findsOneWidget); + }); + + testWidgets('the open sheet pauses; a tap outside only closes it', ( + tester, + ) async { + await open(tester); + await tester.tap(find.text('Used products')); + await tester.pump(); + expect(find.text('Hide products'), findsOneWidget); + await _wait(tester, const Duration(seconds: 10)); + expect(find.text('Slide 70'), findsOneWidget, reason: 'paused'); + + // Above the sheet, on the right third. + await tester.tapAt(at(tester, 0.9) - const Offset(0, 200)); + await tester.pump(); + expect(find.text('Used products'), findsOneWidget, reason: 'closed'); + expect(find.text('Slide 70'), findsOneWidget, reason: 'no navigation'); + }); + + testWidgets('a button without a link only counts the click', ( + tester, + ) async { + final buttonStory = Story.fromJson({ + 'id': 8, + 'name': 'Button', + 'avatar': '', + 'slides': >[ + { + 'id': 80, + 'duration': 5, + 'type': 'image', + 'background': 'https://cdn.example/80.jpg', + 'elements': >[ + {'type': 'button', 'title': 'Nowhere'}, + ], + }, + ], + }); + var closed = false; + final links = []; + final api = await open( + tester, + stories: [buttonStory], + onClose: () => closed = true, + onLink: links.add, + ); + await tester.tap(find.text('Nowhere')); + await tester.pump(); + expect(api.clicks, ['8/80/block']); + expect(closed, isFalse); + expect(links, isEmpty); + expect(find.text('Nowhere'), findsOneWidget); + }); + + testWidgets('a product slide shows the text block promo in the card', ( + tester, + ) async { + String? clipboard; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + clipboard = (call.arguments as Map)['text'] as String; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final promoStory = Story.fromJson({ + 'id': 9, + 'name': 'Promo', + 'avatar': '', + 'slides': >[ + { + 'id': 90, + 'duration': 5, + 'type': 'product', + 'elements': >[ + { + 'type': 'text_block', + 'text_input': 'Your code SALE10', + 'promocode': 'SALE10', + 'y_offset': 30, + }, + { + 'type': 'product', + 'item': { + 'id': 'p9', + 'name': 'Product 9', + 'price': 100, + 'price_formatted': '100 ₽', + 'url': 'https://shop.example/p9', + }, + }, + ], + }, + ], + }); + final api = await open(tester, stories: [promoStory]); + + // The text block itself stays hidden on a product slide. + expect(find.byType(PersonalizationStoryTextBlock), findsNothing); + expect(find.text('Your code SALE10'), findsNothing); + final price = tester.widget( + find.byType(PersonalizationStoryPrice), + ); + expect(price.type, PersonalizationStoryPriceType.promoCode); + expect(price.price, '100 ₽'); + expect(price.oldPrice, isNull); + expect(price.promoCode, 'SALE10'); + + // A tap copies the code, toasts and counts the click, as a product promo. + await tester.tap(find.text('SALE10')); + await tester.pump(); + expect(clipboard, 'SALE10'); + expect(find.text('Copied'), findsOneWidget); + expect(api.clicks, ['9/90/block']); + expect(find.text('Product 9'), findsOneWidget, reason: 'still open'); + // Let the toast leave before the test ends. + await _wait(tester, const Duration(seconds: 3)); + }); + + testWidgets('the product picture pages like the slide and opens nothing', ( + tester, + ) async { + // A phone-like portrait screen: the picture spans all three tap zones. + tester.view + ..physicalSize = const Size(400, 800) + ..devicePixelRatio = 1; + addTearDown(tester.view.reset); + final semantics = tester.ensureSemantics(); + final cards = Story.fromJson({ + 'id': 1, + 'name': 'Cards', + 'avatar': '', + 'slides': >[ + {..._productSlide(10, 1), 'duration': 5}, + {..._productSlide(11, 2), 'duration': 5}, + ], + }); + var closed = 0; + final products = []; + final api = await open( + tester, + stories: [cards], + onClose: () => closed++, + onProduct: (product) => products.add(product.id), + ); + expect(find.text('Product 1'), findsOneWidget); + + final picture = find.byType(AspectRatio); + expect(picture, findsOneWidget); + final width = tester + .getSize(find.byType(PersonalizationStoryViewer)) + .width; + final rect = tester.getRect(picture); + final left = Offset(rect.left + 8, rect.center.dy); + final right = Offset(rect.right - 8, rect.center.dy); + expect(left.dx, lessThan(width / 3), reason: 'the left third'); + expect(right.dx, greaterThan(width * 2 / 3), reason: 'the right third'); + + // No node of its own: the picture is no button, and the only tap under it is the + // whole slide's (the tap zones), not one sized to the picture. + final node = tester.getSemantics( + find.descendant(of: picture, matching: find.byType(Image)), + ); + expect(node.flagsCollection.isButton, isFalse); + expect(node.rect.size, Size(width, 800), reason: 'the slide surface'); + + // The centre third does nothing, the right third pages on, the left one back. + await tester.tapAt(rect.center); + await tester.pump(); + expect(find.text('Product 1'), findsOneWidget, reason: 'the centre'); + await tester.tapAt(right); + await tester.pump(); + expect(find.text('Product 2'), findsOneWidget); + await tester.tapAt(left); + await tester.pump(); + expect(find.text('Product 1'), findsOneWidget); + + // A hold on the picture pauses and never moves. + final hold = await tester.startGesture(right); + await tester.pump(const Duration(milliseconds: 300)); + await _wait(tester, const Duration(seconds: 6)); + await hold.up(); + await tester.pump(); + expect(find.text('Product 1'), findsOneWidget, reason: 'held, released'); + + expect(products, isEmpty, reason: 'the picture opens no product'); + expect(api.clicks, isEmpty); + expect(closed, 0); + + // The product opens only from the slide's button. + await tester.tap(find.text('More info')); + await tester.pump(); + expect(products, ['p1']); + expect(api.clicks, ['1/10/block']); + semantics.dispose(); + }); + + testWidgets('the cross closes the viewer also with the sheet open', ( + tester, + ) async { + var closed = 0; + await open(tester, onClose: () => closed++); + await tester.tap(find.text('Used products')); + await tester.pump(); + + // The header row beside the cross is outside the sheet: only the sheet goes. + final header = tester.getTopLeft( + find.byType(PersonalizationStoryNavigation), + ); + await tester.tapAt(header + const Offset(40, 30)); + await tester.pump(); + expect(find.text('Used products'), findsOneWidget); + expect(closed, 0); + + await tester.tap(find.text('Used products')); + await tester.pump(); + await tester.tap( + find.descendant( + of: find.byType(PersonalizationStoryNavigation), + matching: find.byType(GestureDetector), + ), + ); + await tester.pump(); + expect(closed, 1); + }); + + testWidgets( + 'a carousel product closes the viewer even with the sheet open', + (tester) async { + final products = []; + final api = _FakeHostApi(null); + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () => Navigator.of(context).push( + PersonalizationStoryViewer.route( + PersonalizationStoryViewer( + stories: [story], + code: 'block', + sdk: PersonalizationSdk(api: api), + imageProvider: _offline, + onProductClick: (product) => products.add(product.id), + ), + ), + ), + child: const Text('open'), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await _closed(tester); + await tester.tap(find.text('Used products')); + await tester.pump(); + await tester.tap(find.text('Mouse')); + await _closed(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(products, ['m1']); + expect(api.clicks, ['7/70/block']); + }, + ); + + group('GIF slides', () { + late List fetched; + late List codecs; + + setUp(() { + fetched = []; + codecs = []; + StoriesImageBytes.instance = StoriesImageBytes( + fetch: (uri) async { + fetched.add(uri.path); + return gifFixture; + }, + ); + StoryGifPlayer.codecOf = (_) async { + final codec = FakeGifCodec(3); + codecs.add(codec); + return codec; + }; + }); + tearDown(() { + StoriesImageBytes.instance = StoriesImageBytes(); + StoryGifPlayer.codecOf = ui.instantiateImageCodec; + PaintingBinding.instance.imageCache.clear(); + }); + + /// A GIF slide the server gives 300 ms (the fixture loops in 100 + 100 + 500 ms), + /// then a slide without media. No host imageProvider: the SDK loads the GIF. + final gifStory = Story( + id: '8', + name: 'GIF', + avatar: '', + slides: const [ + StorySlide( + id: '80', + type: StorySlideType.image, + background: 'https://cdn.example/clock.gif', + duration: Duration(milliseconds: 300), + ), + StorySlide(id: '81', type: StorySlideType.image), + ], + ); + + /// The GIF frame on screen by its width: frame i is i + 1 pixels wide. + int? frame(WidgetTester tester) { + for (final raw in tester.widgetList(find.byType(RawImage))) { + final image = raw.image; + if (image != null && image.height == 1) return image.width; + } + return null; + } + + Future> openGif( + WidgetTester tester, { + ValueNotifier? paused, + }) async { + final shown = []; + await tester.pumpWidget( + MaterialApp( + home: PersonalizationStoryViewer( + stories: [gifStory], + paused: paused, + onClose: () {}, + onSlideShown: (_, index) => shown.add(index), + ), + ), + ); + // The page settles and loads; then the first frame is in and the clock runs. + await tester.pump(); + await tester.pump(); + return shown; + } + + testWidgets('plays one loop at least and stands still with the slide', ( + tester, + ) async { + final paused = ValueNotifier(false); + final shown = await openGif(tester, paused: paused); + expect(frame(tester), 1); + await _wait(tester, const Duration(milliseconds: 100)); + expect(frame(tester), 2); + await _wait(tester, const Duration(milliseconds: 100)); + expect(frame(tester), 3); + + // pause() from the host: the slide and its GIF stay on the third frame. + paused.value = true; + await _wait(tester, const Duration(seconds: 2)); + expect(frame(tester), 3); + expect(shown, [0]); + + paused.value = false; + await tester.pump(); + // Past the server's 300 ms the slide goes on: one loop is 700 ms. + await _wait(tester, const Duration(milliseconds: 400)); + expect(shown, [0]); + expect(frame(tester), 3, reason: 'the 500 ms frame'); + await _wait(tester, const Duration(milliseconds: 100)); + await tester.pump(); + expect(shown, [0, 1]); + expect(fetched, ['/clock.gif']); + }); + + testWidgets('a hold freezes the frame; release goes on from it', ( + tester, + ) async { + await openGif(tester); + await _wait(tester, const Duration(milliseconds: 100)); + expect(frame(tester), 2); + final hold = await tester.startGesture(at(tester, 0.5)); + // 100 ms of the press still run; the hold stops the rest. + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(const Duration(milliseconds: 100)); + expect(frame(tester), 3); + await _wait(tester, const Duration(seconds: 3)); + expect(frame(tester), 3); + await hold.up(); + await tester.pump(); + await _wait(tester, const Duration(milliseconds: 400)); + expect(frame(tester), 3); + await _wait(tester, const Duration(milliseconds: 100)); + expect(frame(tester), isNull, reason: 'the next slide has no GIF'); + }); + + testWidgets('restart and a return begin at the first frame, no download', ( + tester, + ) async { + final shown = await openGif(tester); + await _wait(tester, const Duration(milliseconds: 200)); + expect(frame(tester), 3); + + // Back on the first slide of the first story restarts it. + await tester.tapAt(at(tester, 0.1)); + await tester.pump(); + await tester.pump(); + expect(frame(tester), 1); + await _wait(tester, const Duration(milliseconds: 100)); + expect(frame(tester), 2); + + // The next slide and back: the GIF starts over from the bytes in memory. + await tester.tapAt(at(tester, 0.9)); + await tester.pump(); + await tester.tapAt(at(tester, 0.1)); + await tester.pump(); + await tester.pump(); + expect(shown, [0, 1, 0]); + expect(frame(tester), 1); + expect(fetched, ['/clock.gif']); + expect(codecs, hasLength(3)); + expect(codecs.take(2).every((codec) => codec.disposed), isTrue); + }); + }); + }); + + group('PersonalizationStories', () { + Future<_FakeHostApi> bar( + WidgetTester tester, { + _FakeHostApi? api, + PersonalizationStoriesController? controller, + ValueChanged? onLink, + List? errors, + String code = 'block', + }) async { + final host = api ?? _FakeHostApi(_blockJson()); + await tester.pumpWidget( + _host( + PersonalizationStories( + code: code, + sdk: PersonalizationSdk(api: host, shopId: 'shop'), + controller: controller, + imageProvider: _offline, + productButtonText: 'Open', + onLinkClick: onLink, + onProductClick: (product) => onLink?.call('product:${product.id}'), + onError: errors?.add, + ), + ), + ); + await tester.pump(); + await tester.pump(); + return host; + } + + testWidgets('skeletons while loading, hidden when empty', (tester) async { + final api = _FakeHostApi(jsonEncode({'stories': []})) + ..hold = Completer(); + await tester.pumpWidget( + _host( + PersonalizationStories( + code: 'block', + sdk: PersonalizationSdk(api: api), + ), + ), + ); + expect(find.byType(PersonalizationStoryPreview), findsNWidgets(4)); + api.hold!.complete(); + await tester.pump(); + await tester.pump(); + expect(find.byType(PersonalizationStoriesBar), findsNothing); + }); + + testWidgets('errors, a missing code and a slow load reach onError', ( + tester, + ) async { + final errors = []; + await bar(tester, api: _FakeHostApi(null), errors: errors); + expect(find.byType(PersonalizationStoriesBar), findsNothing); + expect(errors.single, isA()); + + errors.clear(); + await bar(tester, errors: errors, code: ''); + expect(errors.single, isA()); + + errors.clear(); + final slow = _FakeHostApi(_blockJson())..hold = Completer(); + await bar(tester, api: slow, errors: errors); + expect(find.byType(PersonalizationStoryPreview), findsNWidgets(4)); + await tester.pump(PersonalizationStories.loadTimeout); + await tester.pump(); + expect(errors.single, isA()); + expect(find.byType(PersonalizationStoriesBar), findsNothing); + }); + + testWidgets('seen slides persist, light the ring, pick the start', ( + tester, + ) async { + final api = await bar( + tester, + api: _FakeHostApi(_blockJson()) + ..seen = >{ + '1': ['11'], + }, + ); + expect(find.text('No slides'), findsNothing); + expect(_preview(tester, 'Story 1').seenSegments, {1}); + + await _openStory(tester, 'Story 1'); + expect(find.text('Product 1'), findsOneWidget); + expect(api.views, ['1/10/block'], reason: 'the first unseen'); + expect(api.stored, ['1/10']); + + // Both slides seen: the story is viewed. Then story 2 plays to the end. + await _wait(tester, const Duration(seconds: 4)); + await _closed(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(api.views, ['1/10/block', '1/11/block', '2/20/block']); + expect( + _preview(tester, 'Story 1').state, + PersonalizationStoryCoverState.viewed, + ); + expect( + _preview(tester, 'Story 2').state, + PersonalizationStoryCoverState.viewed, + ); + }); + + testWidgets('a button closes the viewer, then hands over the link', ( + tester, + ) async { + final links = []; + final api = await bar(tester, onLink: links.add); + await _openStory(tester, 'Story 2'); + await tester.tap(find.text('Open')); + expect(links, ['product:p2']); + expect(api.clicks, ['2/20/block']); + await _closed(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + }); + + testWidgets('dynamic slide ids are not tracked', (tester) async { + final api = await bar( + tester, + api: _FakeHostApi(_blockJson(slideOne: '1_0')), + ); + await _openStory(tester, 'Story 1'); + expect(api.views, isEmpty); + expect(api.stored, ['1/1_0'], reason: 'still seen locally'); + }); + + testWidgets('the controller opens a story and pauses it', (tester) async { + final controller = PersonalizationStoriesController(); + final api = await bar(tester, controller: controller); + unawaited(controller.openStory('2')); + await _closed(tester); + expect(find.text('Product 2'), findsOneWidget); + controller.pause(); + await _wait(tester, const Duration(seconds: 3)); + expect(find.text('Product 2'), findsOneWidget); + controller.resume(); + await _wait(tester, const Duration(seconds: 2)); + await _closed(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(api.views, ['2/20/block']); + }); + + testWidgets('open before the block loads runs after the load', ( + tester, + ) async { + final controller = PersonalizationStoriesController(); + final api = _FakeHostApi(_blockJson())..hold = Completer(); + await bar(tester, api: api, controller: controller); + var done = false; + unawaited(controller.openStory('2').then((_) => done = true)); + await tester.pump(); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + + api.hold!.complete(); + await tester.pump(); + await _closed(tester); + expect(find.text('Product 2'), findsOneWidget); + expect(done, isFalse); + await _wait(tester, const Duration(seconds: 2)); + await _closed(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(done, isTrue); + }); + + testWidgets('a controller handed to a loaded block runs its open', ( + tester, + ) async { + final controller = PersonalizationStoriesController(); + unawaited(controller.openStory('2')); + final sdk = PersonalizationSdk(api: _FakeHostApi(_blockJson())); + Widget block(PersonalizationStoriesController? controller) => _host( + PersonalizationStories( + code: 'block', + sdk: sdk, + controller: controller, + imageProvider: _offline, + ), + ); + await tester.pumpWidget(block(null)); + await tester.pump(); + await tester.pump(); + expect(find.text('Story 2'), findsOneWidget); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + + await tester.pumpWidget(block(controller)); + await _closed(tester); + expect(find.text('Product 2'), findsOneWidget); + }); + + testWidgets('open with the viewer open turns to that story inside it', ( + tester, + ) async { + final controller = PersonalizationStoriesController(); + final api = await bar(tester, controller: controller); + var first = false; + var second = false; + unawaited(controller.open(0).then((_) => first = true)); + await _closed(tester); + expect(find.text('Product 1'), findsOneWidget); + + unawaited(controller.openStory('2').then((_) => second = true)); + await _wait(tester, const Duration(milliseconds: 500)); + expect(find.text('Product 2'), findsOneWidget); + expect(find.byType(PersonalizationStoryViewer), findsOneWidget); + expect(api.views, ['1/10/block', '2/20/block']); + expect(second, isFalse, reason: 'done when the viewer closes'); + + await _wait(tester, const Duration(seconds: 2)); + await _closed(tester); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + expect(first, isTrue); + expect(second, isTrue); + }); + + testWidgets('pause and resume without a viewer do nothing', (tester) async { + final controller = PersonalizationStoriesController(); + await bar(tester, controller: controller); + controller.pause(); + unawaited(controller.openStory('2')); + await _closed(tester); + expect(find.text('Product 2'), findsOneWidget); + await _wait(tester, const Duration(seconds: 2)); + await _closed(tester); + expect( + find.byType(PersonalizationStoryViewer), + findsNothing, + reason: 'the earlier pause did not stick', + ); + }); + + group('without an explicit SDK', () { + late _FakeHostApi api; + + setUp(() { + api = _FakeHostApi(_blockJson()); + REES46.debugFactory = (config) => + PersonalizationSdk(api: api, shopId: config.shopId); + }); + + tearDown(REES46.reset); + + Future> pumpBar(WidgetTester tester) async { + final errors = []; + await tester.pumpWidget( + _host( + PersonalizationStories( + code: 'block', + imageProvider: _offline, + onError: errors.add, + ), + ), + ); + return errors; + } + + testWidgets('the widget waits for the SDK registration', (tester) async { + final errors = await pumpBar(tester); + await tester.pump(const Duration(seconds: 3)); + expect(find.byType(PersonalizationStoryPreview), findsNWidgets(4)); + + REES46.initialize(const REES46Config(shopId: 'shop')); + await tester.pump(const Duration(milliseconds: 200)); + await tester.pump(); + expect(find.text('Story 1'), findsOneWidget); + expect(errors, isEmpty); + }); + + testWidgets('no registration in 15 s reaches onError', (tester) async { + final errors = await pumpBar(tester); + await tester.pump(PersonalizationStories.registrationTimeout); + await tester.pump(const Duration(milliseconds: 200)); + await tester.pump(); + expect(errors.single, isA()); + expect(find.byType(PersonalizationStoriesBar), findsNothing); + }); + }); + + testWidgets('show() reports an empty block and completes', (tester) async { + final api = _FakeHostApi(jsonEncode({'stories': []})); + await tester.pumpWidget(_host(const Placeholder())); + final errors = []; + var done = false; + unawaited( + PersonalizationStories.show( + tester.element(find.byType(Placeholder)), + code: 'block', + sdk: PersonalizationSdk(api: api, shopId: 'shop'), + onError: errors.add, + ).then((_) => done = true), + ); + await tester.pump(); + await tester.pump(); + expect(errors.single, isA()); + expect(done, isTrue); + expect(find.byType(PersonalizationStoryViewer), findsNothing); + }); + + testWidgets('show() with an unknown start story opens the first', ( + tester, + ) async { + final api = _FakeHostApi(_blockJson()); + await tester.pumpWidget(_host(const Placeholder())); + unawaited( + PersonalizationStories.show( + tester.element(find.byType(Placeholder)), + code: 'block', + sdk: PersonalizationSdk(api: api, shopId: 'shop'), + startStoryId: 'missing', + imageProvider: _offline, + ), + ); + await tester.pump(); + await _closed(tester); + expect(find.text('Product 1'), findsOneWidget); + }); + + testWidgets('show() opens a block without the bar', (tester) async { + final api = _FakeHostApi(_blockJson()); + await tester.pumpWidget(_host(const Placeholder())); + final context = tester.element(find.byType(Placeholder)); + var done = false; + PersonalizationStories.show( + context, + code: 'block', + sdk: PersonalizationSdk(api: api, shopId: 'shop'), + startStoryId: '2', + imageProvider: _offline, + ).then((_) => done = true); + await tester.pump(); + await _closed(tester); + expect(find.text('Product 2'), findsOneWidget); + await _wait(tester, const Duration(seconds: 2)); + await _closed(tester); + expect(done, isTrue); + }); + }); +} diff --git a/test/ui/personalization_story_components_test.dart b/test/ui/personalization_story_components_test.dart new file mode 100644 index 0000000..38e2249 --- /dev/null +++ b/test/ui/personalization_story_components_test.dart @@ -0,0 +1,482 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +Widget _host(Widget child) => MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: 400, child: child), + ), + ), +); + +void main() { + group('StoryPrice', () { + test('the currency is the trailing non-digit token', () { + expect(PersonalizationStoryPrice.splitCurrency('1 190 900 ₽'), ( + '1 190 900', + '₽', + )); + expect(PersonalizationStoryPrice.splitCurrency('9 999₽'), ('9 999', '₽')); + expect(PersonalizationStoryPrice.splitCurrency('1,190.00 USD'), ( + '1,190.00', + 'USD', + )); + expect(PersonalizationStoryPrice.splitCurrency('10 000 тг.'), ( + '10 000', + 'тг.', + )); + expect(PersonalizationStoryPrice.splitCurrency(r'$140'), (r'$140', '')); + expect(PersonalizationStoryPrice.splitCurrency(''), ('', '')); + }); + + testWidgets('discount draws the percent on the brand block', ( + tester, + ) async { + await tester.pumpWidget( + _host( + const PersonalizationStoryPrice( + type: PersonalizationStoryPriceType.discount, + price: '1 190 900 ₽', + oldPrice: '245 000 ₽', + discount: '10%', + ), + ), + ); + expect(find.text('10%'), findsOneWidget); + expect(find.text('1 190 900'), findsOneWidget); + expect(find.text('245 000'), findsOneWidget); + expect(find.text('₽'), findsNWidgets(2)); + final brand = find.byWidgetPredicate( + (widget) => + widget is DecoratedBox && + widget.decoration is BoxDecoration && + (widget.decoration as BoxDecoration).color == + PersonalizationColors.light.brandPrimary, + ); + expect(brand, findsOneWidget); + }); + + testWidgets('tapping the promo code copies it, toasts and reports', ( + tester, + ) async { + String? clipboard; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + clipboard = (call.arguments as Map)['text'] as String; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final copied = []; + await tester.pumpWidget( + _host( + PersonalizationStoryPrice( + type: PersonalizationStoryPriceType.promoCode, + price: '1 190 900 ₽', + promoCode: 'YAGODA-MALINA', + copiedText: 'Code copied', + onPromoCopied: copied.add, + ), + ), + ); + + final gesture = await tester.startGesture( + tester.getCenter(find.text('YAGODA-MALINA')), + ); + await tester.pump(const Duration(milliseconds: 200)); + final scale = tester.widget(find.byType(AnimatedScale)); + expect(scale.scale, PersonalizationStoryPrice.pressedScale); + await gesture.up(); + await tester.pump(); + + expect(clipboard, 'YAGODA-MALINA'); + expect(copied, ['YAGODA-MALINA']); + expect(find.text('Code copied'), findsOneWidget); + expect( + tester.getCenter(find.text('Code copied')).dy, + lessThan( + tester.view.physicalSize.height / tester.view.devicePixelRatio / 2, + ), + reason: 'the toast shows at the top by default', + ); + expect(tester.widget(find.byType(AnimatedScale)).scale, 1); + // The toast leaves by itself. + await tester.pump(const Duration(seconds: 3)); + expect(find.text('Code copied'), findsNothing); + }); + + testWidgets('columns share the width; a long code takes more', ( + tester, + ) async { + Future promoWidth(String code) async { + await tester.pumpWidget( + _host( + PersonalizationStoryPrice( + type: PersonalizationStoryPriceType.promoCode, + price: '1 190 900 ₽', + promoCode: code, + ), + ), + ); + return tester.getSize(find.byType(AnimatedScale)).width; + } + + expect(await promoWidth('PROMO'), 200); + final long = await promoWidth('A-VERY-LONG-PROMO-CODE-2026'); + expect(long, greaterThan(200)); + expect(long, lessThanOrEqualTo(400 * 0.7)); + }); + }); + + test('the timer splits the rest into days and two-digit units', () { + expect( + PersonalizationStoryTimer.format( + const Duration(days: 2, hours: 18, minutes: 33, seconds: 24), + ), + ('2', '18', '33', '24'), + ); + expect( + PersonalizationStoryTimer.format( + const Duration(hours: 1, minutes: 2, seconds: 3), + ), + ('0', '01', '02', '03'), + ); + expect(PersonalizationStoryTimer.format(const Duration(seconds: -5)), ( + '0', + '00', + '00', + '00', + )); + }); + + testWidgets('a finished timer shows zeros and reports once', (tester) async { + var finished = 0; + await tester.pumpWidget( + _host( + PersonalizationStoryTimer( + endTime: DateTime.now().subtract(const Duration(seconds: 1)), + view: PersonalizationStoryTimerView.separate, + onFinished: () => finished++, + ), + ), + ); + expect(find.text('0'), findsOneWidget); + expect(find.text('00'), findsNWidgets(3)); + expect(find.text('d'), findsOneWidget); + await tester.pump(const Duration(seconds: 2)); + expect(finished, 0, reason: 'already over when shown: nothing to count'); + }); + + group('StoryTextBlock', () { + BoxDecoration? frame(WidgetTester tester) { + final boxes = find.descendant( + of: find.byType(PersonalizationStoryTextBlock), + matching: find.byType(DecoratedBox), + ); + if (boxes.evaluate().isEmpty) return null; + return tester.widget(boxes.first).decoration + as BoxDecoration; + } + + testWidgets('solid: server colour, radius 12, padding by size', ( + tester, + ) async { + const green = Color(0x6616AE13); + await tester.pumpWidget( + _host( + const PersonalizationStoryTextBlock( + text: 'Open eat dear winding belonging.', + size: PersonalizationStoryTextSize.large, + background: green, + ), + ), + ); + expect(frame(tester)!.color, green); + expect(frame(tester)!.borderRadius, BorderRadius.circular(12)); + final padding = tester.widget( + find.descendant( + of: find.byType(PersonalizationStoryTextBlock), + matching: find.byType(Padding), + ), + ); + expect( + padding.padding, + const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + ); + final text = tester.widget(find.byType(Text)); + expect(text.style!.color, PersonalizationColors.light.textLightPrimary); + expect(text.style!.fontSize, 48); + + await tester.pumpWidget( + _host( + const PersonalizationStoryTextBlock( + text: 'Small', + size: PersonalizationStoryTextSize.small, + background: green, + ), + ), + ); + expect( + tester + .widget( + find.descendant( + of: find.byType(PersonalizationStoryTextBlock), + matching: find.byType(Padding), + ), + ) + .padding, + const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + ); + + // Medium (30) is not above 30: the small padding, as in the design file. + await tester.pumpWidget( + _host( + const PersonalizationStoryTextBlock( + text: 'Medium', + background: green, + ), + ), + ); + expect( + tester + .widget( + find.descendant( + of: find.byType(PersonalizationStoryTextBlock), + matching: find.byType(Padding), + ), + ) + .padding, + const EdgeInsets.symmetric(vertical: 8, horizontal: 16), + ); + }); + + testWidgets('transparent: no frame, Text/Primary', (tester) async { + await tester.pumpWidget( + _host( + const PersonalizationStoryTextBlock( + text: 'Plain', + background: Color(0x0016AE13), + ), + ), + ); + expect(frame(tester), isNull); + final text = tester.widget(find.byType(Text)); + expect(text.style!.color, PersonalizationColors.light.textPrimary); + expect(text.style!.fontSize, 30); + }); + }); + + test('ring colours: viewed solid, pinned always warning, seen by index', () { + const c = PersonalizationColors.light; + List ring( + PersonalizationStoryCoverState state, { + bool pinned = false, + Set seen = const {}, + }) => PersonalizationStoryCover.ringColors( + c, + state: state, + pinned: pinned, + segments: 4, + seen: seen, + ); + + expect(ring(PersonalizationStoryCoverState.viewed), [c.neutralSubtle]); + expect( + ring(PersonalizationStoryCoverState.viewed, pinned: true, seen: {0, 1}), + [c.semanticWarning], + reason: 'a fully viewed pinned story: a plain warning ring', + ); + expect(ring(PersonalizationStoryCoverState.unviewed, seen: {1, 3}), [ + c.buttonPrimary, + c.buttonPrimaryDisabled, + c.buttonPrimary, + c.buttonPrimaryDisabled, + ]); + expect( + ring(PersonalizationStoryCoverState.unviewed, pinned: true, seen: {0}), + [ + c.buttonPrimaryDisabled, + c.semanticWarning, + c.semanticWarning, + c.semanticWarning, + ], + ); + }); + + testWidgets('a viewed cover rings solid; a partly seen one in arcs', ( + tester, + ) async { + const light = PersonalizationColors.light; + RenderObject ring() => tester.renderObject( + find + .descendant( + of: find.byType(PersonalizationStoryCover), + matching: find.byType(CustomPaint), + ) + .first, + ); + // Paint keeps its colour as floats: compare the packed value. + PaintPatternPredicate drawn(Symbol call, Color color) => + (method, arguments) => + method == call && + arguments.whereType().single.color.toARGB32() == + color.toARGB32(); + + await tester.pumpWidget( + _host( + const Align( + alignment: Alignment.topLeft, + child: PersonalizationStoryCover( + state: PersonalizationStoryCoverState.viewed, + pinned: true, + segments: 5, + seenSegments: {0, 1, 2, 3, 4}, + ), + ), + ), + ); + expect(ring(), paints..something(drawn(#drawOval, light.semanticWarning))); + expect(ring(), isNot(paints..arc())); + + await tester.pumpWidget( + _host( + const Align( + alignment: Alignment.topLeft, + child: PersonalizationStoryCover(segments: 3, seenSegments: {2}), + ), + ), + ); + expect( + ring(), + paints + ..something(drawn(#drawArc, light.buttonPrimary)) + ..something(drawn(#drawArc, light.buttonPrimary)) + ..something(drawn(#drawArc, light.buttonPrimaryDisabled)), + ); + }); + + testWidgets('a pinned cover wears the star; a skeleton has none', ( + tester, + ) async { + await tester.pumpWidget( + _host( + const Align( + alignment: Alignment.topLeft, + child: PersonalizationStoryPreview( + label: 'Pinned', + pinned: true, + segments: 5, + seenSegments: {0, 1}, + ), + ), + ), + ); + expect(find.byType(PersonalizationFavoritesBadge), findsOneWidget); + expect(find.text('Pinned'), findsOneWidget); + expect( + tester.getSize(find.byType(PersonalizationStoryPreview)), + const Size(88, 88 + 8 + 16), + ); + + await tester.pumpWidget( + _host( + const Align( + alignment: Alignment.topLeft, + child: PersonalizationStoryPreview( + state: PersonalizationStoryCoverState.skeleton, + ), + ), + ), + ); + expect(find.byType(PersonalizationFavoritesBadge), findsNothing); + expect( + tester.getSize(find.byType(PersonalizationStoryPreview)), + const Size(88, 88 + 8 + 16), + reason: 'the skeleton keeps the height of a labelled preview', + ); + }); + + testWidgets('a cover label takes up to two lines, as wide as the cover', ( + tester, + ) async { + await tester.pumpWidget( + _host( + const Align( + alignment: Alignment.topLeft, + child: PersonalizationStoryPreview( + label: 'A label far too long for one line or even two of them', + ), + ), + ), + ); + final text = tester.widget(find.byType(Text)); + expect(text.maxLines, 2); + expect(text.overflow, TextOverflow.ellipsis); + expect(text.textAlign, TextAlign.center); + expect( + tester.getSize(find.byType(PersonalizationStoryPreview)), + const Size(88, 88 + 8 + 32), + ); + }); + + test('a text block without a line spacing takes the preset for its size', () { + double line(double size) => + PersonalizationStoryTextBlock.presetLineHeight(size) * size; + expect(line(48), 48); + expect(line(30), closeTo(36, 1e-9)); + expect(line(20), closeTo(24, 1e-9)); + // The nearest preset; a tie between Large and Medium goes to Large. + expect(line(39), 39, reason: 'tie: Large'); + expect(line(38), closeTo(46, 1e-9), reason: 'Medium, 45.6 rounded'); + expect(line(40), 40, reason: 'Large'); + expect(line(14), closeTo(17, 1e-9), reason: 'Small, 16.8 rounded'); + }); + + testWidgets('the sound button names the current state and toggles', ( + tester, + ) async { + final handle = tester.ensureSemantics(); + for (final muted in [true, false]) { + await tester.pumpWidget( + _host(PersonalizationStorySoundButton(muted: muted, onPressed: () {})), + ); + expect( + tester.getSemantics(find.byType(PersonalizationStorySoundButton)), + matchesSemantics( + label: muted ? 'Sound off' : 'Sound on', + isButton: true, + hasToggledState: true, + isToggled: !muted, + hasTapAction: true, + ), + ); + } + handle.dispose(); + }); + + testWidgets('progress fills the passed segments and part of the current', ( + tester, + ) async { + await tester.pumpWidget( + _host( + const PersonalizationStoryProgress(count: 4, current: 1, progress: 0.5), + ), + ); + final fills = tester + .widgetList(find.byType(FractionallySizedBox)) + .map((box) => box.widthFactor) + .toList(); + expect(fills, [1, 0.5, 0, 0]); + }); +} diff --git a/test/ui/personalization_toast_test.dart b/test/ui/personalization_toast_test.dart new file mode 100644 index 0000000..086fd6f --- /dev/null +++ b/test/ui/personalization_toast_test.dart @@ -0,0 +1,288 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; + +const Duration _fade = PersonalizationToast.fadeDuration; + +/// A screen with a button that shows a toast, and a counter of taps on the +/// area under it. +class _Screen extends StatelessWidget { + const _Screen({required this.onShow, required this.onBackgroundTap}); + + final void Function(BuildContext context) onShow; + final VoidCallback onBackgroundTap; + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + Positioned.fill( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onBackgroundTap, + ), + ), + Center( + child: Builder( + builder: (context) => TextButton( + onPressed: () => onShow(context), + child: const Text('show'), + ), + ), + ), + ], + ); + } +} + +Future _pumpScreen( + WidgetTester tester, { + required void Function(BuildContext context) onShow, + VoidCallback? onBackgroundTap, +}) { + return tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: _Screen( + onShow: onShow, + onBackgroundTap: onBackgroundTap ?? () {}, + ), + ), + ), + ); +} + +void main() { + testWidgets('the pill is 50 high, float-coloured, with Elevation 2', ( + tester, + ) async { + await tester.pumpWidget( + const MaterialApp( + home: Center(child: PersonalizationToast(text: 'Copied')), + ), + ); + + expect(tester.getSize(find.byType(PersonalizationToast)).height, 50); + final decoration = + tester + .widget( + find.descendant( + of: find.byType(PersonalizationToast), + matching: find.byType(DecoratedBox), + ), + ) + .decoration + as BoxDecoration; + expect(decoration.color, PersonalizationColors.light.backgroundFloat); + expect( + decoration.borderRadius, + BorderRadius.circular(PersonalizationRadius.toast), + ); + expect(decoration.boxShadow, hasLength(PersonalizationElevation.e2.length)); + for (int i = 0; i < decoration.boxShadow!.length; i++) { + expect( + decoration.boxShadow![i].offset, + PersonalizationElevation.e2[i].offset, + ); + expect( + decoration.boxShadow![i].color, + PersonalizationColors.light.shadowHeavy, + ); + } + final style = tester.widget(find.text('Copied')).style!; + expect(style.fontWeight, FontWeight.w500); + expect(style.color, PersonalizationColors.light.textPrimary); + }); + + testWidgets('shows at the bottom and hides after the duration', ( + tester, + ) async { + addTearDown(tester.view.reset); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(400, 800); + tester.view.padding = const FakeViewPadding(top: 40, bottom: 30); + + await _pumpScreen( + tester, + onShow: (context) => PersonalizationToast.show( + context, + 'Copied', + duration: const Duration(seconds: 1), + ), + ); + await tester.tap(find.text('show')); + await tester.pump(); + await tester.pump(_fade); + + expect(find.text('Copied'), findsOneWidget); + final pill = tester.getRect(find.byType(PersonalizationToast)); + expect(pill.bottom, 800 - 30 - 16); + expect(pill.center.dx, 200); + + // Still there just before the duration runs out. + await tester.pump(const Duration(seconds: 1) - _fade - _ms); + expect(find.text('Copied'), findsOneWidget); + + await tester.pump(_ms); + await tester.pumpAndSettle(); + expect(find.text('Copied'), findsNothing); + }); + + testWidgets('shows at the top below the safe area', (tester) async { + addTearDown(tester.view.reset); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(400, 800); + tester.view.padding = const FakeViewPadding(top: 40, bottom: 30); + + await _pumpScreen( + tester, + onShow: (context) => PersonalizationToast.show( + context, + 'Code copied to clipboard', + position: PersonalizationToastPosition.top, + ), + ); + await tester.tap(find.text('show')); + await tester.pump(); + await tester.pump(_fade); + + expect(tester.getRect(find.byType(PersonalizationToast)).top, 40 + 16); + + await _runOut(tester); + expect(find.byType(PersonalizationToast), findsNothing); + }); + + testWidgets('a long text wraps inside the screen width less 16 a side', ( + tester, + ) async { + addTearDown(tester.view.reset); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(400, 800); + + await _pumpScreen( + tester, + onShow: (context) => PersonalizationToast.show(context, 'word ' * 40), + ); + await tester.tap(find.text('show')); + await tester.pump(); + + final pill = tester.getRect(find.byType(PersonalizationToast)); + expect(pill.left, 16); + expect(pill.right, 400 - 16); + expect(pill.height, greaterThan(50)); + + await _runOut(tester); + }); + + testWidgets('a new toast replaces the one on screen', (tester) async { + await _pumpScreen( + tester, + onShow: (context) { + PersonalizationToast.show(context, 'First'); + PersonalizationToast.show(context, 'Second'); + }, + ); + await tester.tap(find.text('show')); + await tester.pump(); + + expect(find.text('First'), findsNothing); + expect(find.text('Second'), findsOneWidget); + expect(find.byType(PersonalizationToast), findsOneWidget); + + await _runOut(tester); + expect(find.byType(PersonalizationToast), findsNothing); + }); + + testWidgets('the replaced toast\'s timer does not cut the new one short', ( + tester, + ) async { + late BuildContext screen; + await _pumpScreen(tester, onShow: (context) => screen = context); + await tester.tap(find.text('show')); + + PersonalizationToast.show(screen, 'First'); + await tester.pump(const Duration(milliseconds: 1500)); + PersonalizationToast.show(screen, 'Second'); + await tester.pump(); + + // The first one's two seconds are up; the second has shown for 0.5 s. + await tester.pump(const Duration(milliseconds: 1000)); + expect(find.text('Second'), findsOneWidget); + + await _runOut(tester); + expect(find.byType(PersonalizationToast), findsNothing); + }); + + testWidgets('touches go through to the screen underneath', (tester) async { + int taps = 0; + await _pumpScreen( + tester, + onShow: (context) => PersonalizationToast.show(context, 'Copied'), + onBackgroundTap: () => taps++, + ); + await tester.tap(find.text('show')); + await tester.pump(); + await tester.pump(_fade); + + await tester.tapAt(tester.getCenter(find.byType(PersonalizationToast))); + expect(taps, 1); + + await _runOut(tester); + }); + + testWidgets('the text is announced where the platform supports it', ( + tester, + ) async { + tester.platformDispatcher.accessibilityFeaturesTestValue = + const FakeAccessibilityFeatures(supportsAnnounce: true); + addTearDown(tester.platformDispatcher.clearAccessibilityFeaturesTestValue); + + await _pumpScreen( + tester, + onShow: (context) => PersonalizationToast.show(context, 'Copied'), + ); + await tester.tap(find.text('show')); + await tester.pump(); + + expect( + tester.takeAnnouncements().map((announcement) => announcement.message), + contains('Copied'), + ); + + await _runOut(tester); + }); + + testWidgets('without announcements the toast is a live region', ( + tester, + ) async { + // Android: announcement events are deprecated there. + tester.platformDispatcher.accessibilityFeaturesTestValue = + const FakeAccessibilityFeatures(); + addTearDown(tester.platformDispatcher.clearAccessibilityFeaturesTestValue); + final semantics = tester.ensureSemantics(); + await _pumpScreen( + tester, + onShow: (context) => PersonalizationToast.show(context, 'Copied'), + ); + await tester.tap(find.text('show')); + await tester.pump(); + // Fully transparent, the toast is left out of the semantics tree. + await tester.pump(_fade); + + expect( + tester.getSemantics(find.byType(PersonalizationToast)), + isSemantics(label: 'Copied', isLiveRegion: true), + ); + + await _runOut(tester); + semantics.dispose(); + }); +} + +const Duration _ms = Duration(milliseconds: 1); + +/// Lets the default two seconds run out and the fade-out finish. +Future _runOut(WidgetTester tester) async { + await tester.pump(const Duration(seconds: 3)); + await tester.pumpAndSettle(); +} diff --git a/test/ui/stories_gif_test.dart b/test/ui/stories_gif_test.dart new file mode 100644 index 0000000..ec15607 --- /dev/null +++ b/test/ui/stories_gif_test.dart @@ -0,0 +1,270 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_gif.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_gif_player.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_image.dart'; + +import 'gif_fixture.dart'; + +void main() { + group('StoryGif', () { + test('the shared fixture: 3 frames, 100/100/500 ms, a 700 ms loop', () { + expect(StoryGif.isGif(gifFixture), isTrue); + final gif = StoryGif.parse(gifFixture)!; + expect(gif.width, 2); + expect(gif.height, 2); + expect(gif.delays, const [ + Duration(milliseconds: 100), + Duration(milliseconds: 100), + Duration(milliseconds: 500), + ]); + expect(gif.loop, const Duration(milliseconds: 700)); + }); + + test('GIF87a is a GIF too; other bytes are not', () { + final old = Uint8List.fromList(gifFixture)..[4] = 0x37; // "GIF87a" + expect(StoryGif.isGif(old), isTrue); + expect(StoryGif.parse(old)!.loop, const Duration(milliseconds: 700)); + + const png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0]; + expect(StoryGif.isGif(png), isFalse); + expect(StoryGif.parse(png), isNull); + expect(StoryGif.isGif(ascii.encode('GIF90a')), isFalse); + expect( + StoryGif.isGif(ascii.encode('GIF8')), + isFalse, + reason: 'too short', + ); + expect(StoryGif.parse([]), isNull); + }); + + test('a delay below 20 ms counts as 100 ms, the browser rule', () { + expect(StoryGif.frameDelay(Duration.zero), StoryGif.shortDelay); + expect( + StoryGif.frameDelay(const Duration(milliseconds: 10)), + const Duration(milliseconds: 100), + ); + expect( + StoryGif.frameDelay(const Duration(milliseconds: 19)), + const Duration(milliseconds: 100), + ); + expect( + StoryGif.frameDelay(const Duration(milliseconds: 20)), + const Duration(milliseconds: 20), + ); + }); + + test('a broken GIF has no known loop', () { + // Cut inside the second frame. + final cut = StoryGif.parse(gifFixture.sublist(0, 80))!; + expect(StoryGif.isGif(gifFixture.sublist(0, 80)), isTrue); + expect(cut.loop, isNull); + // An unknown block. + final garbled = Uint8List.fromList(gifFixture)..[0x2C] = 0x99; + expect(StoryGif.parse(garbled)!.loop, isNull); + // A header alone: no frames. + expect(StoryGif.parse(gifFixture.sublist(0, 13))!.loop, isNull); + }); + + test( + 'a GIF that ends after its last frame without a trailer still counts', + () { + final noTrailer = gifFixture.sublist(0, gifFixture.length - 1); + expect( + StoryGif.parse(noTrailer)!.loop, + const Duration(milliseconds: 700), + ); + }, + ); + }); + + group('StoryImage', () { + setUp(() { + StoriesImageBytes.instance = StoriesImageBytes( + fetch: (_) async => gifFixture, + ); + }); + tearDown(() => StoriesImageBytes.instance = StoriesImageBytes()); + + test('a GIF codec gives its first frame only, again and again', () async { + final codec = await ui.instantiateImageCodec(gifFixture); + final frames = >[ + for (var i = 0; i < 3; i++) + await _pixel((await codec.getNextFrame()).image), + ]; + expect(frames[0], isNot(frames[1]), reason: 'the fixture frames differ'); + + final still = StoryImage.firstFrame( + await ui.instantiateImageCodec(gifFixture), + ); + expect(still.frameCount, 1); + expect(still.repetitionCount, 0); + for (var i = 0; i < 4; i++) { + expect(await _pixel((await still.getNextFrame()).image), frames[0]); + } + still.dispose(); + }); + + testWidgets('a GIF cover shows its first frame', (tester) async { + const image = StoryImage('https://cdn.example/cover.gif'); + final emitted = []; + final listener = ImageStreamListener( + (info, _) => emitted.add(info.image), + ); + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Center(child: PersonalizationStoryCover(image: image)), + ), + ); + final stream = image.resolve(ImageConfiguration.empty) + ..addListener(listener); + addTearDown(() => stream.removeListener(listener)); + + // Decoding is real async; give a 700 ms loop time to come round twice. + final first = await tester.runAsync(() async { + await precacheImage(image, tester.element(find.byType(Center))); + await Future.delayed(const Duration(milliseconds: 1500)); + final codec = await ui.instantiateImageCodec(gifFixture); + return _pixel((await codec.getNextFrame()).image); + }); + await tester.pump(); + + expect(emitted, hasLength(1), reason: 'one frame, no animation'); + final shown = tester.widget(find.byType(RawImage)).image!; + expect(await tester.runAsync(() => _pixel(shown)), first); + }); + + testWidgets('other formats stay as NetworkImage draws them', ( + tester, + ) async { + final png = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + ); + StoriesImageBytes.instance = StoriesImageBytes(fetch: (_) async => png); + const image = StoryImage('https://cdn.example/photo.png'); + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Center(child: PersonalizationStoryCover(image: image)), + ), + ); + await tester.runAsync( + () => precacheImage(image, tester.element(find.byType(Center))), + ); + await tester.pump(); + final shown = tester.widget(find.byType(RawImage)).image!; + expect(shown.width, 1); + expect(const StoryImage('a'), const StoryImage('a')); + expect(const StoryImage('a'), isNot(const StoryImage('b'))); + }); + }); + + group('StoryGifPlayer', () { + final gif = StoryGif.parse(gifFixture)!; + late List codecs; + + setUp(() { + codecs = []; + StoryGifPlayer.codecOf = (_) async { + final codec = FakeGifCodec(3); + codecs.add(codec); + return codec; + }; + }); + tearDown(() => StoryGifPlayer.codecOf = ui.instantiateImageCodec); + + /// Lets the decoding of the next frame finish. + Future settle() => Future.delayed(Duration.zero); + + test( + 'frames follow their delays, loop, and wait while time stands', + () async { + final player = StoryGifPlayer(gifFixture, gif); + expect(player.frame, isNull); + await player.start(); + await settle(); + expect((player.index, player.frame!.width), (0, 1)); + + player.advance(const Duration(milliseconds: 99)); + expect(player.index, 0); + player.advance(const Duration(milliseconds: 1)); + expect((player.index, player.frame!.width), (1, 2)); + await settle(); + + // No time from the slide (it is paused): the frame stays. + await Future.delayed(const Duration(milliseconds: 150)); + expect(player.index, 1); + player.advance(const Duration(milliseconds: 60)); + expect(player.index, 1); + player.advance(const Duration(milliseconds: 40)); + expect(player.index, 2, reason: 'the rest of the paused frame'); + await settle(); + + player.advance(const Duration(milliseconds: 499)); + expect(player.index, 2, reason: 'the 500 ms frame'); + player.advance(const Duration(milliseconds: 1)); + expect(player.index, 0, reason: 'the loop starts over'); + expect(codecs, hasLength(1)); + player.dispose(); + expect(codecs.single.disposed, isTrue); + }, + ); + + test('restart begins at the first frame from the same bytes', () async { + final player = StoryGifPlayer(gifFixture, gif); + await player.start(); + await settle(); + player.advance(const Duration(milliseconds: 150)); + expect(player.index, 1); + + await player.restart(); + expect((player.index, player.frame!.width), (0, 1)); + expect(codecs, hasLength(2), reason: 'a new codec, no download'); + expect(codecs.first.disposed, isTrue); + await settle(); + player.advance(const Duration(milliseconds: 99)); + expect(player.index, 0); + player.advance(const Duration(milliseconds: 1)); + expect(player.index, 1); + player.dispose(); + }); + + test('a GIF the codec cannot read fails its start', () async { + StoryGifPlayer.codecOf = (_) async => throw Exception('broken'); + final player = StoryGifPlayer(gifFixture, gif); + await expectLater(player.start(), throwsException); + expect(player.frame, isNull); + player.dispose(); + }); + + testWidgets('real frames larger than the slide shrink to it', ( + tester, + ) async { + StoryGifPlayer.codecOf = ui.instantiateImageCodec; + await tester.runAsync(() async { + final player = StoryGifPlayer(gifFixture, gif, limit: const Size(1, 1)); + await player.start(); + expect(player.index, 0); + expect((player.frame!.width, player.frame!.height), (1, 1)); + player.dispose(); + + final full = StoryGifPlayer(gifFixture, gif); + await full.start(); + expect((full.frame!.width, full.frame!.height), (2, 2)); + full.dispose(); + }); + }); + }); +} + +/// The RGBA of the top-left pixel of [image]. +Future> _pixel(ui.Image image) async { + final data = await image.toByteData(); + return data!.buffer.asUint8List(0, 4).toList(); +} diff --git a/test/ui/stories_image_test.dart b/test/ui/stories_image_test.dart new file mode 100644 index 0000000..ceba693 --- /dev/null +++ b/test/ui/stories_image_test.dart @@ -0,0 +1,126 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_image.dart'; + +// No test binding here: the loader talks to a real loopback server. +void main() { + group('StoriesImageBytes', () { + late List fetched; + late Map> pending; + + StoriesImageBytes loader({int maxEntries = 4, int maxBytes = 1 << 20}) { + fetched = []; + pending = >{}; + return StoriesImageBytes( + maxEntries: maxEntries, + maxBytes: maxBytes, + fetch: (uri) { + fetched.add(uri.path); + return (pending[uri.path] = Completer()).future; + }, + ); + } + + Uint8List bytes(int size) => Uint8List(size); + + test( + 'one request per address; a slide background stays in memory', + () async { + final images = loader(); + final first = images.load('https://cdn.example/a.gif', keep: true); + final second = images.load('https://cdn.example/a.gif'); + expect(fetched, ['/a.gif']); + pending['/a.gif']!.complete(bytes(3)); + expect(await first, hasLength(3)); + expect(await second, hasLength(3)); + + // Kept: a restart or a return to the slide does not download again. + expect(await images.load('https://cdn.example/a.gif'), hasLength(3)); + expect(fetched, ['/a.gif']); + + // Evicted (Retry): downloaded again. + images.evict('https://cdn.example/a.gif'); + unawaited(images.load('https://cdn.example/a.gif')); + expect(fetched, ['/a.gif', '/a.gif']); + }, + ); + + test('a cover is not kept; a later keep request is honoured', () async { + final images = loader(); + final cover = images.load('https://cdn.example/c.jpg'); + final slide = images.load('https://cdn.example/c.jpg', keep: true); + pending['/c.jpg']!.complete(bytes(1)); + await cover; + await slide; + await images.load('https://cdn.example/c.jpg'); + expect(fetched, ['/c.jpg'], reason: 'kept for the slide'); + + unawaited(images.load('https://cdn.example/d.jpg')); + pending['/d.jpg']!.complete(bytes(1)); + await Future.delayed(Duration.zero); + unawaited(images.load('https://cdn.example/d.jpg')); + expect(fetched, ['/c.jpg', '/d.jpg', '/d.jpg']); + }); + + test('memory keeps the newest entries within both limits', () async { + final images = loader(maxEntries: 2, maxBytes: 10); + for (final name in ['a', 'b', 'c']) { + final load = images.load('https://cdn.example/$name', keep: true); + pending['/$name']!.complete(bytes(4)); + await load; + } + await images.load('https://cdn.example/c'); + await images.load('https://cdn.example/b'); + expect(fetched, ['/a', '/b', '/c'], reason: 'b and c kept'); + unawaited(images.load('https://cdn.example/a')); + expect(fetched.last, '/a', reason: 'a was the oldest'); + + final big = images.load('https://cdn.example/big', keep: true); + pending['/big']!.complete(bytes(11)); + await big; + unawaited(images.load('https://cdn.example/big')); + expect(fetched.last, '/big', reason: 'over the byte limit'); + }); + + test('a failure is not remembered', () async { + final images = loader(); + final failed = images.load('https://cdn.example/x', keep: true); + pending['/x']!.completeError(StateError('offline')); + await expectLater(failed, throwsStateError); + unawaited(images.load('https://cdn.example/x')); + expect(fetched, ['/x', '/x']); + }); + + test( + 'downloads like NetworkImage: a non-200 or empty answer fails', + () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + server.listen((request) { + final response = request.response; + switch (request.uri.path) { + case '/ok.gif': + response.add([0x47, 0x49, 0x46]); + case '/empty.gif': + break; + default: + response.statusCode = HttpStatus.notFound; + } + response.close(); + }); + final base = 'http://127.0.0.1:${server.port}'; + final images = StoriesImageBytes(); + expect(await images.load('$base/ok.gif'), [0x47, 0x49, 0x46]); + await expectLater( + images.load('$base/missing.gif'), + throwsA(isA()), + ); + await expectLater(images.load('$base/empty.gif'), throwsException); + }, + ); + }); +} diff --git a/test/ui/stories_mapping_test.dart b/test/ui/stories_mapping_test.dart new file mode 100644 index 0000000..080b286 --- /dev/null +++ b/test/ui/stories_mapping_test.dart @@ -0,0 +1,271 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/personalization_ui.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_support.dart'; + +StoryProduct _product({ + String promocode = '', + double discountPercent = 0, + double oldPrice = 0, + String withPromo = '', + double withPromoNumber = 0, +}) => StoryProduct( + id: 'p1', + name: 'Laptop', + price: 1190900, + priceFormatted: '1 190 900 ₽', + oldPrice: oldPrice, + oldPriceFormatted: oldPrice > 0 ? '${oldPrice.toInt()} ₽' : '', + discountPercent: discountPercent, + promocode: promocode, + priceWithPromocode: withPromoNumber, + priceWithPromocodeFormatted: withPromo, + url: 'https://shop.example/p1', + deeplinkAndroid: 'app://p1', +); + +StorySlide _slide({ + StorySlideType type = StorySlideType.image, + String background = 'https://cdn.example/1.jpg', + String color = '', + List elements = const [], +}) => StorySlide( + id: '1', + type: type, + background: background, + backgroundColor: color, + elements: elements, +); + +void main() { + group('price', () { + test('promo code: the promo price, the old price crossed out', () { + final price = storyPriceOf( + _product(promocode: 'P', oldPrice: 2000000, withPromo: '1 000 000 ₽'), + ); + expect(price.type, PersonalizationStoryPriceType.promoCode); + expect(price.price, '1 000 000 ₽'); + expect(price.oldPrice, '2000000 ₽'); + expect(price.promoCode, 'P'); + }); + + test('promo code without an old price crosses out the regular one', () { + final crossed = storyPriceOf( + _product(promocode: 'P', withPromo: '1 000 000 ₽'), + ); + expect(crossed.oldPrice, '1 190 900 ₽'); + final same = storyPriceOf( + _product(promocode: 'P', withPromo: '1 190 900 ₽'), + ); + expect(same.oldPrice, isNull, reason: 'the same price is not crossed'); + final numeric = storyPriceOf( + _product(promocode: 'P', withPromo: 'x', withPromoNumber: 1190900), + ); + expect(numeric.oldPrice, isNull, reason: 'numbers decide when sent'); + }); + + test('discount keeps a fractional percent; old price only if greater', () { + final discount = storyPriceOf(_product(discountPercent: 12.5)); + expect(discount.type, PersonalizationStoryPriceType.discount); + expect(discount.discount, '12.5%'); + expect(storyPriceOf(_product(discountPercent: 10)).discount, '10%'); + expect(storyPriceOf(_product(oldPrice: 245000)).oldPrice, isNull); + expect(storyPriceOf(_product(oldPrice: 2000000)).oldPrice, isNotNull); + }); + }); + + group('text block promo on a product slide', () { + /// A product slide whose text blocks carry [codes] (`null` — a block without one). + StorySlide promoSlide(List codes) => _slide( + background: '', + elements: [ + for (final code in codes) + StoryTextBlockElement(text: 'Use the code', promocode: code), + StoryProductElement(item: _product()), + ], + ); + + test('a product without a promo takes the text block code', () { + final slide = promoSlide([null, ' SALE10 ', 'LATER']); + final code = storySlidePromocode(slide); + expect(code, 'SALE10', reason: 'the first non-blank code, trimmed'); + final price = storyPriceOf( + _product(withPromo: '1 000 000 ₽', withPromoNumber: 1000000), + slidePromo: code, + ); + expect(price.type, PersonalizationStoryPriceType.promoCode); + expect(price.price, '1 190 900 ₽', reason: 'the regular price, big'); + expect(price.oldPrice, isNull, reason: 'no old price, nothing crossed'); + expect(price.promoCode, 'SALE10'); + // Promo beats discount, as for a product promo. + final discounted = storyPriceOf( + _product(discountPercent: 15), + slidePromo: code, + ); + expect(discounted.type, PersonalizationStoryPriceType.promoCode); + expect(discounted.discount, isNull); + }); + + test('the product promo wins over the text block one', () { + final price = storyPriceOf( + _product(promocode: 'OWN', withPromo: '1 000 000 ₽'), + slidePromo: storySlidePromocode(promoSlide(['SALE10'])), + ); + expect(price.promoCode, 'OWN'); + expect(price.price, '1 000 000 ₽'); + expect(price.oldPrice, '1 190 900 ₽'); + }); + + test('a "null" or blank text block code is no promo', () { + final slide = promoSlide(['null', ' ', '']); + expect(storySlidePromocode(slide), isNull); + final price = storyPriceOf( + _product(discountPercent: 10), + slidePromo: storySlidePromocode(slide), + ); + expect(price.type, PersonalizationStoryPriceType.discount); + expect(price.promoCode, isNull); + expect( + storyPriceOf(_product(), slidePromo: '').type, + PersonalizationStoryPriceType.price, + ); + }); + + test('only an old price above the regular one is crossed out', () { + for (final oldPrice in [1190900, 245000]) { + final price = storyPriceOf( + _product(oldPrice: oldPrice), + slidePromo: 'SALE10', + ); + expect(price.oldPrice, isNull, reason: 'oldprice $oldPrice ≤ price'); + } + final greater = storyPriceOf( + _product(oldPrice: 2000000), + slidePromo: 'SALE10', + ); + expect(greater.oldPrice, '2000000 ₽'); + expect(greater.price, '1 190 900 ₽'); + }); + }); + + group('slide', () { + test('media is a non-empty background, not the slide type', () { + expect(storyMediaOf(_slide()), StoryMedia.image); + expect(storyMediaOf(_slide(background: ' ')), StoryMedia.none); + expect( + storyMediaOf(_slide(type: StorySlideType.product)), + StoryMedia.image, + ); + expect( + storyMediaOf(_slide(type: StorySlideType.video)), + StoryMedia.video, + ); + }); + + test('the letterbox is background_color, else black', () { + expect(storyLetterbox(_slide(color: '#FF0000')), const Color(0xFFFF0000)); + expect(storyLetterbox(_slide()), const Color(0xFF000000)); + }); + + test('scrim: 50% only on bare media, 30% otherwise', () { + expect(storyScrimOpacity(_slide()), 0.5); + expect( + storyScrimOpacity( + _slide(elements: const [StoryTextBlockElement(text: ' ')]), + ), + 0.5, + reason: 'a blank text block does not count', + ); + expect( + storyScrimOpacity( + _slide(elements: const [StoryTextBlockElement(text: 'Sale')]), + ), + 0.3, + ); + expect( + storyScrimOpacity( + _slide(elements: [StoryProductElement(item: _product())]), + ), + 0.3, + ); + expect(storyScrimOpacity(_slide(background: '')), 0.3); + }); + + test('only positive integer ids are tracked', () { + expect(storyTrackableId('36'), isTrue); + expect(storyTrackableId('39_0'), isFalse); + expect(storyTrackableId('0'), isFalse); + expect(storyTrackableId('-3'), isFalse); + expect(storyTrackableId(''), isFalse); + }); + }); + + group('links and texts', () { + test('a product slide button: its own link first, else the product', () { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final product = _product(); + expect( + storySlideButtonLink( + const StoryButtonElement(title: 'Buy', link: 'w', linkAndroid: 'a'), + product, + ), + 'a', + ); + expect( + storySlideButtonLink(const StoryButtonElement(title: 'Buy'), product), + 'app://p1', + ); + }); + + test('promo caption: the admin title, else the host text', () { + expect( + storyPromoCaption(const StoryProductElement(title: 'Code'), 'Promo'), + 'Code', + ); + expect( + storyPromoCaption(const StoryProductElement(title: ' '), 'Promo'), + 'Promo', + ); + }); + + test('text blocks: blank ones skipped, alignment and line height', () { + final slide = _slide( + elements: const [ + StoryTextBlockElement(text: ''), + StoryTextBlockElement(text: 'Big', fontSize: 48, textAlign: 'end'), + ], + ); + final texts = storyTextBlocks(slide); + expect(texts, hasLength(1)); + final block = storyTextBlock(texts.single); + expect(block.textAlign, TextAlign.end); + expect(block.lineHeight, 1); + expect(storyTextAlign('left'), TextAlign.start); + expect(storyTextAlign('right'), TextAlign.end); + expect(storyTextAlign('center'), TextAlign.center); + }); + }); + + test('repeated story ids and stories without slides are dropped', () { + Story story(Object id, String name, {bool slides = true}) => Story.fromJson( + { + 'id': id, + 'name': name, + 'slides': slides + ? >[ + {'id': 1, 'type': 'image', 'background': 'x'}, + ] + : >[], + }, + ); + final list = playableStories([ + story(7, 'first'), + story(8, 'empty', slides: false), + story('7', 'again'), + story(9, 'other'), + ]); + expect(list.map((s) => s.name), ['first', 'other']); + }); +} diff --git a/test/ui/stories_media_cache_test.dart b/test/ui/stories_media_cache_test.dart new file mode 100644 index 0000000..6289f96 --- /dev/null +++ b/test/ui/stories_media_cache_test.dart @@ -0,0 +1,100 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_media_cache.dart'; + +void main() { + late HttpServer server; + late Directory root; + final requests = []; + + setUp(() async { + requests.clear(); + root = await Directory.systemTemp.createTemp('stories_cache_test'); + server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((request) { + requests.add(request.uri.path); + final size = int.parse(request.uri.queryParameters['size'] ?? '10'); + final response = request.response; + // Chunked: the length is not known up front. + if (request.uri.queryParameters['chunked'] != null) { + response.headers.chunkedTransferEncoding = true; + } else { + response.contentLength = size; + } + response + ..add(List.filled(size, 7)) + ..close(); + }); + }); + + tearDown(() async { + await server.close(force: true); + await root.delete(recursive: true); + }); + + String url(String name, {int size = 10, bool chunked = false}) => + 'http://127.0.0.1:${server.port}/$name.mp4?size=$size' + '${chunked ? '&chunked=1' : ''}'; + + test('each file downloads once, also when asked twice at once', () async { + final cache = StoriesMediaCache(directory: () async => root); + final results = await Future.wait([ + cache.fetch(url('a')), + cache.fetch(url('a')), + ]); + expect(results[0]!.path, results[1]!.path); + expect(results[0]!.path, endsWith('.mp4')); + expect(await results[0]!.length(), 10); + + await cache.fetch(url('a')); + expect(requests, ['/a.mp4'], reason: 'the second fetch reads the file'); + }); + + test('over the limit, the least recently opened files go', () async { + final cache = StoriesMediaCache(maxBytes: 250, directory: () async => root); + final a = await cache.fetch(url('a', size: 100)); + await Future.delayed(const Duration(milliseconds: 20)); + final b = await cache.fetch(url('b', size: 100)); + await Future.delayed(const Duration(milliseconds: 20)); + await cache.fetch(url('a', size: 100)); // a is fresh again + await Future.delayed(const Duration(milliseconds: 20)); + await cache.fetch(url('c', size: 100)); + + expect(await a!.exists(), isTrue); + expect(await b!.exists(), isFalse); + }); + + test('a lookup never downloads; a filled file is found next time', () async { + final cache = StoriesMediaCache(directory: () async => root); + expect(await cache.cached(url('a')), isNull); + expect(requests, isEmpty); + + cache.fill(url('a')); + cache.fill(url('a')); + final file = await cache.fetch(url('a')); + expect(await cache.cached(url('a')), isNotNull); + expect((await cache.cached(url('a')))!.path, file!.path); + expect(requests, ['/a.mp4'], reason: 'one download per address'); + }); + + test('a file over the limit is cut short and never fetched again', () async { + final cache = StoriesMediaCache(maxBytes: 250, directory: () async => root); + expect(await cache.fetch(url('big', size: 300)), isNull); + expect(await cache.fetch(url('big', size: 300)), isNull); + expect(requests, ['/big.mp4']); + + // Without a length up front, the download stops on the first byte too many. + expect(await cache.fetch(url('chunk', size: 300, chunked: true)), isNull); + expect(await cache.fetch(url('chunk', size: 300, chunked: true)), isNull); + expect(requests, ['/big.mp4', '/chunk.mp4']); + expect(root.listSync(), isEmpty, reason: 'no part files are left'); + }); + + test('HLS is left to the player', () async { + final cache = StoriesMediaCache(directory: () async => root); + expect(await cache.fetch('https://cdn.example/clip.m3u8'), isNull); + expect(await cache.cached('https://cdn.example/clip.m3u8'), isNull); + expect(StoriesMediaCache.cacheable('https://cdn.example/clip.mp4'), isTrue); + }); +} diff --git a/test/ui/stories_playback_test.dart b/test/ui/stories_playback_test.dart new file mode 100644 index 0000000..86cf5bf --- /dev/null +++ b/test/ui/stories_playback_test.dart @@ -0,0 +1,285 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/src/stories/stories_response.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_playback.dart'; + +/// A story with [count] slides `0`, `1`, … lasting 5 s each. +Story _story(String id, int count, {bool viewed = false, int start = 0}) => + Story( + id: id, + name: id, + avatar: '', + viewed: viewed, + startPosition: start, + slides: [ + for (var i = 0; i < count; i++) + StorySlide( + id: '$id$i', + type: StorySlideType.image, + duration: const Duration(seconds: 5), + ), + ], + ); + +/// Opens [playback] the way the viewer does: the first page settles, media is ready. +StoriesPlayback _open(StoriesPlayback playback) { + playback.settle(playback.storyIndex); + playback.mediaReady(playback.generation); + return playback; +} + +void main() { + group('start slide', () { + test('nothing seen: the server start_position, clamped', () { + expect(StoriesPlayback.startSlideOf(_story('a', 3, start: 2), {}), 2); + expect(StoriesPlayback.startSlideOf(_story('a', 3, start: 9), {}), 2); + expect(StoriesPlayback.startSlideOf(_story('a', 3, start: -1), {}), 0); + }); + + test('partly seen: the first unseen slide in order', () { + final story = _story('a', 4, start: 3); + expect(StoriesPlayback.startSlideOf(story, {'a0', 'a2'}), 1); + expect(StoriesPlayback.startSlideOf(story, {'a1'}), 0); + }); + + test('viewed by the server or fully seen: the first slide', () { + expect( + StoriesPlayback.startSlideOf(_story('a', 3, viewed: true), {'a0'}), + 0, + ); + final story = _story('a', 2, start: 1); + expect(StoriesPlayback.startSlideOf(story, {'a0', 'a1'}), 0); + expect(StoriesPlayback.isViewed(story, {'a0', 'a1'}), isTrue); + expect(StoriesPlayback.isViewed(story, {'a0'}), isFalse); + }); + }); + + group('navigation', () { + test('slides, then the next story on settle, then close', () { + final playback = _open( + StoriesPlayback(stories: [_story('a', 2), _story('b', 1)]), + ); + expect(playback.slide.id, 'a0'); + + expect(playback.next(), StoriesStep.slide); + expect(playback.slide.id, 'a1'); + + expect(playback.next(), StoriesStep.turn); + expect(playback.turnTarget, 1); + expect(playback.pausedBy(StoriesPauseReason.drag), isTrue); + expect(playback.next(), StoriesStep.none, reason: 'turning'); + expect( + playback.seenOf('b'), + isEmpty, + reason: 'not entered before settle', + ); + + expect(playback.settle(1), isTrue); + expect(playback.slide.id, 'b0'); + expect(playback.seenOf('b'), {'b0'}); + playback.mediaReady(playback.generation); + + expect(playback.next(), StoriesStep.close); + }); + + test('back on the first slide of the first story restarts it', () { + final playback = _open(StoriesPlayback(stories: [_story('a', 2)])); + playback.mediaReady(playback.generation); + playback.tick(const Duration(seconds: 2)); + final generation = playback.generation; + + expect(playback.previous(), StoriesStep.restart); + expect(playback.slide.id, 'a0'); + expect(playback.generation, generation, reason: 'no new entry'); + expect(playback.elapsed, Duration.zero); + expect(playback.running, isTrue, reason: 'the media stays ready'); + }); + + test('back into the previous story opens its start slide', () { + final playback = _open( + StoriesPlayback( + stories: [_story('a', 3), _story('b', 1)], + initialStory: 1, + seen: { + 'a': {'a0'}, + }, + ), + ); + expect(playback.slide.id, 'b0'); + expect(playback.previous(), StoriesStep.turn); + expect(playback.turnTarget, 0); + playback.settle(0); + expect(playback.slide.id, 'a1', reason: 'the first unseen'); + }); + + test('a peeked page that springs back is not entered', () { + final playback = _open( + StoriesPlayback(stories: [_story('a', 1), _story('b', 1)]), + ); + playback.pause(StoriesPauseReason.drag); + expect(playback.settle(0), isFalse); + expect(playback.running, isTrue); + expect(playback.seenOf('b'), isEmpty); + }); + + test('stories without slides are dropped, the index follows', () { + final playback = StoriesPlayback( + stories: [_story('a', 1), _story('empty', 0), _story('b', 1)], + initialStory: 2, + ); + expect(playback.stories.map((story) => story.id), ['a', 'b']); + expect(playback.storyIndex, 1); + expect(StoriesPlayback(stories: [_story('x', 0)]).isEmpty, isTrue); + }); + }); + + group('pause reasons and the clock', () { + test('the clock runs only with no reason, in real deltas', () { + final playback = StoriesPlayback(stories: [_story('a', 2)]); + playback.settle(0); + expect(playback.pausedBy(StoriesPauseReason.loading), isTrue); + expect(playback.tick(const Duration(seconds: 9)), isFalse); + expect(playback.elapsed, Duration.zero, reason: 'loading'); + + playback.mediaReady(playback.generation); + playback.pause(StoriesPauseReason.hold); + playback.pause(StoriesPauseReason.background); + expect(playback.tick(const Duration(seconds: 1)), isFalse); + playback.resume(StoriesPauseReason.hold); + expect(playback.running, isFalse, reason: 'still in the background'); + playback.resume(StoriesPauseReason.background); + expect(playback.running, isTrue); + + // A frame gap (e.g. right after returning) counts for at most a second. + playback.tick(const Duration(minutes: 5)); + expect(playback.elapsed, StoriesPlayback.maxTick); + expect(playback.progress, closeTo(0.2, 1e-9)); + for (var i = 0; i < 3; i++) { + expect(playback.tick(const Duration(seconds: 1)), isFalse); + } + expect(playback.tick(const Duration(seconds: 1)), isTrue); + }); + + test('a video slide lasts the video and follows its position', () { + final playback = _open(StoriesPlayback(stories: [_story('a', 1)])); + playback.useVideoDuration(const Duration(seconds: 30)); + expect(playback.followsVideo, isTrue); + playback.syncVideoPosition(const Duration(seconds: 15)); + expect(playback.progress, closeTo(0.5, 1e-9)); + playback.syncVideoPosition(const Duration(seconds: 30)); + expect( + playback.tick(const Duration(seconds: 1)), + isFalse, + reason: 'the video itself ends the slide', + ); + playback.useVideoDuration(Duration.zero); + expect(playback.duration, const Duration(seconds: 30)); + }); + + test( + 'a GIF slide lasts the server time or one loop, whichever is longer', + () { + // The server says 5 s; an 8 s loop plays exactly once. + final playback = _open(StoriesPlayback(stories: [_story('a', 2)])); + playback.useGifLoop(const Duration(seconds: 8)); + expect(playback.duration, const Duration(seconds: 8)); + expect(playback.followsVideo, isFalse, reason: 'the clock ends it'); + for (var i = 0; i < 7; i++) { + expect(playback.tick(const Duration(seconds: 1)), isFalse); + } + expect(playback.tick(const Duration(seconds: 1)), isTrue); + + // A 700 ms loop repeats until the server's 5 s are up. + playback.next(); + playback.mediaReady(playback.generation); + playback.useGifLoop(const Duration(milliseconds: 700)); + expect(playback.duration, const Duration(seconds: 5)); + + // An unknown loop (a host image, a broken GIF): the server time. + playback.useGifLoop(const Duration(seconds: 8)); + playback.useGifLoop(null); + expect(playback.duration, const Duration(seconds: 5)); + }, + ); + + test('a paused GIF slide keeps its time; retry measures it again', () { + final playback = _open(StoriesPlayback(stories: [_story('a', 1)])); + playback.useGifLoop(const Duration(seconds: 8)); + playback.tick(const Duration(seconds: 1)); + for (final reason in [ + StoriesPauseReason.hold, + StoriesPauseReason.sheet, + StoriesPauseReason.background, + StoriesPauseReason.host, + ]) { + playback.pause(reason); + expect(playback.running, isFalse, reason: '$reason stops the clock'); + expect(playback.tick(const Duration(seconds: 1)), isFalse); + playback.resume(reason); + } + expect(playback.elapsed, const Duration(seconds: 1)); + + playback.mediaFailed(playback.generation); + playback.retry(); + expect( + playback.duration, + const Duration(seconds: 5), + reason: 'unmeasured', + ); + }); + + test('a failed load pauses until retry; old loads are ignored', () { + final playback = StoriesPlayback(stories: [_story('a', 1)]); + playback.settle(0); + final first = playback.generation; + playback.mediaFailed(first); + expect(playback.pausedBy(StoriesPauseReason.error), isTrue); + + final second = playback.retry(); + expect(second, greaterThan(first)); + expect(playback.pausedBy(StoriesPauseReason.error), isFalse); + expect(playback.pausedBy(StoriesPauseReason.loading), isTrue); + playback.mediaReady(first); + expect(playback.running, isFalse, reason: 'a stale load'); + playback.mediaReady(second); + expect(playback.running, isTrue); + expect(playback.seenOf('a'), {'a0'}); + }); + }); + + group('products sheet', () { + test('pauses, blocks navigation, resets on a slide change', () { + final playback = _open( + StoriesPlayback(stories: [_story('a', 2), _story('b', 1)]), + ); + expect(playback.openSheet(), isTrue); + expect(playback.running, isFalse); + expect(playback.next(), StoriesStep.none); + expect(playback.previous(), StoriesStep.none); + expect(playback.slide.id, 'a0'); + + expect(playback.closeSheet(), isTrue); + expect(playback.running, isTrue); + playback.openSheet(); + // A programmatic jump to another story closes it. + expect(playback.turnTo(1), StoriesStep.turn); + expect(playback.sheetOpen, isFalse); + playback.settle(1); + expect(playback.sheetOpen, isFalse); + }); + + test('entering a slide closes an open sheet', () { + final playback = _open(StoriesPlayback(stories: [_story('a', 2)])); + playback.openSheet(); + playback.closeSheet(); + playback.next(); + playback.mediaReady(playback.generation); + playback.openSheet(); + playback.settle(0); + expect(playback.sheetOpen, isTrue, reason: 'same story: no new entry'); + playback.closeSheet(); + playback.previous(); + expect(playback.sheetOpen, isFalse); + expect(playback.reasons, {StoriesPauseReason.loading}); + }); + }); +} diff --git a/test/ui/stories_runtime_test.dart b/test/ui/stories_runtime_test.dart new file mode 100644 index 0000000..8bf6bb8 --- /dev/null +++ b/test/ui/stories_runtime_test.dart @@ -0,0 +1,91 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:rees46_sdk/rees46_sdk.dart'; +import 'package:rees46_sdk/src/pigeon/personalization_api.g.dart' as pigeon; +import 'package:rees46_sdk/src/ui/widgets/stories_seen_store.dart'; +import 'package:rees46_sdk/src/ui/widgets/stories_sound.dart'; + +class _FakeHostApi extends pigeon.PersonalizationHostApi { + final Map> stored = >{ + '40': ['36'], + }; + final List writes = []; + final List audio = []; + int reads = 0; + + @override + Future>> getStoriesSeen(String shop) async { + reads++; + return shop == 'shop-a' ? stored : >{}; + } + + @override + Future setStorySlideSeen( + String shop, + String storyId, + String slideId, + ) async => writes.add('$shop/$storyId/$slideId'); + + @override + Future beginStoriesAudio() async => audio.add('begin'); + + @override + Future updateStoriesAudio(bool muted) async => + audio.add(muted ? 'muted' : 'sound'); + + @override + Future endStoriesAudio() async => audio.add('end'); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('seen slides load once per shop and every mark is stored', () async { + final api = _FakeHostApi(); + final store = StoriesSeenStore(); + final sdk = PersonalizationSdk(api: api, shopId: 'shop-a'); + + expect(await store.load(sdk), >{ + '40': {'36'}, + }); + store.mark(sdk, '40', '37'); + store.mark(sdk, '40', '37'); + expect(await store.load(sdk), >{ + '40': {'36', '37'}, + }); + expect(api.reads, 1); + expect(api.writes, ['shop-a/40/37']); + }); + + test('without the platform store, seen slides live in memory', () async { + final store = StoriesSeenStore(); + // The real host API: no platform in tests, the channel fails. + final sdk = PersonalizationSdk(shopId: 'shop-x'); + expect(await store.load(sdk), isEmpty); + store.mark(sdk, '1', '2'); + expect(store.seen(sdk), >{ + '1': {'2'}, + }); + }); + + test('sound: muted first, volume up unmutes, the session follows', () async { + final api = _FakeHostApi(); + StoriesSound.api = api; + final sound = StoriesSound.instance; + addTearDown(() => sound.muted.value = true); + expect(sound.muted.value, isTrue); + + sound.attach(); + await sound.beforeVideo(); + await sound.afterVideo(); + await simulateKeyDownEvent(LogicalKeyboardKey.audioVolumeUp); + expect(sound.muted.value, isFalse); + await Future.delayed(Duration.zero); + + sound.toggle(); + sound.detach(); + await Future.delayed(Duration.zero); + expect(api.audio, ['begin', 'muted', 'sound', 'muted', 'end']); + expect(sound.muted.value, isTrue, reason: 'the choice outlives a viewer'); + }); +}