From 7deed9648bcad1e4574f9aa7bb3786614f8daf2c Mon Sep 17 00:00:00 2001 From: Akylbek Utekeshev Date: Mon, 7 Sep 2026 12:41:01 +0500 Subject: [PATCH 01/16] =?UTF-8?q?MOBILE-342:=20=D0=9F=D1=83=D0=B1=D0=BB?= =?UTF-8?q?=D0=B8=D1=87=D0=BD=D0=BE=D0=B5=20API=20=D0=B2=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=B5=D0=BD=D0=BD=D1=8B=D1=85=20=D0=B1=D0=BB=D0=BE=D0=BA?= =?UTF-8?q?=D0=BE=D0=B2=20(#220)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * MOBILE-342: Add the embedded block as a Fabric component over the native block * MOBILE-342: Follow mission/stories — a live height and a place name taken as it is * MOBILE-342: Answer the review — a nameless place collapses, a sizeless one waits * MOBILE-342: Say the same about a zero, a negative and a not-a-number height * MOBILE-342: Leave the pinned version alone and keep the notes to the public API The SDK version was only lifted into a variable, not changed — and a branch that changes nothing about it should not touch the line at all. The two dependencies the block needs are spelled with the version develop already pins. The notes stay where a caller reads them: the props, the outcomes and the component itself. The native sides, the codegen spec and the suite carry none. * MOBILE-342: Draw the embedded block in the old renderer too The block was a Fabric component and nothing else: `RCTViewComponentView` and the generated `MindboxSdkSpec` descriptors, with no guard. An app on the old renderer does not install `React-RCTFabric` or `React-Fabric`, so those headers are not there to include and the pod does not build at all — and this branch's develop base is the old renderer. So the file now carries both, split on `RCT_NEW_ARCH_ENABLED`: the component view as it was, and an `RCTViewManager` whose exported name React Native reads as `MindboxEmbeddedBlockView` once it drops the `Manager` suffix — the same name `codegenNativeComponent` falls back to asking for when there is no generated view config. The block itself is untouched. `MindboxEmbeddedBlockHost` is plain UIKit, so both paths drive the same host in the same order, and the old renderer's view builds it from `didSetProps:` and `layoutSubviews` for the reason Fabric builds it from `finalizeUpdates:` — the props of a transaction and the frame of a layout pass do not arrive together, and either one can be last. * MOBILE-342: Let the pinned toolchain typecheck the block and run its tests The block was the first thing under `src/` to write JSX and the first to import the codegen vocabulary, and the toolchain this repo pins — `react-native@0.63.4` with `@types/react-native@0.62.13` — describes neither. On a clean checkout that is eleven errors where `src/` had none: React Native 0.63 ships `CodegenTypes` and `codegenNativeComponent` as JavaScript with no declarations beside them, and `ViewProps`/`TextProps` of that vintage have no `children`. The two declaration files say what the pins leave out. The spec keeps importing the codegen types from the paths the native generator expects — declaring them is what lets that stay true rather than be worked around — and the `children` file is an augmentation, which is why it carries an `export {}`: without it the `declare module` would replace React Native's typings instead of adding to them. Both are marked for deletion once the pinned React Native ships its own types. `react-test-renderer` was missing outright, so the block's test suite could not start. Verified in an environment with only this repo's own `node_modules` on the resolution path: tsc clean, 52 tests passing. Worth knowing for anyone checking locally — this working copy sits under a parent folder that carries its own `react-native@0.82.1`, and TypeScript walks up into it, so a plain `npx tsc` here reports a different set of errors than a clean clone does. * MOBILE-342: Tell React Native this pod carries a Fabric component The podspec asked for React-Core and nothing else, and that is the one place where `RCT_NEW_ARCH_ENABLED` gets defined for a library's own sources — React Native sets it through `install_modules_dependencies` and nowhere else. Left out, the flag is simply absent from this pod's build settings, so `MindboxEmbeddedBlockView.mm` compiled its old-renderer half on React Native 0.82, where there is no old renderer to compile it for, and the Fabric component was never registered. The call also brings in what a Fabric component actually needs to build — React-RCTFabric, ReactCodegen, React-Fabric and the rest — and on the old renderer it adds the same pods but leaves the flag undefined, which is how the file's other half keeps being the one that compiles. Verified by running the example on both renderers: React Native 0.82 bridgeless (the stand reports the block's outcome and its own placeholder holds while `active` is false) and React Native 0.74 on the old renderer (a failed block collapses to zero and a paused one keeps its height). * MOBILE-342: Stop warning about space the SDK trims off itself The component told the host that a place system name is taken exactly as given, that space around it is part of the name, and that such a block will not match its place. None of that is true on either platform: iOS normalizes the name with `trimmingCharacters(in: .whitespacesAndNewlines)` before it resolves, and Android with `orNullIfBlank()`. A padded name finds its place, and the warning sent the host looking for a bug that was not there. What stays is the empty name, where the same trimming is what makes it empty: nothing is left to resolve by, the place reports a failure, and that is worth a word. Checked against the branches this API is being written for — ios-sdk `mission/stories` and android-sdk `feature/MOBILE-413`. * MOBILE-342: Keep the lint clean, and say why the one style stays inline `develop` reports nothing at all, and this branch was leaving a single `react-native/no-inline-styles` warning behind — CI does not fail on warnings, so it would simply have sat there for the next person to wonder about. The style stays where it is: the container's height is the host's number while the block occupies its place and zero once it hands it back, so there is no StyleSheet entry it could be. The rule is switched off for that one line, with the reason next to it rather than in a commit nobody reads. * MOBILE-342: Let the package build where the checkout is not alone `yarn prepare` — the build that makes the published package — failed on the definitions: Type 'NativeSyntheticEvent>' is not assignable to type 'NativeSyntheticEvent<{ appearance: string; }>'. Types of property 'currentTarget' are incompatible. Type 'NativeMethods' is not assignable to type 'number'. Two names for one event, and they only agree while both resolve to the same React Native. Here they did not: this checkout sits inside a host app that carries its own React Native, TypeScript walks up into it, and the spec's `NativeSyntheticEvent` came from there while the container's came from the pinned `@types/react-native` — a `currentTarget` that is a view on one side and a number on the other. The alone-in-a-folder case built fine, which is exactly why this was worth catching: the submodule layout is the one people actually work in. The container's handler now takes its type from the prop it is passed to, so there is only ever one event type in play and nothing left to disagree about. Both layouts build: commonjs, module and the definitions. * MOBILE-342: Let a host app point the wrapper at a local native SDK The Android module was pinned to `cloud.mindbox:mobile-sdk:2.15.4`, and the embedded block hooks are in no released version of it — so the module could not be compiled at all. The build stopped on `Unresolved reference 'embedded'` in every file the block touches, and there was no way to say otherwise short of editing this file. The version is a property now, defaulting to the same release, so nothing changes for anyone building against a published SDK. A host app that needs the hooks before they ship sets `ext.nativeSdkVersion` in its root project or passes `-PMindboxSdk_nativeSdkVersion=...` — this is what the New Architecture branch had and what the develop-based one lost, and it is how the module was verified: built against the locally published `2.15.3-rn-local`, debug and release, with codegen writing `MindboxEmbeddedBlockViewManagerInterface` and `...Delegate` and the AAR carrying the host view, the manager and both. The `mindbox-common` line moves to the same property for the same reason, and both dependencies now say next to them why they are there at all. * MOBILE-342: Take the native SDK version knob back out Reverts the property added in ba96dc2 — the Android dependency is a hardcoded 2.15.4 again, as it was on develop. Asked for by the author, who will shape this part themselves. Worth knowing while that is open: the embedded block hooks are in no released native SDK, so the Android module cannot be compiled against this pin — the build stops on `Unresolved reference 'embedded'` in every file the block touches. iOS does not have the same problem only because the numbers happen to line up: the local iOS SDK calls itself 2.15.3, which is what the podspec asks for, so an app can point at it with `:path` and satisfy the pin. The Android build of the same SDK is published as `2.15.3-rn-local`, a different version string, which a hardcoded 2.15.4 cannot match from the app side. * MOBILE-342: Say which React Native the package needs The Android module applies the com.facebook.react Gradle plugin and the block's glue comes out of Codegen, both of which appeared in React Native 0.71. The peer dependency said any version would do; now it says 0.71 or newer, and the README says why. * MOBILE-342: Warn from an effect, not from the render body React may run a render more than once for one commit, and a ref flipped during render does not keep a warning from being said twice under StrictMode. An effect runs once per commit, so the three warnings move there. --------- Co-authored-by: Vailence --- MindboxSdk.podspec | 16 +- README.md | 52 +++ android/build.gradle | 3 + .../java/com/mindboxsdk/MindboxSdkPackage.kt | 3 +- .../embedded/MindboxEmbeddedBlockEvents.kt | 41 ++ .../embedded/MindboxEmbeddedBlockHostView.kt | 217 +++++++++++ .../MindboxEmbeddedBlockViewManager.kt | 94 +++++ .../MindboxEmbeddedBlockHost.swift | 91 +++++ ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm | 354 ++++++++++++++++++ package.json | 17 +- src/MindboxEmbeddedBlock.tsx | 214 +++++++++++ src/MindboxEmbeddedBlockNativeComponent.ts | 29 ++ src/__tests__/MindboxEmbeddedBlock.test.tsx | 220 +++++++++++ src/index.tsx | 4 + src/react-native-children.d.ts | 26 ++ src/react-native-codegen.d.ts | 53 +++ yarn.lock | 23 +- 17 files changed, 1450 insertions(+), 7 deletions(-) create mode 100644 android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt create mode 100644 android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt create mode 100644 android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt create mode 100644 ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift create mode 100644 ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm create mode 100644 src/MindboxEmbeddedBlock.tsx create mode 100644 src/MindboxEmbeddedBlockNativeComponent.ts create mode 100644 src/__tests__/MindboxEmbeddedBlock.test.tsx create mode 100644 src/react-native-children.d.ts create mode 100644 src/react-native-codegen.d.ts diff --git a/MindboxSdk.podspec b/MindboxSdk.podspec index b5e72a2..206aeaa 100644 --- a/MindboxSdk.podspec +++ b/MindboxSdk.podspec @@ -15,8 +15,20 @@ Pod::Spec.new do |s| s.source_files = "ios/**/*.{h,m,mm,swift}" - s.dependency "React-Core" - s.dependency "Mindbox", "2.15.3" s.dependency "MindboxNotifications", "2.15.3" + + # The embedded block is a native component, and on the new renderer that means a Fabric component: + # this brings in the renderer's own pods and, the part that decides everything, defines + # `RCT_NEW_ARCH_ENABLED` for our sources — what `MindboxEmbeddedBlockView.mm` splits on. React + # Native defines it for a library's own pod only through this call and nowhere else, so without it + # the file compiles its old-renderer half even on a React Native that no longer has one. + # + # On the old renderer the same call settles for React-Core and leaves the flag undefined, which is + # how the other half of that file gets compiled instead. + if respond_to?(:install_modules_dependencies, true) + install_modules_dependencies(s) + else + s.dependency "React-Core" + end end diff --git a/README.md b/README.md index 2d8c1e9..4f101aa 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,9 @@ Follow the installation process detailed [here](https://developers.mindbox.ru/do ```markdown npm i --save mindbox-sdk ``` + The package requires React Native 0.71 or newer: the embedded block is a native component whose + glue is generated by React Native Codegen, and the Android module applies the + `com.facebook.react` Gradle plugin to run it. Both work on the old and the new architecture. 2. For iOS, make sure to install the pods: ```markdown @@ -31,6 +34,55 @@ Initialize the Mindbox SDK in your React Native app. You can find the necessary Learn how to send events to Mindbox. Different operations and their usage are detailed [here](https://developers.mindbox.ru/docs/integration-actions-react-native). +### Embedded Blocks + +Mark a place in your layout with `MindboxEmbeddedBlock` and the SDK decides what goes into it from +the admin panel — the app never learns what the content is, and it can change without a release. +The host owns the size: pass the `height` the block should occupy. A place that ends up without +content collapses to zero height and hands the space back. + +```tsx +import { MindboxEmbeddedBlock } from 'mindbox-sdk'; + + +``` + +Both outcomes can be customized, the same way as in SwiftUI, Compose and Flutter: `placeholder` +replaces the stock loading shimmer, and `error` opts into showing a failure instead of collapsing. +An empty place always collapses — a host cannot fill the space of a block that was never meant to +be there. `onLoad` and `onFail` report how the load ended. + +```tsx +} + error={} + onFail={() => setShowStoriesSection(false)} +/> +``` + +How long a block may wait for its content before it gives the place back is `timeoutMs`. Left out, +it is the SDK's own budget of 30 seconds. The wait is the user's: it is counted only while the +screen the block stands on is the one being looked at — and since every React Native screen lives +in the same native window, the block cannot see that for itself. Pass `active` from the navigation +(`useIsFocused()` in React Navigation), or a block behind a pushed screen will spend its budget on +a screen nobody is looking at. + +```tsx + +``` + +`height` is live: a new value resizes a block already on screen in place — the same content, no +reload. It has to be positive, though: a block given no space to occupy is never loaded and reports +no outcome. `timeoutMs` is fixed when the block is created — a new value is ignored with a warning; +give the component a new `key` to load a block on a new budget. + ### Push Notifications Mindbox SDK aids in handling push notifications. It offers configurations and usage instructions, found in the SDK documentation [Android(FCM)](https://developers.mindbox.ru/docs/firebase-send-push-notifications-react-native), [Android(HCM)](https://developers.mindbox.ru/docs/huawei-send-push-notifications-react-native), [IOS](https://developers.mindbox.ru/docs/ios-send-push-notifications-react-native) and [IOS(Rich)](https://developers.mindbox.ru/docs/ios-send-rich-push-react-native). diff --git a/android/build.gradle b/android/build.gradle index 4126851..c687848 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -16,6 +16,7 @@ buildscript { apply plugin: 'com.android.library' apply plugin: 'kotlin-android' +apply plugin: "com.facebook.react" def getExtOrDefault(name) { return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['MindboxSdk_' + name] @@ -127,4 +128,6 @@ dependencies { api 'com.facebook.react:react-native:+' implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" api 'cloud.mindbox:mobile-sdk:2.15.4' + implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.7" + compileOnly 'cloud.mindbox:mindbox-common:2.15.4' } diff --git a/android/src/main/java/com/mindboxsdk/MindboxSdkPackage.kt b/android/src/main/java/com/mindboxsdk/MindboxSdkPackage.kt index 148b1c1..637b938 100644 --- a/android/src/main/java/com/mindboxsdk/MindboxSdkPackage.kt +++ b/android/src/main/java/com/mindboxsdk/MindboxSdkPackage.kt @@ -4,6 +4,7 @@ import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager +import com.mindboxsdk.embedded.MindboxEmbeddedBlockViewManager class MindboxSdkPackage : ReactPackage { @@ -12,6 +13,6 @@ class MindboxSdkPackage : ReactPackage { } override fun createViewManagers(reactContext: ReactApplicationContext): List> { - return emptyList() + return listOf(MindboxEmbeddedBlockViewManager()) } } diff --git a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt new file mode 100644 index 0000000..a4a04e0 --- /dev/null +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt @@ -0,0 +1,41 @@ +package com.mindboxsdk.embedded + +import com.facebook.react.bridge.Arguments +import com.facebook.react.bridge.WritableMap +import com.facebook.react.uimanager.events.Event + +internal class AppearanceChangeEvent( + surfaceId: Int, + viewTag: Int, + private val appearance: String, +) : Event(surfaceId, viewTag) { + override fun getEventName(): String = EVENT_NAME + + override fun getEventData(): WritableMap = Arguments.createMap().apply { + putString("appearance", appearance) + } + + companion object { + const val EVENT_NAME = "topAppearanceChange" + } +} + +internal class BlockLoadEvent(surfaceId: Int, viewTag: Int) : Event(surfaceId, viewTag) { + override fun getEventName(): String = EVENT_NAME + + override fun getEventData(): WritableMap = Arguments.createMap() + + companion object { + const val EVENT_NAME = "topBlockLoad" + } +} + +internal class BlockFailEvent(surfaceId: Int, viewTag: Int) : Event(surfaceId, viewTag) { + override fun getEventName(): String = EVENT_NAME + + override fun getEventData(): WritableMap = Arguments.createMap() + + companion object { + const val EVENT_NAME = "topBlockFail" + } +} diff --git a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt new file mode 100644 index 0000000..e0a5d0b --- /dev/null +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt @@ -0,0 +1,217 @@ +package com.mindboxsdk.embedded + +import android.content.Context +import android.graphics.Color +import android.view.View +import android.widget.FrameLayout +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.setViewTreeLifecycleOwner +import cloud.mindbox.mobile_sdk.Mindbox +import cloud.mindbox.mobile_sdk.annotations.InternalMindboxApi +import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockAppearance +import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockListener +import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockView +import cloud.mindbox.mobile_sdk.logger.Level + +@OptIn(InternalMindboxApi::class) +internal class MindboxEmbeddedBlockHostView(context: Context) : FrameLayout(context) { + var onAppearance: ((String) -> Unit)? = null + + var onOutcome: ((String) -> Unit)? = null + + private var blockView: MindboxEmbeddedBlockView? = null + private var placeSystemName: String? = null + private var timeoutMs: Long? = null + private var hostVisible: Boolean = true + private var hasPlaceholder: Boolean = false + private var hasErrorView: Boolean = false + + private var placeholderStandIn: View? = null + private var errorStandIn: View? = null + + private val hostLifecycleOwner = object : LifecycleOwner { + val registry: LifecycleRegistry = LifecycleRegistry(this) + + override val lifecycle: Lifecycle + get() = registry + } + + init { + hostLifecycleOwner.registry.currentState = Lifecycle.State.RESUMED + setViewTreeLifecycleOwner(hostLifecycleOwner) + } + + private val measureAndLayout = Runnable { + isLayoutScheduled = false + forceLayout() + measure( + MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY), + ) + layout(left, top, right, bottom) + } + + private var isLayoutScheduled = false + + private var isBlockWanted = false + + override fun requestLayout() { + super.requestLayout() + + if (isLayoutScheduled || width == 0 || height == 0) { + return + } + + isLayoutScheduled = true + post(measureAndLayout) + } + + fun setPlaceSystemName(name: String?) { + if (name == placeSystemName) { + return + } + + placeSystemName = name + dropBlock() + } + + fun setTimeoutMs(timeoutMs: Double) { + if (blockView == null) { + this.timeoutMs = timeoutMs.takeIf { it != 0.0 }?.toLong() + } + } + + fun setHostVisible(isHostVisible: Boolean) { + if (hostVisible == isHostVisible) { + return + } + + hostVisible = isHostVisible + blockView?.setHostVisible(isHostVisible) + } + + fun setHasPlaceholder(hasPlaceholder: Boolean) { + if (this.hasPlaceholder == hasPlaceholder) { + return + } + + this.hasPlaceholder = hasPlaceholder + syncStandIns() + } + + fun setHasErrorView(hasErrorView: Boolean) { + if (this.hasErrorView == hasErrorView) { + return + } + + this.hasErrorView = hasErrorView + syncStandIns() + } + + fun commitProps() { + isBlockWanted = true + buildBlockIfPossible() + } + + override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { + super.onSizeChanged(width, height, oldWidth, oldHeight) + buildBlockIfPossible() + } + + private fun buildBlockIfPossible() { + val place = placeSystemName ?: return + if (blockView != null || !isBlockWanted || width == 0 || height == 0) { + return + } + + if (place.isEmpty()) { + Mindbox.writeLog( + message = "[EmbeddedBlock] A React Native block was created without a place system name and has nothing to resolve", + logLevel = Level.ERROR, + ) + } + + val block = MindboxEmbeddedBlockView(context, place, timeoutMs) + blockView = block + + syncStandIns() + block.setHostVisible(hostVisible) + block.setListener( + object : MindboxEmbeddedBlockListener { + override fun onLoad(view: MindboxEmbeddedBlockView) { + onOutcome?.invoke(OUTCOME_LOAD) + } + + override fun onFail(view: MindboxEmbeddedBlockView) { + onOutcome?.invoke(OUTCOME_FAIL) + } + }, + ) + block.setAppearanceObserver { appearance -> onAppearance?.invoke(nameOf(appearance)) } + + addView(block, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + } + + fun release() { + dropBlock() + onAppearance = null + onOutcome = null + hostLifecycleOwner.registry.currentState = Lifecycle.State.DESTROYED + } + + private fun dropBlock() { + val block = blockView ?: return + + blockView = null + placeholderStandIn = null + errorStandIn = null + block.setAppearanceObserver(null) + block.setListener(null) + block.release() + removeView(block) + } + + private fun syncStandIns() { + val block = blockView ?: return + + if (hasPlaceholder) { + if (placeholderStandIn == null) { + placeholderStandIn = makeStandIn() + block.setPlaceholderView(placeholderStandIn) + } + } else if (placeholderStandIn != null) { + placeholderStandIn = null + block.setPlaceholderView(null) + } + + if (hasErrorView) { + if (errorStandIn == null) { + errorStandIn = makeStandIn() + block.setErrorView(errorStandIn) + } + } else if (errorStandIn != null) { + errorStandIn = null + block.setErrorView(null) + } + } + + private fun makeStandIn(): View = View(context).apply { + setBackgroundColor(Color.TRANSPARENT) + isClickable = false + isFocusable = false + } + + private companion object { + const val OUTCOME_LOAD = "load" + const val OUTCOME_FAIL = "fail" + + fun nameOf(appearance: MindboxEmbeddedBlockAppearance): String = when (appearance) { + MindboxEmbeddedBlockAppearance.PLACEHOLDER -> "placeholder" + MindboxEmbeddedBlockAppearance.CONTENT -> "content" + MindboxEmbeddedBlockAppearance.ERROR -> "error" + MindboxEmbeddedBlockAppearance.COLLAPSED -> "collapsed" + } + } +} diff --git a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt new file mode 100644 index 0000000..c205157 --- /dev/null +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt @@ -0,0 +1,94 @@ +package com.mindboxsdk.embedded + +import com.facebook.react.bridge.ReactContext +import com.facebook.react.module.annotations.ReactModule +import com.facebook.react.uimanager.SimpleViewManager +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.UIManagerHelper +import com.facebook.react.uimanager.ViewManagerDelegate +import com.facebook.react.uimanager.events.Event +import com.facebook.react.viewmanagers.MindboxEmbeddedBlockViewManagerDelegate +import com.facebook.react.viewmanagers.MindboxEmbeddedBlockViewManagerInterface + +@ReactModule(name = MindboxEmbeddedBlockViewManager.NAME) +internal class MindboxEmbeddedBlockViewManager : + SimpleViewManager(), + MindboxEmbeddedBlockViewManagerInterface { + private val managerDelegate = MindboxEmbeddedBlockViewManagerDelegate(this) + + override fun getDelegate(): ViewManagerDelegate = managerDelegate + + override fun getName(): String = NAME + + override fun createViewInstance(context: ThemedReactContext): MindboxEmbeddedBlockHostView = + MindboxEmbeddedBlockHostView(context) + + override fun addEventEmitters(reactContext: ThemedReactContext, view: MindboxEmbeddedBlockHostView) { + super.addEventEmitters(reactContext, view) + view.onAppearance = { appearance -> + dispatch(view) { surfaceId, tag -> AppearanceChangeEvent(surfaceId, tag, appearance) } + } + view.onOutcome = { outcome -> + dispatch(view) { surfaceId, tag -> + if (outcome == OUTCOME_LOAD) BlockLoadEvent(surfaceId, tag) else BlockFailEvent(surfaceId, tag) + } + } + } + + override fun onAfterUpdateTransaction(view: MindboxEmbeddedBlockHostView) { + super.onAfterUpdateTransaction(view) + view.commitProps() + } + + override fun onDropViewInstance(view: MindboxEmbeddedBlockHostView) { + view.release() + super.onDropViewInstance(view) + } + + override fun prepareToRecycleView( + reactContext: ThemedReactContext, + view: MindboxEmbeddedBlockHostView, + ): MindboxEmbeddedBlockHostView? = null + + override fun setPlaceSystemName(view: MindboxEmbeddedBlockHostView, value: String?) { + view.setPlaceSystemName(value) + } + + override fun setBlockHeight(view: MindboxEmbeddedBlockHostView, value: Double) = Unit + + override fun setTimeoutMs(view: MindboxEmbeddedBlockHostView, value: Double) { + view.setTimeoutMs(value) + } + + override fun setHasPlaceholder(view: MindboxEmbeddedBlockHostView, value: Boolean) { + view.setHasPlaceholder(value) + } + + override fun setHasErrorView(view: MindboxEmbeddedBlockHostView, value: Boolean) { + view.setHasErrorView(value) + } + + override fun setHostVisible(view: MindboxEmbeddedBlockHostView, value: Boolean) { + view.setHostVisible(value) + } + + override fun getExportedCustomDirectEventTypeConstants(): MutableMap = mutableMapOf( + AppearanceChangeEvent.EVENT_NAME to mutableMapOf("registrationName" to "onAppearanceChange"), + BlockLoadEvent.EVENT_NAME to mutableMapOf("registrationName" to "onBlockLoad"), + BlockFailEvent.EVENT_NAME to mutableMapOf("registrationName" to "onBlockFail"), + ) + + private inline fun dispatch( + view: MindboxEmbeddedBlockHostView, + event: (surfaceId: Int, viewTag: Int) -> Event<*>, + ) { + val reactContext = view.context as? ReactContext ?: return + val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, view.id) ?: return + dispatcher.dispatchEvent(event(UIManagerHelper.getSurfaceId(view), view.id)) + } + + internal companion object { + const val NAME = "MindboxEmbeddedBlockView" + const val OUTCOME_LOAD = "load" + } +} diff --git a/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift b/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift new file mode 100644 index 0000000..5161f54 --- /dev/null +++ b/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift @@ -0,0 +1,91 @@ +import UIKit +@_spi(Internal) import Mindbox +import MindboxLogger + +@objc(MindboxEmbeddedBlockHost) +public final class MindboxEmbeddedBlockHost: NSObject { + @objc public var onAppearance: ((NSString) -> Void)? + + @objc public var onOutcome: ((NSString) -> Void)? + + @objc public var view: UIView { blockView } + + private let blockView: MindboxEmbeddedBlockView + private var isTornDown = false + + @objc public init(placeSystemName: String, height: CGFloat, timeoutMs: Double) { + let timeout: TimeInterval? = timeoutMs == 0 ? nil : timeoutMs / 1000 + blockView = MindboxEmbeddedBlockView(placeSystemName: placeSystemName, height: height, timeout: timeout) + super.init() + + if placeSystemName.isEmpty { + Logger.common(message: "[EmbeddedBlock] A React Native block was created without a place system name and has nothing to resolve", + level: .error, + category: .embeddedBlocks) + } + + blockView.delegate = self + blockView.setAppearanceObserver { [weak self] appearance in + self?.onAppearance?(Self.name(of: appearance) as NSString) + } + } + + @objc public func setHostVisible(_ isHostVisible: Bool) { + blockView.setHostVisible(isHostVisible) + } + + @objc public func setStandIns(hasPlaceholder: Bool, hasErrorView: Bool) { + if hasPlaceholder { + if blockView.placeholderView == nil { + blockView.placeholderView = Self.makeStandIn() + } + } else { + blockView.placeholderView = nil + } + + if hasErrorView { + if blockView.errorView == nil { + blockView.errorView = Self.makeStandIn() + } + } else { + blockView.errorView = nil + } + } + + @objc public func tearDown() { + guard !isTornDown else { return } + + isTornDown = true + onAppearance = nil + onOutcome = nil + blockView.setAppearanceObserver(nil) + blockView.delegate = nil + blockView.release() + } + + private static func makeStandIn() -> UIView { + let standIn = UIView() + standIn.backgroundColor = .clear + standIn.isUserInteractionEnabled = false + return standIn + } + + private static func name(of appearance: MindboxEmbeddedBlockAppearance) -> String { + switch appearance { + case .placeholder: return "placeholder" + case .content: return "content" + case .error: return "error" + case .collapsed: return "collapsed" + } + } +} + +extension MindboxEmbeddedBlockHost: MindboxEmbeddedBlockViewDelegate { + public func mindboxEmbeddedBlockViewDidLoad(_ blockView: MindboxEmbeddedBlockView) { + onOutcome?("load") + } + + public func mindboxEmbeddedBlockViewDidFail(_ blockView: MindboxEmbeddedBlockView) { + onOutcome?("fail") + } +} diff --git a/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm b/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm new file mode 100644 index 0000000..4340088 --- /dev/null +++ b/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm @@ -0,0 +1,354 @@ +// The embedded block on iOS, in both renderers. +// +// The block itself lives in `MindboxEmbeddedBlockHost` — plain UIKit, no React in it — and each +// renderer only carries props to it and its two signals back. Fabric does that through a component +// view and a C++ event emitter; the old renderer through a view manager and direct event blocks. +// The order of the calls into the host is kept the same in both, so a block behaves the same way +// whichever renderer the host app runs. + +#if __has_include("MindboxSdk-Swift.h") +#import "MindboxSdk-Swift.h" +#elif __has_include() +#import +#else +#error "MindboxSdk-Swift.h not found. Ensure Swift sources are included in the MindboxSdk pod target." +#endif + +// The outcome words the Swift host reports. A contract with the host, not derived from anything. +static NSString *const MindboxEmbeddedBlockOutcomeLoad = @"load"; + +#ifdef RCT_NEW_ARCH_ENABLED + +#import + +#import +#import +#import +#import + +using namespace facebook::react; + +@interface MindboxEmbeddedBlockViewComponentView : RCTViewComponentView +@end + +@implementation MindboxEmbeddedBlockViewComponentView { + MindboxEmbeddedBlockHost *_host; + + std::string _placeSystemName; + CGFloat _blockHeight; + double _timeoutMs; + BOOL _hasPlaceholder; + BOOL _hasErrorView; + BOOL _isHostVisible; + + NSString *_pendingAppearance; + NSString *_pendingOutcome; +} + ++ (ComponentDescriptorProvider)componentDescriptorProvider +{ + return concreteComponentDescriptorProvider(); +} + ++ (BOOL)shouldBeRecycled +{ + return NO; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + static const auto defaultProps = std::make_shared(); + _props = defaultProps; + _isHostVisible = YES; + } + + return self; +} + +- (void)dealloc +{ + [_host tearDown]; +} + +- (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared &)oldProps +{ + const auto &next = *std::static_pointer_cast(props); + + if (next.placeSystemName != _placeSystemName) { + _placeSystemName = next.placeSystemName; + [self dropHost]; + } + + _blockHeight = next.blockHeight; + _timeoutMs = next.timeoutMs; + _hasPlaceholder = next.hasPlaceholder; + _hasErrorView = next.hasErrorView; + _isHostVisible = next.hostVisible; + + if (_host != nil) { + [_host setStandInsWithHasPlaceholder:_hasPlaceholder hasErrorView:_hasErrorView]; + [_host setHostVisible:_isHostVisible]; + } + + [super updateProps:props oldProps:oldProps]; +} + +- (void)finalizeUpdates:(RNComponentViewUpdateMask)updateMask +{ + [super finalizeUpdates:updateMask]; + + if (_host != nil || CGRectIsEmpty(self.bounds)) { + return; + } + + _host = [[MindboxEmbeddedBlockHost alloc] initWithPlaceSystemName:@(_placeSystemName.c_str()) + height:_blockHeight + timeoutMs:_timeoutMs]; + [_host setStandInsWithHasPlaceholder:_hasPlaceholder hasErrorView:_hasErrorView]; + [_host setHostVisible:_isHostVisible]; + + __weak MindboxEmbeddedBlockViewComponentView *weakSelf = self; + _host.onAppearance = ^(NSString *appearance) { + [weakSelf emitAppearance:appearance]; + }; + _host.onOutcome = ^(NSString *outcome) { + [weakSelf emitOutcome:outcome]; + }; + + self.contentView = _host.view; +} + +- (void)updateEventEmitter:(const EventEmitter::Shared &)eventEmitter +{ + [super updateEventEmitter:eventEmitter]; + + if (_pendingAppearance != nil) { + NSString *appearance = _pendingAppearance; + _pendingAppearance = nil; + [self emitAppearance:appearance]; + } + + if (_pendingOutcome != nil) { + NSString *outcome = _pendingOutcome; + _pendingOutcome = nil; + [self emitOutcome:outcome]; + } +} + +- (void)invalidate +{ + [self dropHost]; + _placeSystemName = ""; +} + +- (void)emitAppearance:(NSString *)appearance +{ + if (!_eventEmitter) { + _pendingAppearance = appearance; + return; + } + + std::static_pointer_cast(_eventEmitter) + ->onAppearanceChange({.appearance = std::string([appearance UTF8String])}); +} + +- (void)emitOutcome:(NSString *)outcome +{ + if (!_eventEmitter) { + _pendingOutcome = outcome; + return; + } + + const auto emitter = std::static_pointer_cast(_eventEmitter); + if ([outcome isEqualToString:MindboxEmbeddedBlockOutcomeLoad]) { + emitter->onBlockLoad({}); + } else { + emitter->onBlockFail({}); + } +} + +- (void)dropHost +{ + if (_host == nil) { + return; + } + + [_host tearDown]; + self.contentView = nil; + _host = nil; + _pendingAppearance = nil; + _pendingOutcome = nil; +} + +@end + +Class MindboxEmbeddedBlockViewCls(void) +{ + return MindboxEmbeddedBlockViewComponentView.class; +} + +#else // RCT_NEW_ARCH_ENABLED + +#import +#import + +/** + * The block's place in the old renderer. + * + * An `RCTView` and not a bare `UIView`: the view manager the block is exported through is an + * `RCTViewManager`, and the standard view props it brings — the border, the shadow, the overflow — + * are written to an `RCTView`. + * + * The host is built once the place has both its props and a size, which is why the attempt is made + * from `didSetProps:` and from `layoutSubviews`: the props of a transaction and the frame of a + * layout pass do not arrive together, and either can be the last of the two. This is what + * `finalizeUpdates:` does for the block under Fabric. + */ +@interface MindboxEmbeddedBlockPaperView : RCTView + +@property (nonatomic, copy) NSString *placeSystemName; +@property (nonatomic, assign) CGFloat blockHeight; +@property (nonatomic, assign) double timeoutMs; +@property (nonatomic, assign) BOOL hasPlaceholder; +@property (nonatomic, assign) BOOL hasErrorView; +@property (nonatomic, assign) BOOL hostVisible; + +@property (nonatomic, copy) RCTDirectEventBlock onAppearanceChange; +@property (nonatomic, copy) RCTDirectEventBlock onBlockLoad; +@property (nonatomic, copy) RCTDirectEventBlock onBlockFail; + +@end + +@implementation MindboxEmbeddedBlockPaperView { + MindboxEmbeddedBlockHost *_host; + NSString *_builtPlaceSystemName; + double _builtTimeoutMs; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + _hostVisible = YES; + } + + return self; +} + +- (void)dealloc +{ + [_host tearDown]; +} + +- (void)didSetProps:(NSArray *)changedProps +{ + [super didSetProps:changedProps]; + + // A different name is a different block, built from scratch in place of the old one — the same + // rule the JS side states and the Fabric path follows. + if (_host != nil && ![_builtPlaceSystemName isEqualToString:(_placeSystemName ?: @"")]) { + [self dropHost]; + } + + if (_host != nil) { + [_host setStandInsWithHasPlaceholder:_hasPlaceholder hasErrorView:_hasErrorView]; + [_host setHostVisible:_hostVisible]; + return; + } + + [self buildHostIfPossible]; +} + +- (void)layoutSubviews +{ + [super layoutSubviews]; + + [self buildHostIfPossible]; + _host.view.frame = self.bounds; +} + +- (void)buildHostIfPossible +{ + if (_host != nil || CGRectIsEmpty(self.bounds)) { + return; + } + + _builtPlaceSystemName = _placeSystemName ?: @""; + // Taken once, when the block is created: the container cannot re-budget a running wait, and the + // JS side warns the host about a new value rather than applying it. + _builtTimeoutMs = _timeoutMs; + + _host = [[MindboxEmbeddedBlockHost alloc] initWithPlaceSystemName:_builtPlaceSystemName + height:_blockHeight + timeoutMs:_builtTimeoutMs]; + [_host setStandInsWithHasPlaceholder:_hasPlaceholder hasErrorView:_hasErrorView]; + [_host setHostVisible:_hostVisible]; + + __weak MindboxEmbeddedBlockPaperView *weakSelf = self; + _host.onAppearance = ^(NSString *appearance) { + MindboxEmbeddedBlockPaperView *strongSelf = weakSelf; + if (strongSelf.onAppearanceChange != nil) { + strongSelf.onAppearanceChange(@{@"appearance" : appearance}); + } + }; + _host.onOutcome = ^(NSString *outcome) { + MindboxEmbeddedBlockPaperView *strongSelf = weakSelf; + if ([outcome isEqualToString:MindboxEmbeddedBlockOutcomeLoad]) { + if (strongSelf.onBlockLoad != nil) { + strongSelf.onBlockLoad(@{}); + } + } else if (strongSelf.onBlockFail != nil) { + strongSelf.onBlockFail(@{}); + } + }; + + UIView *blockView = _host.view; + blockView.frame = self.bounds; + blockView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + [self addSubview:blockView]; +} + +- (void)dropHost +{ + if (_host == nil) { + return; + } + + [_host.view removeFromSuperview]; + [_host tearDown]; + _host = nil; + _builtPlaceSystemName = nil; +} + +@end + +/** + * The exported component. React Native drops the `Manager` suffix when it names the component, so + * this is the `MindboxEmbeddedBlockView` the JS side asks for — the same name Fabric registers. + */ +@interface MindboxEmbeddedBlockViewManager : RCTViewManager +@end + +@implementation MindboxEmbeddedBlockViewManager + +RCT_EXPORT_MODULE() + +- (UIView *)view +{ + return [MindboxEmbeddedBlockPaperView new]; +} + +RCT_EXPORT_VIEW_PROPERTY(placeSystemName, NSString) +RCT_EXPORT_VIEW_PROPERTY(blockHeight, CGFloat) +RCT_EXPORT_VIEW_PROPERTY(timeoutMs, double) +RCT_EXPORT_VIEW_PROPERTY(hasPlaceholder, BOOL) +RCT_EXPORT_VIEW_PROPERTY(hasErrorView, BOOL) +RCT_EXPORT_VIEW_PROPERTY(hostVisible, BOOL) + +RCT_EXPORT_VIEW_PROPERTY(onAppearanceChange, RCTDirectEventBlock) +RCT_EXPORT_VIEW_PROPERTY(onBlockLoad, RCTDirectEventBlock) +RCT_EXPORT_VIEW_PROPERTY(onBlockFail, RCTDirectEventBlock) + +@end + +#endif // RCT_NEW_ARCH_ENABLED diff --git a/package.json b/package.json index d16806b..e8d7420 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "@types/jest": "^26.0.0", "@types/react": "^16.9.19", "@types/react-native": "0.62.13", + "@types/react-test-renderer": "^16.9.0", "eslint": "^8.19.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-prettier": "^3.1.3", @@ -64,13 +65,27 @@ "prettier": "^2.0.5", "react": "16.13.1", "react-native": "0.63.4", + "react-test-renderer": "16.13.1", "react-native-builder-bob": "^0.18.0", "release-it": "^14.2.2", "typescript": "^4.1.3" }, "peerDependencies": { "react": "*", - "react-native": "*" + "react-native": ">=0.71" + }, + "codegenConfig": { + "name": "MindboxSdkSpec", + "type": "all", + "jsSrcsDir": "src", + "android": { + "javaPackageName": "com.mindboxsdk" + }, + "ios": { + "componentProvider": { + "MindboxEmbeddedBlockView": "MindboxEmbeddedBlockViewComponentView" + } + } }, "jest": { "preset": "react-native", diff --git a/src/MindboxEmbeddedBlock.tsx b/src/MindboxEmbeddedBlock.tsx new file mode 100644 index 0000000..a69f955 --- /dev/null +++ b/src/MindboxEmbeddedBlock.tsx @@ -0,0 +1,214 @@ +import React, { useCallback, useEffect, useRef, useState } from 'react' +import { StyleSheet, View } from 'react-native' +import type { StyleProp, ViewStyle } from 'react-native' + +import MindboxEmbeddedBlockNativeView from './MindboxEmbeddedBlockNativeComponent' +import type { NativeProps } from './MindboxEmbeddedBlockNativeComponent' + +/** + * The handler is typed by the prop it is handed to, not by a second spelling of the same event. + * + * Spelling it out again would mean naming `NativeSyntheticEvent` here as well, and the two names + * only agree while both resolve to the same React Native. They do not always: a checkout that sits + * under a folder carrying its own React Native resolves this file's import and the spec's to + * different copies, and `bob build` then refuses to write the definitions over a `currentTarget` + * that is a number on one side and a view on the other. Taking the type from the prop leaves + * nothing to disagree about. + */ +type AppearanceChangeHandler = NonNullable + +type Appearance = 'placeholder' | 'content' | 'error' | 'collapsed' + +const APPEARANCES: Array = ['placeholder', 'content', 'error', 'collapsed'] + +/** + * Why the place ended up without content. + * + * Empty today, and an object rather than nothing on purpose: the SDK does not yet tell a timeout from + * an empty place from a network failure, and when it does the reason lands here without breaking a + * single caller. + */ +export type MindboxEmbeddedBlockFailure = {} + +export type MindboxEmbeddedBlockProps = { + /** + * The name of the place from the admin panel. A different name is a different block, built from + * scratch in place of the old one. + * + * Space around the name is not part of it: the SDK trims the name before resolving by it, on both + * platforms. A name that is empty — or nothing but spaces — is then no name at all, so the place + * resolves to nothing, collapses and reports [onFail]. The component warns about that. + */ + placeSystemName: string + + /** + * The height the block occupies while it loads and while it is shown. A place that ends up without + * content collapses to zero height and hands the space back. + * + * Live: a new value resizes a block already on screen in place — the same content, no reload — + * exactly as the SwiftUI, Compose and Flutter wrappers behave. + * + * It has to be a positive number. A block given no space to occupy is never loaded at all — a page + * laid out in a zero viewport does not lay itself out again once the space arrives — and reports + * neither outcome. The component warns about such a height. + */ + height: number + + /** + * How long the block waits to find out what to show, in milliseconds. Covers the wait for the + * answer — the config and the targeting — not the whole life of the block: a page that has already + * arrived gets its own time to render. When the wait runs out, the block collapses and reports + * [onFail]. + * + * The budget is the user's, not the clock's: it ticks only while the screen with the block is + * actually looked at (see [active]). Omitted means the SDK's own default of 30 seconds; zero and + * negative values mean it too. The value is taken once, when the block is created — the same rule as + * in the SwiftUI, Compose and Flutter wrappers — so a new value on a live block is ignored with a + * warning. Remount the component (give it a new `key`) to change it. + */ + timeoutMs?: number + + /** + * Drawn instead of the SDK shimmer while the block is loading. Fills the whole place, as the native + * placeholder does. + */ + placeholder?: React.ReactNode + + /** + * Drawn instead of collapsing when the block cannot be shown. + * + * Applies only to failures: an empty place — one with nothing behind its place system name — always + * collapses, so a host cannot fill the space of a block that was never meant to be there. + */ + error?: React.ReactNode + + /** The content is shown. */ + onLoad?: () => void + + /** + * The place ended up without content: the load failed or timed out, or there is nothing behind the + * name. An empty place is a normal outcome, not a breakage. + */ + onFail?: (failure: MindboxEmbeddedBlockFailure) => void + + /** + * Whether the screen the block stands on is the one being looked at. `true` by default. + * + * The native container watches its window, and in RN that is not enough: a native stack keeps the + * screens below the top one in the window, so leaving a screen never takes the block out of it. + * Left alone, the block would spend its whole waiting budget behind another screen and collapse + * before the user came back. Pass `useIsFocused()` — or whatever the app's navigation calls it. + */ + active?: boolean + + style?: StyleProp +} + +/** + * An embedded Mindbox block. + * + * The app marks a *place* by its [placeSystemName] and never learns what goes into it — that is the + * config's decision, and it can change without an app release. **The host owns the size**: pass the + * [height] the block should occupy. + * + * ```tsx + * + * ``` + * + * Both outcomes can be customized, the same way as in SwiftUI, Compose and Flutter: [placeholder] + * replaces the stock loading shimmer, and [error] opts into showing a failure instead of collapsing. + * Both stay ordinary RN nodes, drawn above the native view, so they resolve the context, the theme + * and the handlers of the tree the block itself stands in. The wait for an answer is bounded by + * [timeoutMs] — 30 seconds unless the host says otherwise. + * + * The component is a thin layer over the native block: the native view holds the SDK's own container + * — with its waiting budget and its web page — and this component only mirrors the container's + * decisions in the RN layout. + */ +export const MindboxEmbeddedBlock = (props: MindboxEmbeddedBlockProps) => + +const Block = ({ placeSystemName, height, timeoutMs, placeholder, error, onLoad, onFail, active = true, style }: MindboxEmbeddedBlockProps) => { + const [appearance, setAppearance] = useState('placeholder') + + const blockHeight = Number.isFinite(height) ? Math.max(0, height) : 0 + + // The warnings live in effects, not in the render body: React may run a render more than once + // for a single commit (StrictMode, a suspended tree), and a ref flipped during render would not + // keep the word from being said twice. An effect runs once per commit. + // + // Only the empty name is worth a word. Space around a real name is not a mistake to report: the + // SDK trims the name before it resolves by it, so a padded name finds its place either way. + useEffect(() => { + if (placeSystemName.trim().length === 0) { + console.warn('[MindboxEmbeddedBlock] A block was created without a place system name: there is nothing to resolve by it, so the place collapses and reports onFail.') + } + if (blockHeight <= 0) { + console.warn(`[MindboxEmbeddedBlock] The block "${placeSystemName}" was created with height ${height}: it reserves no space, so nothing loads and no outcome is reported.`) + } + // Creation only: the name remounts the component through its key, and the height is live. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + const creationTimeoutMs = useRef(timeoutMs).current + const hasWarnedAboutTimeout = useRef(false) + useEffect(() => { + if (timeoutMs === creationTimeoutMs || hasWarnedAboutTimeout.current) { + return + } + hasWarnedAboutTimeout.current = true + console.warn(`[MindboxEmbeddedBlock] The block "${placeSystemName}" keeps the timeout it was created with; the new value is ignored. Remount the component — give it a new key — to change the timeout.`) + }, [timeoutMs, creationTimeoutMs, placeSystemName]) + + const deliveredOutcome = useRef<'load' | 'fail' | null>(null) + + const handleAppearanceChange = useCallback((event) => { + const reported = event.nativeEvent.appearance + if (APPEARANCES.includes(reported)) { + setAppearance(reported as Appearance) + } + }, []) + + const handleLoad = useCallback(() => { + if (deliveredOutcome.current === 'load') { + return + } + deliveredOutcome.current = 'load' + onLoad?.() + }, [onLoad]) + + const handleFail = useCallback(() => { + if (deliveredOutcome.current === 'fail') { + return + } + deliveredOutcome.current = 'fail' + onFail?.({}) + }, [onFail]) + + const overlay = appearance === 'placeholder' ? placeholder : appearance === 'error' ? error : null + + return ( + + + {overlay != null ? ( + + {overlay} + + ) : null} + + ) +} + +const styles = StyleSheet.create({ + block: { + width: '100%', + overflow: 'hidden', + }, +}) + +export default MindboxEmbeddedBlock diff --git a/src/MindboxEmbeddedBlockNativeComponent.ts b/src/MindboxEmbeddedBlockNativeComponent.ts new file mode 100644 index 0000000..35a1c68 --- /dev/null +++ b/src/MindboxEmbeddedBlockNativeComponent.ts @@ -0,0 +1,29 @@ +import type { ViewProps } from 'react-native' +import type { DirectEventHandler, Double, WithDefault } from 'react-native/Libraries/Types/CodegenTypes' +import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent' + +type AppearanceChangeEvent = Readonly<{ + appearance: string +}> + +export interface NativeProps extends ViewProps { + placeSystemName?: string + + blockHeight?: Double + + timeoutMs?: Double + + hasPlaceholder?: WithDefault + + hasErrorView?: WithDefault + + hostVisible?: WithDefault + + onAppearanceChange?: DirectEventHandler + + onBlockLoad?: DirectEventHandler + + onBlockFail?: DirectEventHandler +} + +export default codegenNativeComponent('MindboxEmbeddedBlockView') diff --git a/src/__tests__/MindboxEmbeddedBlock.test.tsx b/src/__tests__/MindboxEmbeddedBlock.test.tsx new file mode 100644 index 0000000..c89101e --- /dev/null +++ b/src/__tests__/MindboxEmbeddedBlock.test.tsx @@ -0,0 +1,220 @@ +import React from 'react' +import { StyleSheet, Text, View } from 'react-native' +import { act, create } from 'react-test-renderer' +import type { ReactTestRenderer } from 'react-test-renderer' + +import { MindboxEmbeddedBlock } from '../MindboxEmbeddedBlock' + +jest.mock('../MindboxEmbeddedBlockNativeComponent', () => { + const ReactActual = require('react') + const { View: RNView } = require('react-native') + return { + __esModule: true, + default: (props: unknown) => ReactActual.createElement(RNView, { ...(props as object), testID: 'native-block' }), + } +}) + +const render = (element: React.ReactElement): ReactTestRenderer => { + let renderer: ReactTestRenderer + act(() => { + renderer = create(element as any) + }) + return renderer! +} + +const update = (renderer: ReactTestRenderer, element: React.ReactElement) => { + act(() => { + renderer.update(element as any) + }) +} + +const asType = (component: unknown) => component as any + +const nativeProps = (renderer: ReactTestRenderer) => renderer.root.findByProps({ testID: 'native-block' }).props + +const reportAppearance = (renderer: ReactTestRenderer, appearance: string) => { + act(() => { + nativeProps(renderer).onAppearanceChange({ nativeEvent: { appearance } }) + }) +} + +const frameHeight = (renderer: ReactTestRenderer) => { + const frame = renderer.root.findAllByType(asType(View))[0] + return StyleSheet.flatten(frame.props.style).height +} + +describe('MindboxEmbeddedBlock', () => { + it('takes its height while loading and hands it back when the block collapses', () => { + const renderer = render() + + expect(frameHeight(renderer)).toBe(104) + + reportAppearance(renderer, 'collapsed') + + expect(frameHeight(renderer)).toBe(0) + }) + + it('resizes a live block in place when the height changes', () => { + const renderer = render() + + update(renderer, ) + + expect(frameHeight(renderer)).toBe(80) + expect(nativeProps(renderer).blockHeight).toBe(80) + }) + + it('says nothing about space around a name the SDK trims anyway', () => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) + const renderer = render() + + update(renderer, ) + + expect(warn).not.toHaveBeenCalled() + expect(nativeProps(renderer).placeSystemName).toBe(' stories ') + warn.mockRestore() + }) + + it('warns once about a place system name that is not there at all', () => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) + const renderer = render() + + update(renderer, ) + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('without a place system name') + expect(nativeProps(renderer).placeSystemName).toBe('') + warn.mockRestore() + }) + + it('calls a name of nothing but spaces a missing name, not a padded one', () => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) + render() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('without a place system name') + warn.mockRestore() + }) + + it('hands the failure of a nameless place to the host and gives the space back', () => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) + const onFail = jest.fn() + const renderer = render() + + reportAppearance(renderer, 'collapsed') + act(() => { + nativeProps(renderer).onBlockFail() + }) + + expect(onFail).toHaveBeenCalledTimes(1) + expect(frameHeight(renderer)).toBe(0) + warn.mockRestore() + }) + + it.each([ + ['zero', 0], + ['negative', -104], + ['not a number', Number.NaN], + ])('warns about a %s height that reserves no space and hands the layout zero', (_name, height) => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) + const renderer = render() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('reserves no space') + expect(frameHeight(renderer)).toBe(0) + expect(nativeProps(renderer).blockHeight).toBe(0) + warn.mockRestore() + }) + + it('tells the native block the place, the height and whether the place is taken', () => { + const renderer = render(wait} active={false} />) + + expect(nativeProps(renderer)).toMatchObject({ + placeSystemName: 'stories', + blockHeight: 104, + hasPlaceholder: true, + hasErrorView: false, + hostVisible: false, + }) + }) + + it('sends zero for a timeout the host did not set', () => { + const renderer = render() + + expect(nativeProps(renderer).timeoutMs).toBe(0) + }) + + it('sends the timeout it was created with, in milliseconds', () => { + const renderer = render() + + expect(nativeProps(renderer).timeoutMs).toBe(5000) + }) + + it('keeps the timeout it was created with and warns once about a change', () => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) + const renderer = render() + + update(renderer, ) + update(renderer, ) + + expect(nativeProps(renderer).timeoutMs).toBe(5000) + expect(warn).toHaveBeenCalledTimes(1) + warn.mockRestore() + }) + + it('draws the host placeholder over the loading block and the host error over the failed one', () => { + const renderer = render(loading} error={broken} />) + + expect(renderer.root.findByType(asType(Text)).props.children).toBe('loading') + + reportAppearance(renderer, 'content') + + expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) + + reportAppearance(renderer, 'error') + + expect(renderer.root.findByType(asType(Text)).props.children).toBe('broken') + }) + + it('delivers each outcome once and a changed outcome again', () => { + const onLoad = jest.fn() + const onFail = jest.fn() + const renderer = render() + + act(() => { + nativeProps(renderer).onBlockLoad() + nativeProps(renderer).onBlockLoad() + }) + + expect(onLoad).toHaveBeenCalledTimes(1) + + act(() => { + nativeProps(renderer).onBlockFail() + }) + + expect(onFail).toHaveBeenCalledTimes(1) + }) + + it('ignores an appearance it does not know, keeping the last known one', () => { + const renderer = render() + + reportAppearance(renderer, 'collapsed') + reportAppearance(renderer, 'sideways') + + expect(frameHeight(renderer)).toBe(0) + }) + + it('builds a different place as a different block, with nothing remembered', () => { + const onLoad = jest.fn() + const renderer = render() + + act(() => { + nativeProps(renderer).onBlockLoad() + }) + update(renderer, ) + act(() => { + nativeProps(renderer).onBlockLoad() + }) + + expect(onLoad).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/index.tsx b/src/index.tsx index c2c8273..68868bc 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -493,3 +493,7 @@ export default MindboxSdk export { LogLevel } from './LogLevel' export { InAppCallback, CopyPayloadInAppCallback, EmptyInAppCallback, UrlInAppCallback } from './InAppCallback' + +export { MindboxEmbeddedBlock } from './MindboxEmbeddedBlock' + +export type { MindboxEmbeddedBlockProps, MindboxEmbeddedBlockFailure } from './MindboxEmbeddedBlock' diff --git a/src/react-native-children.d.ts b/src/react-native-children.d.ts new file mode 100644 index 0000000..0e177d0 --- /dev/null +++ b/src/react-native-children.d.ts @@ -0,0 +1,26 @@ +/** + * `children` on the React Native views this package draws with. + * + * `@types/react-native@0.62.13` — the version this repo pins — describes `ViewProps` and + * `TextProps` without `children`, so nesting anything inside a `` is an error. It never came + * up before: until the embedded block there was no JSX under `src/` at all. + * + * This is an augmentation, not a redeclaration: the top-level `export {}` is what makes the file a + * module, and without it the `declare module` below would replace React Native's typings instead of + * adding to them. + * + * Delete this file together with the `@types/react-native` dependency, once the pinned React Native + * is one that ships its own TypeScript types. + */ + +export {} + +declare module 'react-native' { + interface ViewProps { + children?: import('react').ReactNode + } + + interface TextProps { + children?: import('react').ReactNode + } +} diff --git a/src/react-native-codegen.d.ts b/src/react-native-codegen.d.ts new file mode 100644 index 0000000..e315266 --- /dev/null +++ b/src/react-native-codegen.d.ts @@ -0,0 +1,53 @@ +/** + * The codegen vocabulary, for the React Native this repo pins. + * + * A native component's spec has to name its prop types in the words the native codegen reads — + * `Double`, `WithDefault`, `DirectEventHandler` — and import them, along with + * `codegenNativeComponent`, from these exact paths. React Native 0.63 ships both files as plain + * JavaScript with no declarations next to them, so TypeScript has nothing to go on and the spec + * would be an implicit `any`. + * + * Declared here rather than worked around: the paths are what the generator expects, and a spec + * written any other way stops producing the Android view manager delegate and the iOS component + * descriptor. What the runtime does with the two modules is unaffected — on the old renderer + * `codegenNativeComponent` falls back to `requireNativeComponent`, on the new one the generated + * view config takes over. + * + * Delete this file once the pinned React Native is 0.71 or later: from there React Native ships + * its own TypeScript types and these declarations become its own. + */ + +declare module 'react-native/Libraries/Types/CodegenTypes' { + import type { NativeSyntheticEvent } from 'react-native' + + export type Double = number + export type Float = number + export type Int32 = number + export type UnsafeMixed = unknown + + /** + * A prop the native side gives a default to. Left out on the JS side, it crosses the boundary as + * that default, which is why the JS type stays optional. + */ + export type WithDefault = Type | undefined + + /** An event the native view sends to this view's own handler. */ + export type DirectEventHandler = (event: NativeSyntheticEvent) => void + + /** An event the native view sends up the tree. */ + export type BubblingEventHandler = (event: NativeSyntheticEvent) => void +} + +declare module 'react-native/Libraries/Utilities/codegenNativeComponent' { + import type { HostComponent } from 'react-native' + + export default function codegenNativeComponent( + componentName: string, + options?: { + interfaceOnly?: boolean + paperComponentName?: string + paperComponentNameDeprecated?: string + excludedPlatform?: 'iOS' | 'android' + } + ): HostComponent +} diff --git a/yarn.lock b/yarn.lock index 1fcaa75..ecd3cae 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1949,6 +1949,13 @@ dependencies: "@types/react" "*" +"@types/react-test-renderer@^16.9.0": + version "16.9.12" + resolved "https://registry.yarnpkg.com/@types/react-test-renderer/-/react-test-renderer-16.9.12.tgz#821724ed252c8b45a1f35eb8ecb9f31acdad2933" + integrity sha512-RJ4jeg32v2h1izOZ3gES/zQhQOwi6BEnZW890pmAuf3yVSfDm0wOR42YiWFiuSJJRyRykNaXEzis74+y3Ac9HQ== + dependencies: + "@types/react" "^16" + "@types/react@*": version "19.2.17" resolved "https://registry.yarnpkg.com/@types/react/-/react-19.2.17.tgz#dccac365baa0f1734ec270ff4b51c89465e8dc7f" @@ -1956,7 +1963,7 @@ dependencies: csstype "^3.2.2" -"@types/react@^16.9.19": +"@types/react@^16", "@types/react@^16.9.19": version "16.14.70" resolved "https://registry.yarnpkg.com/@types/react/-/react-16.14.70.tgz#c97b717a6263e18e546c54b3b870482d867c6a93" integrity sha512-DM5Q7rSx9G6QYcVvMgxvEurL5P06OxcDNUXrLxlpBzG4ccUewcBCmsztYbxJBobzO8RIwwmjoaD5OsKqdHDuYQ== @@ -8408,7 +8415,7 @@ react-devtools-core@^4.6.0: shell-quote "^1.6.1" ws "^7" -react-is@^16.12.0, react-is@^16.13.1, react-is@^16.8.4: +react-is@^16.12.0, react-is@^16.13.1, react-is@^16.8.4, react-is@^16.8.6: version "16.13.1" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== @@ -8483,6 +8490,16 @@ react-refresh@^0.4.0: resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.4.3.tgz#966f1750c191672e76e16c2efa569150cc73ab53" integrity sha512-Hwln1VNuGl/6bVwnd0Xdn1e84gT/8T9aYNL+HAKDArLCS7LWjwr7StE30IEYbIkx0Vi3vs+coQxe+SQDbGbbpA== +react-test-renderer@16.13.1: + version "16.13.1" + resolved "https://registry.yarnpkg.com/react-test-renderer/-/react-test-renderer-16.13.1.tgz#de25ea358d9012606de51e012d9742e7f0deabc1" + integrity sha512-Sn2VRyOK2YJJldOqoh8Tn/lWQ+ZiKhyZTPtaO0Q6yNj+QDbmRkVFap6pZPy3YQk8DScRDfyqm/KxKYP9gCMRiQ== + dependencies: + object-assign "^4.1.1" + prop-types "^15.6.2" + react-is "^16.8.6" + scheduler "^0.19.1" + react@16.13.1: version "16.13.1" resolved "https://registry.yarnpkg.com/react/-/react-16.13.1.tgz#2e818822f1a9743122c063d6410d85c1e3afe48e" @@ -8955,7 +8972,7 @@ saxes@^5.0.1: dependencies: xmlchars "^2.2.0" -scheduler@0.19.1: +scheduler@0.19.1, scheduler@^0.19.1: version "0.19.1" resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.19.1.tgz#4f3e2ed2c1a7d65681f4c854fa8c5a1ccb40f196" integrity sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA== From 7829bf034a29179b59ae7e9c8c3e2079eccc40ae Mon Sep 17 00:00:00 2001 From: Akylbek Utekeshev Date: Wed, 9 Sep 2026 20:03:43 +0500 Subject: [PATCH 02/16] MOBILE-0000: Bump mindbox-common together with mobile-sdk on release prep (#222) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wrapper takes mindbox-common compileOnly because mobile-sdk keeps it an implementation dependency, so the release tooling has to move both lines at once — otherwise the compile classpath keeps the old common while the runtime one comes transitively from the new mobile-sdk. Co-authored-by: Vailence --- .github/workflows/manual-prepare_release_branch.yml | 3 +++ git-release-branch.sh | 1 + 2 files changed, 4 insertions(+) diff --git a/.github/workflows/manual-prepare_release_branch.yml b/.github/workflows/manual-prepare_release_branch.yml index ee69f99..02d79e0 100644 --- a/.github/workflows/manual-prepare_release_branch.yml +++ b/.github/workflows/manual-prepare_release_branch.yml @@ -131,9 +131,12 @@ jobs: ############################################################################## # 2) Android build.gradle: bump cloud.mindbox:mobile-sdk: + # mindbox-common goes with it: it is an implementation dependency of mobile-sdk, so the + # wrapper takes it compileOnly and both must stay on the same version. ############################################################################## echo "→ Bumping Android SDK in android/build.gradle" sed -i "s|\(api 'cloud.mindbox:mobile-sdk:\).*|\1$AND_VER'|" android/build.gradle + sed -i "s|\(compileOnly 'cloud.mindbox:mindbox-common:\).*|\1$AND_VER'|" android/build.gradle git add android/build.gradle ############################################################################## diff --git a/git-release-branch.sh b/git-release-branch.sh index a97b347..f1fc43d 100755 --- a/git-release-branch.sh +++ b/git-release-branch.sh @@ -44,6 +44,7 @@ if ! [[ $android_sdk_version =~ ^[0-9]+\.[0-9]+\.[0-9]+(-rc)?$ ]]; then fi sed -i '' "s/ api 'cloud.mindbox:mobile-sdk:.*/ api 'cloud.mindbox:mobile-sdk:${android_sdk_version}'/" "$android_gradle" +sed -i '' "s/ compileOnly 'cloud.mindbox:mindbox-common:.*/ compileOnly 'cloud.mindbox:mindbox-common:${android_sdk_version}'/" "$android_gradle" echo "Bump $android_gradle to $android_sdk_version" read -r -p "iOS SDK version: " ios_sdk_version From 16bb89b3775736cab6ba86fe48d463794dee8d12 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 11 Sep 2026 11:15:36 +0000 Subject: [PATCH 03/16] Bump RN SDK versions: core=2.16.0-rc, android=2.16.0-rc, ios=2.16.0-rc --- CHANGELOG.md | 7 +++++++ MindboxSdk.podspec | 4 ++-- android/build.gradle | 4 ++-- package.json | 2 +- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62748b8..22d1b36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [Unreleased] + +### Changes +- Upgrade Android SDK dependency to v2.16.0-rc +- Upgrade iOS SDK dependency to v2.16.0-rc + + ## [2.15.3] - 2026-08-26 ### Changes diff --git a/MindboxSdk.podspec b/MindboxSdk.podspec index 206aeaa..0da7d1b 100644 --- a/MindboxSdk.podspec +++ b/MindboxSdk.podspec @@ -15,8 +15,8 @@ Pod::Spec.new do |s| s.source_files = "ios/**/*.{h,m,mm,swift}" - s.dependency "Mindbox", "2.15.3" - s.dependency "MindboxNotifications", "2.15.3" + s.dependency "Mindbox", "2.16.0-rc" + s.dependency "MindboxNotifications", "2.16.0-rc" # The embedded block is a native component, and on the new renderer that means a Fabric component: # this brings in the renderer's own pods and, the part that decides everything, defines diff --git a/android/build.gradle b/android/build.gradle index c687848..3c3b60e 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -127,7 +127,7 @@ dependencies { // noinspection GradleDynamicVersion api 'com.facebook.react:react-native:+' implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - api 'cloud.mindbox:mobile-sdk:2.15.4' + api 'cloud.mindbox:mobile-sdk:2.16.0-rc' implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.7" - compileOnly 'cloud.mindbox:mindbox-common:2.15.4' + compileOnly 'cloud.mindbox:mindbox-common:2.16.0-rc' } diff --git a/package.json b/package.json index e8d7420..c410157 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "mindbox-sdk", "version": "2.15.3", - "target-version": "2.15.3", + "target-version": "2.16.0-rc", "description": "SDK for integration React Native mobile apps with Mindbox", "main": "lib/commonjs/index", "module": "lib/module/index", From e5e5328aa37e109aa0f2af95bc9aa526a5ed7e38 Mon Sep 17 00:00:00 2001 From: AndreyEmtsov Date: Fri, 11 Sep 2026 11:46:07 +0000 Subject: [PATCH 04/16] chore: release 2.16.0-rc --- CHANGELOG.md | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22d1b36..6171e58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## [Unreleased] +## [2.16.0-rc] - 2026-09-11 ### Changes - Upgrade Android SDK dependency to v2.16.0-rc diff --git a/package.json b/package.json index c410157..3797986 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mindbox-sdk", - "version": "2.15.3", + "version": "2.16.0-rc", "target-version": "2.16.0-rc", "description": "SDK for integration React Native mobile apps with Mindbox", "main": "lib/commonjs/index", From f86685a2d546cdab3a408bb3b7cc01514469073d Mon Sep 17 00:00:00 2001 From: Akylbek Utekeshev Date: Tue, 6 Oct 2026 16:52:11 +0500 Subject: [PATCH 05/16] =?UTF-8?q?MOBILE-557:=20=D0=A2=D1=80=D0=B8=20=D0=B8?= =?UTF-8?q?=D1=81=D1=85=D0=BE=D0=B4=D0=B0,=20=D1=81=D1=82=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=B5=D0=B3=D0=B8=D1=8F=20=D0=B7=D0=B0=D0=B3=D1=80=D1=83?= =?UTF-8?q?=D0=B7=D0=BA=D0=B8=20=D0=B8=20=D0=B0=D0=BD=D0=B8=D0=BC=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D0=BF=D0=BE=D1=8F=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B2=D1=81=D1=82=D1=80=D0=BE=D0=B5=D0=BD=D0=BD?= =?UTF-8?q?=D0=BE=D0=B3=D0=BE=20=D0=B1=D0=BB=D0=BE=D0=BA=D0=B0=20(#224)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * MOBILE-557: Split the embedded block outcome into onLoad, onEmpty and onFail(reason) The native blocks report three outcomes since MOBILE-504 (iOS) and MOBILE-505 (Android): the content is shown, the place has nothing to show, or the block could not be shown, with a reason. The component now reports the same three. `onEmpty` is new and carries no reason. `onFail` takes a `MindboxEmbeddedBlockFailReason` — a string with the `networkError` and `internalError` constants, the same raw values as on the native side, open to words a later SDK adds. The two outcome events of the native component are folded into one, `onBlockOutcome`, carrying the outcome word and the reason; both native halves implement the new listener and delegate methods: the Android one no longer compiles against the old `onFail(view)`, the iOS one would otherwise keep compiling against a protocol whose default implementation silently swallows the failure. Outcomes are still deduplicated by kind: a failure that repeats with another reason is the same outcome. A platform without a native block collapses and reports `internalError`, which the component did not do before. The empty `MindboxEmbeddedBlockFailure` placeholder type goes: the reason is what it was reserved for. * MOBILE-557: Let the block start hidden, with a placeholder, or by the place's memory, and reveal with the SDK's animation The native blocks take a loading strategy since MOBILE-516 (iOS) and MOBILE-517 (Android): `automatic` — the default — keeps the block hidden until the place has shown content once on this device and puts a placeholder there from then on, `placeholder` takes the space up front, `hidden` never takes it before the content. Content is revealed with the SDK's own animation unless `animatesReveal` is off. The component takes both, fixed at creation like `timeoutMs`, and hands them to the native block. Three things the JS side has to do itself: The first look. Both natives decide it synchronously, before the container exists, through a static `initialAppearance`; JS cannot reach anything synchronously. `placeholder` and `hidden` are decided from the strategy alone. `automatic` asks the `MindboxSdk` native module — the one module the package already has, on both renderers — through a new `embeddedBlockInitialAppearance` method that the JS side does not export, and takes no space until it answers: a place that never showed content must not flash reserved space, and one that has gets its placeholder a frame late rather than a frame early. The native block's own report, once the native view exists, outranks a later answer. The slot. A block that waits hidden used to be impossible: both native halves build the SDK container only once their view has a frame, and the native view sat in a slot of zero. The layout now gives the slot — 0 for a collapsed block — and the block inside keeps its full height under the slot's clip, so it runs its whole cycle unseen, as the native blocks do. The growth. The container fades the content in on its own; the growth of a block that waited hidden is the wrapper's, as in SwiftUI, Compose and Flutter. The native block says whether the change is the animated reveal — it owns the gates: animatesReveal, Reduce Motion, "only the arrival of content" — and how long it takes (`animated` and `revealDurationMs` on the appearance event; Android's isRevealAnimated and REVEAL_ANIMATION_DURATION_MS, the same two added to iOS as @_spi in ios-sdk feature/MOBILE-556). The slot then grows from 0 to the height over that duration, an Animated value on the JS side; every other change lands at once. * MOBILE-557: Say that whitespace around a place name is the native block's to ignore iOS strips the whitespace since MOBILE-419, and Android's PlaceKey trims it too, so a name pasted with a stray space finds its place on both. The component never trimmed or warned about it — the test that the name reaches the native block as given stands — and its doc now says so the way the Flutter widget does, rather than describing what the SDK does with it. * MOBILE-557: Let the native block alone tell an automatic block its first look An `automatic` block asked the `MindboxSdk` module what it starts with — the place's memory, read through the native `initialAppearance` — because the native view was believed to stay unbuilt while the slot is collapsed. It does not: the view inside the slot keeps the block's full height, both native halves build the block as soon as they have a frame, and the block reports its look the moment it is observed. That report reaches JS in the same mount, no later than the module's promise could, with the same word read from the same memory; `hasHeardFromNative` existed only to throw the module's answer away. The channel goes — the TS module, the `@ReactMethod` and the `@objc` method with its `RCT_EXTERN_METHOD`, the SPI import the Swift module needed for it — and the first-look tests drive the native report instead of a mocked promise. * MOBILE-557: Hand the host its callbacks at creation so the block's first look is not lost `MindboxEmbeddedBlockHost` subscribed to the block inside `init`, and the SDK answers a subscription at once with the current look — for an `automatic` block, the place's memory. `onAppearance` was assigned by the component view only after `init` returned, so that first report went to nobody. JS learned the look only through the `.loading` the provider re-emits when the block enters a window and starts, and a block mounted with `active={false}` did not start: its remembered placeholder waited for the screen to become active, while Android, whose emitters are wired before the block exists, showed it at once. Both callbacks are now parameters of the host's initializer and non-optional `let`s, with `isTornDown` as the one guard after teardown; the observer is set last in `init`. Both renderers pass their blocks in: under Fabric the event emitter is set before `finalizeUpdates:`, under Paper the event blocks are props set before `didSetProps:` and any layout pass. With the emitter always in place when the host is built, the pending-event buffers of the Fabric view had no path left; they are gone, and the emit methods keep a plain early return that states the invariant. * MOBILE-557: Keep every appearance and outcome event of an Android block out of coalescing React Native's `Event` coalesces by default: same-named events of one view that are still queued when a frame is dispatched are folded into the last one, on Paper in `EventDispatcherImpl` and under Fabric through the `canCoalesce` flag handed to the emitter. The JS side reads every change — a reveal is content arriving where a placeholder or nothing stood, and every changed outcome is promised to the host — so a report folded into the next one would be a report lost. iOS never coalesced these: direct events and the generated Fabric emitter dispatch each one. * MOBILE-557: Fade a host overlay out above the content it is replaced by, on the native curve The native block fades its content in from transparent, and the stand-in the host's placeholder or error screen is drawn over is clear. The overlay went away in the frame the look changed, so for the length of the fade the screen's background showed through where the placeholder had been. SwiftUI writes the look inside `withAnimation` and Compose fades its stand-in under the content; here the overlay lies above the native view, so it stays and fades out over the same duration, touches passing through to the content meanwhile. Any other change takes it away at once, a fade interrupted included. The slot's growth and this fade now follow the native curve per platform: Material's standard curve on Android, ease-in-out on iOS. Tests cover the fade, its interruption, the opaque placeholder of a reload after it, and the cell the old reveal test missed — a placeholder or an error screen arriving mid-growth takes the full height at once and stops the growth. A nameless place is also told right: both native blocks report it empty, so the docs, the warning and the test say `onEmpty`, not `onFail`. * MOBILE-557: Say that a block waiting hidden draws no placeholder or error, and where the layout moves The docs promised an `error` screen and a layout that does not jump; neither is true for a block that waits hidden, which under the default strategy is every place on a fresh install. Such a block draws neither `placeholder` nor `error` until its content has been shown once — a failure keeps it collapsed and only `onFail` tells — and an `automatic` block at a remembered place takes its space a frame after the mount, not from the first one. `onLoad` of a block that waited hidden comes while it is still growing from zero. The targeting data a `networkError` may stand for is fetched that way on iOS only. * MOBILE-557: Name what breaks for a host on 2.16.0-rc, under the header the release workflow expects `mindbox-sdk@2.16.0-rc` is on npm under the `rc` tag with `onFail(failure)`, the `MindboxEmbeddedBlockFailure` type, a placeholder from the first frame and a README that hid the stories section in `onFail`. After this release an empty place goes to `onEmpty`, so that section stays, and the compiler says nothing about it. The release workflow inserts `## [Unreleased]` with brackets; the header without them would have left two sections. * MOBILE-557: Log an unknown loading strategy on Android once the place name is known Fabric sets props in no fixed order: a strategy word arriving before the name was logged against place 'null'. The word is kept and logged when the block is built, next to the empty-name log, as the iOS host does. --------- Co-authored-by: Vailence --- CHANGELOG.md | 10 + README.md | 53 ++- .../mindboxsdk/embedded/EmbeddedBlockWire.kt | 31 ++ .../embedded/MindboxEmbeddedBlockEvents.kt | 41 +- .../embedded/MindboxEmbeddedBlockHostView.kt | 81 +++- .../MindboxEmbeddedBlockViewManager.kt | 22 +- ios/EmbeddedBlock/EmbeddedBlockWire.swift | 33 ++ .../MindboxEmbeddedBlockHost.swift | 76 ++- ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm | 143 +++--- src/MindboxEmbeddedBlock.tsx | 336 ++++++++++--- src/MindboxEmbeddedBlockFailReason.ts | 30 ++ src/MindboxEmbeddedBlockLoadingStrategy.ts | 43 ++ src/MindboxEmbeddedBlockNativeComponent.ts | 28 +- src/__tests__/MindboxEmbeddedBlock.test.tsx | 448 ++++++++++++++++-- .../MindboxEmbeddedBlock.unsupported.test.tsx | 54 +++ src/index.tsx | 6 +- 16 files changed, 1191 insertions(+), 244 deletions(-) create mode 100644 android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt create mode 100644 ios/EmbeddedBlock/EmbeddedBlockWire.swift create mode 100644 src/MindboxEmbeddedBlockFailReason.ts create mode 100644 src/MindboxEmbeddedBlockLoadingStrategy.ts create mode 100644 src/__tests__/MindboxEmbeddedBlock.unsupported.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 6171e58..1d1537b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## [Unreleased] + +### Changes +- **Breaking since `2.16.0-rc`:** `onFail` of `MindboxEmbeddedBlock` reports failures only; a place with nothing to show arrives in the new `onEmpty`. A host that hid its section in `onFail` — as the previous README showed — moves that to `onEmpty`. +- **Breaking since `2.16.0-rc`:** the `MindboxEmbeddedBlockFailure` type is removed; `onFail` receives a `MindboxEmbeddedBlockFailReason` string instead of an empty object. +- **Breaking since `2.16.0-rc`:** `MindboxEmbeddedBlock` starts by `loadingStrategy="automatic"` — hidden until the place has shown content once on this device — instead of always showing a placeholder; `loadingStrategy="placeholder"` restores the previous look. +- Add `MindboxEmbeddedBlock` — an embedded block for a place from the admin panel, a native component for both the old and the new architecture. +- `MindboxEmbeddedBlock` reports three outcomes, as the native SwiftUI and Compose blocks do: `onLoad`, `onEmpty` and `onFail` with a `MindboxEmbeddedBlockFailReason` (`networkError` or `internalError`). +- `MindboxEmbeddedBlock` takes a `loadingStrategy` — `automatic` (the default: hidden until the place has shown content once on this device, a placeholder from then on), `placeholder` or `hidden` — and `animatesReveal`, as the native SwiftUI and Compose blocks do. A block that waited hidden grows to its height with the SDK's reveal when its content arrives. + ## [2.16.0-rc] - 2026-09-11 ### Changes diff --git a/README.md b/README.md index 4f101aa..a785507 100644 --- a/README.md +++ b/README.md @@ -47,10 +47,19 @@ import { MindboxEmbeddedBlock } from 'mindbox-sdk'; ``` -Both outcomes can be customized, the same way as in SwiftUI, Compose and Flutter: `placeholder` +The outcome arrives through three callbacks, the same three as in SwiftUI, Compose and Flutter: +`onLoad` when the content is shown, `onEmpty` when there is nothing to show at the place, and +`onFail` with a `MindboxEmbeddedBlockFailReason` when the block could not be shown. An empty place +is a normal outcome, not a breakage, and comes with no reason; a block whose place system name is +empty is such a place too. A failure's reason — `networkError` +or `internalError` — is for logs and analytics, not for branching: by the time it arrives the block +has already collapsed or switched to `error`. A later SDK may add reasons, so keep a fallback when +matching. + +Both looks can be customized, the same way as in SwiftUI, Compose and Flutter: `placeholder` replaces the stock loading shimmer, and `error` opts into showing a failure instead of collapsing. An empty place always collapses — a host cannot fill the space of a block that was never meant to -be there. `onLoad` and `onFail` report how the load ended. +be there. ```tsx } error={} - onFail={() => setShowStoriesSection(false)} + onEmpty={() => setShowStoriesSection(false)} + onFail={(reason) => console.log(`stories failed: ${reason}`)} /> ``` @@ -78,10 +88,43 @@ a screen nobody is looking at. /> ``` +What the block shows until the SDK has decided what goes into it is `loadingStrategy`, the same +three choices as in SwiftUI, Compose and Flutter. `automatic` — the default — keeps the block hidden +until the place has shown content once on this device and puts a placeholder there from then on: +nothing flashes where no content is expected, and where it is expected the space is taken as soon +as the native side has read the place's memory — a frame after the block is mounted, so what stands +below moves down by the block's height once. `placeholder` takes the space from the first frame, +worth naming for a place that always has a campaign behind it. `hidden` never takes it until the +content is shown. + +A block that waits hidden — `hidden`, and `automatic` at a place that has not shown content yet — +draws neither `placeholder` nor `error` until its content has been shown once: a failure keeps it +collapsed, and only `onFail` tells. With the default strategy that is every place on a fresh +install, so a host that counts on its `error` screen names `loadingStrategy="placeholder"`. + +The content is revealed with the SDK's own animation — it fades in, and a block that started hidden +grows to its height — unless `animatesReveal` is off; the system's reduced-motion setting turns it +off as well. Turn it off to animate the block's container yourself in `onLoad` — keeping in mind +that a block that waited hidden is only starting to grow from zero at that moment. A host +`placeholder` the content replaces fades out above it over the same reveal. + +```tsx + +``` + `height` is live: a new value resizes a block already on screen in place — the same content, no reload. It has to be positive, though: a block given no space to occupy is never loaded and reports -no outcome. `timeoutMs` is fixed when the block is created — a new value is ignored with a warning; -give the component a new `key` to load a block on a new budget. +no outcome. `timeoutMs`, `loadingStrategy` and `animatesReveal` are fixed when the block is created +— a new value is ignored with a warning; give the component a new `key` to build a block anew. + +Available on iOS and Android. On any other platform the block collapses right away and reports +`onFail` with `internalError`, so a layout that hides its section on failure behaves the same +everywhere. ### Push Notifications diff --git a/android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt b/android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt new file mode 100644 index 0000000..954941b --- /dev/null +++ b/android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt @@ -0,0 +1,31 @@ +package com.mindboxsdk.embedded + +import cloud.mindbox.mobile_sdk.annotations.InternalMindboxApi +import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockAppearance +import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockLoadingStrategy + +/** + * The words the block speaks to JS in: the same ones on iOS, the same ones the Flutter plugin + * uses. A contract with the JS side, not derived from anything. + */ +@OptIn(InternalMindboxApi::class) +internal object EmbeddedBlockWire { + const val OUTCOME_LOAD = "load" + const val OUTCOME_EMPTY = "empty" + const val OUTCOME_FAIL = "fail" + + /** `null` for a word this SDK does not know; an empty word is the default, `automatic`. */ + fun loadingStrategyOf(word: String?): MindboxEmbeddedBlockLoadingStrategy? = when (word) { + null, "", "automatic" -> MindboxEmbeddedBlockLoadingStrategy.AUTOMATIC + "placeholder" -> MindboxEmbeddedBlockLoadingStrategy.PLACEHOLDER + "hidden" -> MindboxEmbeddedBlockLoadingStrategy.HIDDEN + else -> null + } + + fun nameOf(appearance: MindboxEmbeddedBlockAppearance): String = when (appearance) { + MindboxEmbeddedBlockAppearance.PLACEHOLDER -> "placeholder" + MindboxEmbeddedBlockAppearance.CONTENT -> "content" + MindboxEmbeddedBlockAppearance.ERROR -> "error" + MindboxEmbeddedBlockAppearance.COLLAPSED -> "collapsed" + } +} diff --git a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt index a4a04e0..53f41bd 100644 --- a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt @@ -4,15 +4,29 @@ import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap import com.facebook.react.uimanager.events.Event +/** + * The look the native block shows. `animated` is `true` for the one change that is the SDK's + * reveal of content — the block owns that decision, gates included — and `revealDurationMs` is + * how long it takes; `false` and `0` for every other change. + */ internal class AppearanceChangeEvent( surfaceId: Int, viewTag: Int, private val appearance: String, + private val isRevealAnimated: Boolean, + private val revealDurationMs: Int, ) : Event(surfaceId, viewTag) { override fun getEventName(): String = EVENT_NAME + // React Native coalesces same-named events of one view that are still queued when a frame is + // dispatched, keeping the last. The JS side reads every change — a reveal is content arriving + // where a placeholder or nothing stood — so none may be folded into the next. + override fun canCoalesce(): Boolean = false + override fun getEventData(): WritableMap = Arguments.createMap().apply { putString("appearance", appearance) + putBoolean("animated", isRevealAnimated) + putInt("revealDurationMs", if (isRevealAnimated) revealDurationMs else 0) } companion object { @@ -20,22 +34,27 @@ internal class AppearanceChangeEvent( } } -internal class BlockLoadEvent(surfaceId: Int, viewTag: Int) : Event(surfaceId, viewTag) { +/** + * How the load ended: `load`, `empty` or `fail`, the reason going with a failure. An event payload + * has every field, so a missing reason is spelled as an empty string. + */ +internal class BlockOutcomeEvent( + surfaceId: Int, + viewTag: Int, + private val outcome: String, + private val reason: String?, +) : Event(surfaceId, viewTag) { override fun getEventName(): String = EVENT_NAME - override fun getEventData(): WritableMap = Arguments.createMap() + // Every outcome is promised to the host once it changes; two in one frame must both arrive. + override fun canCoalesce(): Boolean = false - companion object { - const val EVENT_NAME = "topBlockLoad" + override fun getEventData(): WritableMap = Arguments.createMap().apply { + putString("outcome", outcome) + putString("reason", reason.orEmpty()) } -} - -internal class BlockFailEvent(surfaceId: Int, viewTag: Int) : Event(surfaceId, viewTag) { - override fun getEventName(): String = EVENT_NAME - - override fun getEventData(): WritableMap = Arguments.createMap() companion object { - const val EVENT_NAME = "topBlockFail" + const val EVENT_NAME = "topBlockOutcome" } } diff --git a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt index e0a5d0b..48fc5b5 100644 --- a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt @@ -10,20 +10,27 @@ import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.setViewTreeLifecycleOwner import cloud.mindbox.mobile_sdk.Mindbox import cloud.mindbox.mobile_sdk.annotations.InternalMindboxApi -import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockAppearance +import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockFailReason import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockListener +import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockLoadingStrategy import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockView import cloud.mindbox.mobile_sdk.logger.Level @OptIn(InternalMindboxApi::class) internal class MindboxEmbeddedBlockHostView(context: Context) : FrameLayout(context) { - var onAppearance: ((String) -> Unit)? = null + /** The appearance word, whether this change is the SDK's animated reveal, and how long it takes. */ + var onAppearance: ((appearance: String, isRevealAnimated: Boolean, revealDurationMs: Int) -> Unit)? = null - var onOutcome: ((String) -> Unit)? = null + /** The outcome word and, for a failure, the reason's raw value. */ + var onOutcome: ((outcome: String, reason: String?) -> Unit)? = null private var blockView: MindboxEmbeddedBlockView? = null private var placeSystemName: String? = null private var timeoutMs: Long? = null + private var loadingStrategy: MindboxEmbeddedBlockLoadingStrategy = MindboxEmbeddedBlockLoadingStrategy.AUTOMATIC + /** A strategy word this SDK did not know, kept to be logged once the block is built and the place is known. */ + private var unknownLoadingStrategyWord: String? = null + private var animatesReveal: Boolean = true private var hostVisible: Boolean = true private var hasPlaceholder: Boolean = false private var hasErrorView: Boolean = false @@ -83,6 +90,26 @@ internal class MindboxEmbeddedBlockHostView(context: Context) : FrameLayout(cont } } + // Fixed at creation, as the timeout is: the JS side warns the host about a later value rather + // than applying it, and the native block takes both only through its constructor. A word this + // SDK does not know is read as `automatic` and logged when the block is built — Fabric sets the + // props in no fixed order, and here the place name may not have arrived yet. + fun setLoadingStrategy(word: String?) { + if (blockView != null) { + return + } + + val strategy = EmbeddedBlockWire.loadingStrategyOf(word) + unknownLoadingStrategyWord = if (strategy == null) word else null + loadingStrategy = strategy ?: MindboxEmbeddedBlockLoadingStrategy.AUTOMATIC + } + + fun setAnimatesReveal(animatesReveal: Boolean) { + if (blockView == null) { + this.animatesReveal = animatesReveal + } + } + fun setHostVisible(isHostVisible: Boolean) { if (hostVisible == isHostVisible) { return @@ -132,8 +159,20 @@ internal class MindboxEmbeddedBlockHostView(context: Context) : FrameLayout(cont logLevel = Level.ERROR, ) } + unknownLoadingStrategyWord?.let { word -> + Mindbox.writeLog( + message = "[EmbeddedBlock] A React Native block for place '$place' was given a loading strategy this SDK does not know ('$word') and starts as automatic", + logLevel = Level.ERROR, + ) + } - val block = MindboxEmbeddedBlockView(context, place, timeoutMs) + val block = MindboxEmbeddedBlockView( + context = context, + placeSystemName = place, + timeoutMs = timeoutMs, + loadingStrategy = loadingStrategy, + animatesReveal = animatesReveal, + ) blockView = block syncStandIns() @@ -141,15 +180,29 @@ internal class MindboxEmbeddedBlockHostView(context: Context) : FrameLayout(cont block.setListener( object : MindboxEmbeddedBlockListener { override fun onLoad(view: MindboxEmbeddedBlockView) { - onOutcome?.invoke(OUTCOME_LOAD) + onOutcome?.invoke(EmbeddedBlockWire.OUTCOME_LOAD, null) } - override fun onFail(view: MindboxEmbeddedBlockView) { - onOutcome?.invoke(OUTCOME_FAIL) + override fun onEmpty(view: MindboxEmbeddedBlockView) { + onOutcome?.invoke(EmbeddedBlockWire.OUTCOME_EMPTY, null) + } + + override fun onFail(view: MindboxEmbeddedBlockView, reason: MindboxEmbeddedBlockFailReason) { + onOutcome?.invoke(EmbeddedBlockWire.OUTCOME_FAIL, reason.value) } }, ) - block.setAppearanceObserver { appearance -> onAppearance?.invoke(nameOf(appearance)) } + // `isRevealAnimated` is read while the observer runs: the block sets it right before it + // calls, for that one call. The block owns the gates — `animatesReveal`, a window to animate + // in, animations enabled on the device, "only the arrival of content" — and this host only + // passes its word on; the growth of a block that waited hidden is then the JS side's. + block.setAppearanceObserver { appearance -> + onAppearance?.invoke( + EmbeddedBlockWire.nameOf(appearance), + block.isRevealAnimated, + MindboxEmbeddedBlockView.REVEAL_ANIMATION_DURATION_MS.toInt(), + ) + } addView(block, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) } @@ -202,16 +255,4 @@ internal class MindboxEmbeddedBlockHostView(context: Context) : FrameLayout(cont isClickable = false isFocusable = false } - - private companion object { - const val OUTCOME_LOAD = "load" - const val OUTCOME_FAIL = "fail" - - fun nameOf(appearance: MindboxEmbeddedBlockAppearance): String = when (appearance) { - MindboxEmbeddedBlockAppearance.PLACEHOLDER -> "placeholder" - MindboxEmbeddedBlockAppearance.CONTENT -> "content" - MindboxEmbeddedBlockAppearance.ERROR -> "error" - MindboxEmbeddedBlockAppearance.COLLAPSED -> "collapsed" - } - } } diff --git a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt index c205157..45db945 100644 --- a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt @@ -25,13 +25,11 @@ internal class MindboxEmbeddedBlockViewManager : override fun addEventEmitters(reactContext: ThemedReactContext, view: MindboxEmbeddedBlockHostView) { super.addEventEmitters(reactContext, view) - view.onAppearance = { appearance -> - dispatch(view) { surfaceId, tag -> AppearanceChangeEvent(surfaceId, tag, appearance) } + view.onAppearance = { appearance, isRevealAnimated, revealDurationMs -> + dispatch(view) { surfaceId, tag -> AppearanceChangeEvent(surfaceId, tag, appearance, isRevealAnimated, revealDurationMs) } } - view.onOutcome = { outcome -> - dispatch(view) { surfaceId, tag -> - if (outcome == OUTCOME_LOAD) BlockLoadEvent(surfaceId, tag) else BlockFailEvent(surfaceId, tag) - } + view.onOutcome = { outcome, reason -> + dispatch(view) { surfaceId, tag -> BlockOutcomeEvent(surfaceId, tag, outcome, reason) } } } @@ -60,6 +58,14 @@ internal class MindboxEmbeddedBlockViewManager : view.setTimeoutMs(value) } + override fun setLoadingStrategy(view: MindboxEmbeddedBlockHostView, value: String?) { + view.setLoadingStrategy(value) + } + + override fun setAnimatesReveal(view: MindboxEmbeddedBlockHostView, value: Boolean) { + view.setAnimatesReveal(value) + } + override fun setHasPlaceholder(view: MindboxEmbeddedBlockHostView, value: Boolean) { view.setHasPlaceholder(value) } @@ -74,8 +80,7 @@ internal class MindboxEmbeddedBlockViewManager : override fun getExportedCustomDirectEventTypeConstants(): MutableMap = mutableMapOf( AppearanceChangeEvent.EVENT_NAME to mutableMapOf("registrationName" to "onAppearanceChange"), - BlockLoadEvent.EVENT_NAME to mutableMapOf("registrationName" to "onBlockLoad"), - BlockFailEvent.EVENT_NAME to mutableMapOf("registrationName" to "onBlockFail"), + BlockOutcomeEvent.EVENT_NAME to mutableMapOf("registrationName" to "onBlockOutcome"), ) private inline fun dispatch( @@ -89,6 +94,5 @@ internal class MindboxEmbeddedBlockViewManager : internal companion object { const val NAME = "MindboxEmbeddedBlockView" - const val OUTCOME_LOAD = "load" } } diff --git a/ios/EmbeddedBlock/EmbeddedBlockWire.swift b/ios/EmbeddedBlock/EmbeddedBlockWire.swift new file mode 100644 index 0000000..6f4fe58 --- /dev/null +++ b/ios/EmbeddedBlock/EmbeddedBlockWire.swift @@ -0,0 +1,33 @@ +@_spi(Internal) import Mindbox + +/// The words the block speaks to JS in: the same ones on Android, the same ones the Flutter plugin +/// uses. A contract with the JS side, not derived from anything. +enum EmbeddedBlockWire { + static let outcomeLoad = "load" + static let outcomeEmpty = "empty" + static let outcomeFail = "fail" + + /// `nil` for a word this SDK does not know; an empty word is the default, `automatic`. + static func loadingStrategy(of word: String?) -> MindboxEmbeddedBlockLoadingStrategy? { + switch word { + case nil, "", "automatic": return .automatic + case "placeholder": return .placeholder + case "hidden": return .hidden + default: return nil + } + } + + static func name(of appearance: MindboxEmbeddedBlockAppearance) -> String { + switch appearance { + case .placeholder: return "placeholder" + case .content: return "content" + case .error: return "error" + case .collapsed: return "collapsed" + } + } + + /// The SDK's reveal, in whole milliseconds — what JS animates the growth of a hidden block over. + static var revealDurationMs: Int { + Int((MindboxEmbeddedBlockView.revealAnimationDuration * 1000).rounded()) + } +} diff --git a/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift b/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift index 5161f54..dc3bd71 100644 --- a/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift +++ b/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift @@ -4,18 +4,43 @@ import MindboxLogger @objc(MindboxEmbeddedBlockHost) public final class MindboxEmbeddedBlockHost: NSObject { - @objc public var onAppearance: ((NSString) -> Void)? + /// The appearance word, whether this change is the SDK's animated reveal, and how long it takes. + /// Given at creation and never replaced: the block reports its first look the moment it is + /// observed, and a callback wired afterwards would miss it. + private let onAppearance: (NSString, Bool, Int) -> Void - @objc public var onOutcome: ((NSString) -> Void)? + /// The outcome word and, for a failure, the reason's raw value. + private let onOutcome: (NSString, NSString?) -> Void @objc public var view: UIView { blockView } private let blockView: MindboxEmbeddedBlockView private var isTornDown = false - @objc public init(placeSystemName: String, height: CGFloat, timeoutMs: Double) { + /// `loadingStrategy` is a word — `automatic`, `placeholder` or `hidden`; a word this SDK does not + /// know is logged and read as `automatic`. Both it and `animatesReveal` are fixed here, as the + /// native block takes them only through its initializer. + /// + /// The callbacks are taken here too, not assigned later: subscribing to the block hands out its + /// current look at once — for an `automatic` block, the place's memory — and that first report + /// is the one JS has no other way to learn. Android wires its emitters before the block exists + /// for the same reason. + @objc public init(placeSystemName: String, + height: CGFloat, + timeoutMs: Double, + loadingStrategy: String, + animatesReveal: Bool, + onAppearance: @escaping (NSString, Bool, Int) -> Void, + onOutcome: @escaping (NSString, NSString?) -> Void) { let timeout: TimeInterval? = timeoutMs == 0 ? nil : timeoutMs / 1000 - blockView = MindboxEmbeddedBlockView(placeSystemName: placeSystemName, height: height, timeout: timeout) + let strategy = EmbeddedBlockWire.loadingStrategy(of: loadingStrategy) + blockView = MindboxEmbeddedBlockView(placeSystemName: placeSystemName, + height: height, + loadingStrategy: strategy ?? .automatic, + timeout: timeout, + animatesReveal: animatesReveal) + self.onAppearance = onAppearance + self.onOutcome = onOutcome super.init() if placeSystemName.isEmpty { @@ -23,10 +48,24 @@ public final class MindboxEmbeddedBlockHost: NSObject { level: .error, category: .embeddedBlocks) } + if strategy == nil { + Logger.common(message: "[EmbeddedBlock] A React Native block for place '\(placeSystemName)' was given a loading strategy this SDK does not know ('\(loadingStrategy)') and starts as automatic", + level: .error, + category: .embeddedBlocks) + } blockView.delegate = self + // `isRevealAnimated` is read while the observer runs: the block sets it right before it + // calls, for that one call. The block owns the gates — `animatesReveal`, a window to animate + // in, Reduce Motion off, "only the arrival of content" — and this host only passes its word + // on; the growth of a block that waited hidden is then the JS side's. + // The observer fires synchronously with the current look, so this comes last in `init`, + // with both callbacks already in place. blockView.setAppearanceObserver { [weak self] appearance in - self?.onAppearance?(Self.name(of: appearance) as NSString) + guard let self, !self.isTornDown else { return } + self.onAppearance(EmbeddedBlockWire.name(of: appearance) as NSString, + self.blockView.isRevealAnimated, + EmbeddedBlockWire.revealDurationMs) } } @@ -56,8 +95,6 @@ public final class MindboxEmbeddedBlockHost: NSObject { guard !isTornDown else { return } isTornDown = true - onAppearance = nil - onOutcome = nil blockView.setAppearanceObserver(nil) blockView.delegate = nil blockView.release() @@ -69,23 +106,24 @@ public final class MindboxEmbeddedBlockHost: NSObject { standIn.isUserInteractionEnabled = false return standIn } - - private static func name(of appearance: MindboxEmbeddedBlockAppearance) -> String { - switch appearance { - case .placeholder: return "placeholder" - case .content: return "content" - case .error: return "error" - case .collapsed: return "collapsed" - } - } } +// All three methods are implemented on purpose: the protocol gives each an empty default, so a +// host that still spelled the old `DidFail(_:)` would compile and silently hear no failure. extension MindboxEmbeddedBlockHost: MindboxEmbeddedBlockViewDelegate { public func mindboxEmbeddedBlockViewDidLoad(_ blockView: MindboxEmbeddedBlockView) { - onOutcome?("load") + guard !isTornDown else { return } + onOutcome(EmbeddedBlockWire.outcomeLoad as NSString, nil) } - public func mindboxEmbeddedBlockViewDidFail(_ blockView: MindboxEmbeddedBlockView) { - onOutcome?("fail") + public func mindboxEmbeddedBlockViewDidBecomeEmpty(_ blockView: MindboxEmbeddedBlockView) { + guard !isTornDown else { return } + onOutcome(EmbeddedBlockWire.outcomeEmpty as NSString, nil) + } + + public func mindboxEmbeddedBlockViewDidFail(_ blockView: MindboxEmbeddedBlockView, + reason: MindboxEmbeddedBlockFailReason) { + guard !isTornDown else { return } + onOutcome(EmbeddedBlockWire.outcomeFail as NSString, reason.rawValue as NSString) } } diff --git a/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm b/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm index 4340088..0204815 100644 --- a/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm +++ b/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm @@ -1,7 +1,7 @@ // The embedded block on iOS, in both renderers. // // The block itself lives in `MindboxEmbeddedBlockHost` — plain UIKit, no React in it — and each -// renderer only carries props to it and its two signals back. Fabric does that through a component +// renderer only carries props to it and its two signals back — the look and the outcome. Fabric does that through a component // view and a C++ event emitter; the old renderer through a view manager and direct event blocks. // The order of the calls into the host is kept the same in both, so a block behaves the same way // whichever renderer the host app runs. @@ -14,9 +14,6 @@ #error "MindboxSdk-Swift.h not found. Ensure Swift sources are included in the MindboxSdk pod target." #endif -// The outcome words the Swift host reports. A contract with the host, not derived from anything. -static NSString *const MindboxEmbeddedBlockOutcomeLoad = @"load"; - #ifdef RCT_NEW_ARCH_ENABLED #import @@ -37,12 +34,11 @@ @implementation MindboxEmbeddedBlockViewComponentView { std::string _placeSystemName; CGFloat _blockHeight; double _timeoutMs; + std::string _loadingStrategy; + BOOL _animatesReveal; BOOL _hasPlaceholder; BOOL _hasErrorView; BOOL _isHostVisible; - - NSString *_pendingAppearance; - NSString *_pendingOutcome; } + (ComponentDescriptorProvider)componentDescriptorProvider @@ -61,6 +57,7 @@ - (instancetype)initWithFrame:(CGRect)frame static const auto defaultProps = std::make_shared(); _props = defaultProps; _isHostVisible = YES; + _animatesReveal = YES; } return self; @@ -82,6 +79,8 @@ - (void)updateProps:(const Props::Shared &)props oldProps:(const Props::Shared & _blockHeight = next.blockHeight; _timeoutMs = next.timeoutMs; + _loadingStrategy = next.loadingStrategy; + _animatesReveal = next.animatesReveal; _hasPlaceholder = next.hasPlaceholder; _hasErrorView = next.hasErrorView; _isHostVisible = next.hostVisible; @@ -102,70 +101,59 @@ - (void)finalizeUpdates:(RNComponentViewUpdateMask)updateMask return; } - _host = [[MindboxEmbeddedBlockHost alloc] initWithPlaceSystemName:@(_placeSystemName.c_str()) - height:_blockHeight - timeoutMs:_timeoutMs]; + // The callbacks go into the host's initializer: the block reports its first look the moment the + // host subscribes to it, and the event emitter is already in place here — Fabric sets it before + // `finalizeUpdates:` on every mount — so that first report reaches JS. + __weak MindboxEmbeddedBlockViewComponentView *weakSelf = self; + _host = [[MindboxEmbeddedBlockHost alloc] + initWithPlaceSystemName:@(_placeSystemName.c_str()) + height:_blockHeight + timeoutMs:_timeoutMs + loadingStrategy:@(_loadingStrategy.c_str()) + animatesReveal:_animatesReveal + onAppearance:^(NSString *appearance, BOOL animated, NSInteger revealDurationMs) { + [weakSelf emitAppearance:appearance animated:animated revealDurationMs:revealDurationMs]; + } + onOutcome:^(NSString *outcome, NSString *_Nullable reason) { + [weakSelf emitOutcome:outcome reason:reason]; + }]; [_host setStandInsWithHasPlaceholder:_hasPlaceholder hasErrorView:_hasErrorView]; [_host setHostVisible:_isHostVisible]; - __weak MindboxEmbeddedBlockViewComponentView *weakSelf = self; - _host.onAppearance = ^(NSString *appearance) { - [weakSelf emitAppearance:appearance]; - }; - _host.onOutcome = ^(NSString *outcome) { - [weakSelf emitOutcome:outcome]; - }; - self.contentView = _host.view; } -- (void)updateEventEmitter:(const EventEmitter::Shared &)eventEmitter -{ - [super updateEventEmitter:eventEmitter]; - - if (_pendingAppearance != nil) { - NSString *appearance = _pendingAppearance; - _pendingAppearance = nil; - [self emitAppearance:appearance]; - } - - if (_pendingOutcome != nil) { - NSString *outcome = _pendingOutcome; - _pendingOutcome = nil; - [self emitOutcome:outcome]; - } -} - - (void)invalidate { [self dropHost]; _placeSystemName = ""; } -- (void)emitAppearance:(NSString *)appearance +// The emitter is set before the host exists and lives as long as the view does, so the guards +// below state an invariant rather than wait for anything: a report with no emitter has nobody to +// go to and is dropped. +- (void)emitAppearance:(NSString *)appearance animated:(BOOL)animated revealDurationMs:(NSInteger)revealDurationMs { if (!_eventEmitter) { - _pendingAppearance = appearance; return; } std::static_pointer_cast(_eventEmitter) - ->onAppearanceChange({.appearance = std::string([appearance UTF8String])}); + ->onAppearanceChange({.appearance = std::string([appearance UTF8String]), + .animated = static_cast(animated), + .revealDurationMs = static_cast(animated ? revealDurationMs : 0)}); } -- (void)emitOutcome:(NSString *)outcome +- (void)emitOutcome:(NSString *)outcome reason:(NSString *_Nullable)reason { if (!_eventEmitter) { - _pendingOutcome = outcome; return; } - const auto emitter = std::static_pointer_cast(_eventEmitter); - if ([outcome isEqualToString:MindboxEmbeddedBlockOutcomeLoad]) { - emitter->onBlockLoad({}); - } else { - emitter->onBlockFail({}); - } + // The payload has every field: a reason that is not there is an empty string. + std::static_pointer_cast(_eventEmitter) + ->onBlockOutcome({.outcome = std::string([outcome UTF8String]), + .reason = std::string([(reason ?: @"") UTF8String])}); } - (void)dropHost @@ -177,8 +165,6 @@ - (void)dropHost [_host tearDown]; self.contentView = nil; _host = nil; - _pendingAppearance = nil; - _pendingOutcome = nil; } @end @@ -210,13 +196,14 @@ @interface MindboxEmbeddedBlockPaperView : RCTView @property (nonatomic, copy) NSString *placeSystemName; @property (nonatomic, assign) CGFloat blockHeight; @property (nonatomic, assign) double timeoutMs; +@property (nonatomic, copy) NSString *loadingStrategy; +@property (nonatomic, assign) BOOL animatesReveal; @property (nonatomic, assign) BOOL hasPlaceholder; @property (nonatomic, assign) BOOL hasErrorView; @property (nonatomic, assign) BOOL hostVisible; @property (nonatomic, copy) RCTDirectEventBlock onAppearanceChange; -@property (nonatomic, copy) RCTDirectEventBlock onBlockLoad; -@property (nonatomic, copy) RCTDirectEventBlock onBlockFail; +@property (nonatomic, copy) RCTDirectEventBlock onBlockOutcome; @end @@ -230,6 +217,7 @@ - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { _hostVisible = YES; + _animatesReveal = YES; } return self; @@ -278,30 +266,38 @@ - (void)buildHostIfPossible // JS side warns the host about a new value rather than applying it. _builtTimeoutMs = _timeoutMs; - _host = [[MindboxEmbeddedBlockHost alloc] initWithPlaceSystemName:_builtPlaceSystemName - height:_blockHeight - timeoutMs:_builtTimeoutMs]; + // The strategy and the animation flag are taken once as well: the native block takes them only + // through its initializer. + // The callbacks go into the host's initializer, as under Fabric: the block reports its first + // look the moment the host subscribes to it. The event blocks are props, set before + // `didSetProps:` and before any layout pass, so they are in place whichever of the two builds. + __weak MindboxEmbeddedBlockPaperView *weakSelf = self; + _host = [[MindboxEmbeddedBlockHost alloc] + initWithPlaceSystemName:_builtPlaceSystemName + height:_blockHeight + timeoutMs:_builtTimeoutMs + loadingStrategy:_loadingStrategy ?: @"" + animatesReveal:_animatesReveal + onAppearance:^(NSString *appearance, BOOL animated, NSInteger revealDurationMs) { + MindboxEmbeddedBlockPaperView *strongSelf = weakSelf; + if (strongSelf.onAppearanceChange != nil) { + strongSelf.onAppearanceChange(@{ + @"appearance" : appearance, + @"animated" : @(animated), + @"revealDurationMs" : @(animated ? revealDurationMs : 0), + }); + } + } + onOutcome:^(NSString *outcome, NSString *_Nullable reason) { + MindboxEmbeddedBlockPaperView *strongSelf = weakSelf; + if (strongSelf.onBlockOutcome != nil) { + // The same shape as under Fabric: every field present, a missing reason is empty. + strongSelf.onBlockOutcome(@{@"outcome" : outcome, @"reason" : reason ?: @""}); + } + }]; [_host setStandInsWithHasPlaceholder:_hasPlaceholder hasErrorView:_hasErrorView]; [_host setHostVisible:_hostVisible]; - __weak MindboxEmbeddedBlockPaperView *weakSelf = self; - _host.onAppearance = ^(NSString *appearance) { - MindboxEmbeddedBlockPaperView *strongSelf = weakSelf; - if (strongSelf.onAppearanceChange != nil) { - strongSelf.onAppearanceChange(@{@"appearance" : appearance}); - } - }; - _host.onOutcome = ^(NSString *outcome) { - MindboxEmbeddedBlockPaperView *strongSelf = weakSelf; - if ([outcome isEqualToString:MindboxEmbeddedBlockOutcomeLoad]) { - if (strongSelf.onBlockLoad != nil) { - strongSelf.onBlockLoad(@{}); - } - } else if (strongSelf.onBlockFail != nil) { - strongSelf.onBlockFail(@{}); - } - }; - UIView *blockView = _host.view; blockView.frame = self.bounds; blockView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; @@ -341,13 +337,14 @@ - (UIView *)view RCT_EXPORT_VIEW_PROPERTY(placeSystemName, NSString) RCT_EXPORT_VIEW_PROPERTY(blockHeight, CGFloat) RCT_EXPORT_VIEW_PROPERTY(timeoutMs, double) +RCT_EXPORT_VIEW_PROPERTY(loadingStrategy, NSString) +RCT_EXPORT_VIEW_PROPERTY(animatesReveal, BOOL) RCT_EXPORT_VIEW_PROPERTY(hasPlaceholder, BOOL) RCT_EXPORT_VIEW_PROPERTY(hasErrorView, BOOL) RCT_EXPORT_VIEW_PROPERTY(hostVisible, BOOL) RCT_EXPORT_VIEW_PROPERTY(onAppearanceChange, RCTDirectEventBlock) -RCT_EXPORT_VIEW_PROPERTY(onBlockLoad, RCTDirectEventBlock) -RCT_EXPORT_VIEW_PROPERTY(onBlockFail, RCTDirectEventBlock) +RCT_EXPORT_VIEW_PROPERTY(onBlockOutcome, RCTDirectEventBlock) @end diff --git a/src/MindboxEmbeddedBlock.tsx b/src/MindboxEmbeddedBlock.tsx index a69f955..ba5b0a5 100644 --- a/src/MindboxEmbeddedBlock.tsx +++ b/src/MindboxEmbeddedBlock.tsx @@ -1,14 +1,17 @@ -import React, { useCallback, useEffect, useRef, useState } from 'react' -import { StyleSheet, View } from 'react-native' +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Animated, Easing, Platform, StyleSheet, View } from 'react-native' import type { StyleProp, ViewStyle } from 'react-native' import MindboxEmbeddedBlockNativeView from './MindboxEmbeddedBlockNativeComponent' import type { NativeProps } from './MindboxEmbeddedBlockNativeComponent' +import { MindboxEmbeddedBlockFailReason } from './MindboxEmbeddedBlockFailReason' +import { MindboxEmbeddedBlockLoadingStrategy } from './MindboxEmbeddedBlockLoadingStrategy' /** - * The handler is typed by the prop it is handed to, not by a second spelling of the same event. + * The handlers are typed by the props they are handed to, not by a second spelling of the same + * events. * - * Spelling it out again would mean naming `NativeSyntheticEvent` here as well, and the two names + * Spelling them out again would mean naming `NativeSyntheticEvent` here as well, and the two names * only agree while both resolve to the same React Native. They do not always: a checkout that sits * under a folder carrying its own React Native resolves this file's import and the spec's to * different copies, and `bob build` then refuses to write the definitions over a `currentTarget` @@ -16,28 +19,39 @@ import type { NativeProps } from './MindboxEmbeddedBlockNativeComponent' * nothing to disagree about. */ type AppearanceChangeHandler = NonNullable +type BlockOutcomeHandler = NonNullable type Appearance = 'placeholder' | 'content' | 'error' | 'collapsed' const APPEARANCES: Array = ['placeholder', 'content', 'error', 'collapsed'] +/** How the load ended — the three words the native blocks report, the same on both platforms. */ +type Outcome = 'load' | 'empty' | 'fail' + +const OUTCOMES: Array = ['load', 'empty', 'fail'] + +/** iOS and Android have the native block; nothing else does. */ +const IS_SUPPORTED = Platform.OS === 'ios' || Platform.OS === 'android' + +/** A host overlay drawn above the native block: the host's placeholder or its error screen. */ +type Overlay = 'placeholder' | 'error' + /** - * Why the place ended up without content. - * - * Empty today, and an object rather than nothing on purpose: the SDK does not yet tell a timeout from - * an empty place from a network failure, and when it does the reason lands here without breaking a - * single caller. + * The curve of the SDK's reveal on each platform, so the slot and the overlay move with the native + * fade: Material's standard curve on Android, ease-in-out on iOS. */ -export type MindboxEmbeddedBlockFailure = {} +const REVEAL_EASING = Platform.OS === 'android' ? Easing.bezier(0.4, 0, 0.2, 1) : Easing.inOut(Easing.ease) export type MindboxEmbeddedBlockProps = { /** * The name of the place from the admin panel. A different name is a different block, built from * scratch in place of the old one. * - * Space around the name is not part of it: the SDK trims the name before resolving by it, on both - * platforms. A name that is empty — or nothing but spaces — is then no name at all, so the place - * resolves to nothing, collapses and reports [onFail]. The component warns about that. + * Passed down as given. Whitespace around the name is not part of it: the native blocks ignore + * it, so a name pasted from the admin panel with a stray space still finds its place. The name + * itself is matched the way the native SDK matches it. A name that is empty — or nothing but + * spaces — is no name at all, so the place resolves to nothing: the block collapses and reports + * [onEmpty], as for any place with nothing behind it. The component warns about that. */ placeSystemName: string @@ -68,9 +82,40 @@ export type MindboxEmbeddedBlockProps = { */ timeoutMs?: number + /** + * What the block shows until the SDK answers — see [MindboxEmbeddedBlockLoadingStrategy]. + * + * `automatic` — the default — keeps the block hidden until the place has shown content once on + * this device and puts a placeholder there from then on. A block that takes its space up front + * keeps the layout still at the price of flashing where there is nothing to show; a block that + * waits hidden never flashes at the price of the layout growing when content arrives. A place + * that always has a campaign behind it is worth an explicit `placeholder`. + * + * A block that waits hidden — `hidden`, and `automatic` at a place that has not shown content + * yet — draws neither [placeholder] nor [error] until its content has been shown once: a failure + * keeps it collapsed, and only [onFail] tells. + * + * Fixed when the block is created, as [timeoutMs] is: a new value on a live block is ignored with + * a warning. Remount the component (give it a new `key`) to build a block anew. + */ + loadingStrategy?: MindboxEmbeddedBlockLoadingStrategy + + /** + * Whether the SDK animates the reveal of the content — a fade, and the growth of a block that + * waited hidden. `true` by default; the system's reduced-motion setting turns the animation off + * as well. Turn it off to animate the block's container yourself in [onLoad]. + * + * Fixed when the block is created, as [timeoutMs] is. + */ + animatesReveal?: boolean + /** * Drawn instead of the SDK shimmer while the block is loading. Fills the whole place, as the native - * placeholder does. + * placeholder does. Not drawn by a block that waits hidden — see [loadingStrategy] — until its + * content has been shown once. + * + * When the content arrives with the SDK's reveal, the placeholder fades out over it rather than + * vanishing a frame before the content is opaque. */ placeholder?: React.ReactNode @@ -78,18 +123,49 @@ export type MindboxEmbeddedBlockProps = { * Drawn instead of collapsing when the block cannot be shown. * * Applies only to failures: an empty place — one with nothing behind its place system name — always - * collapses, so a host cannot fill the space of a block that was never meant to be there. + * collapses, so a host cannot fill the space of a block that was never meant to be there. Nor is it + * drawn by a block that waits hidden — see [loadingStrategy] — which never took the space: with the + * default strategy, a place that has not shown content on this device yet simply stays collapsed + * on a failure, and only [onFail] tells. */ error?: React.ReactNode - /** The content is shown. */ + /** + * The content is shown: the block has taken its height and is visible. A block that waited hidden + * is only starting to grow from zero at this moment — a host that measures the block here, or + * scrolls to it, sees it still at almost no height until the reveal is over. + * + * Delivered once per outcome, not once per lifetime: the same outcome is never repeated, and an + * outcome that actually changed — a place that filled up after a failure — is delivered again. + * The native block reports the same way, so every wrapper of the SDK calls back alike. + */ onLoad?: () => void /** - * The place ended up without content: the load failed or timed out, or there is nothing behind the - * name. An empty place is a normal outcome, not a breakage. + * There is nothing to show at the place: no campaign behind its name, the targeting or the A/B + * group did not match, the show budget is spent, or the page rendered nothing. A normal outcome, + * not a breakage: the block collapses, [error] does not apply, and no reason is given — which of + * these it was is the SDK's business. + * + * Delivered on the same rule as [onLoad]: once per outcome, again if the outcome changes. + */ + onEmpty?: () => void + + /** + * The block could not be shown: the SDK had no config or never answered, the page could not be + * loaded, the content is malformed or the SDK hit an internal error. The block collapses, or keeps + * its height and draws [error] when one is given — unless it was waiting hidden, see + * [loadingStrategy]: a block that never took its space stays collapsed whatever [error] says. An + * empty place is not a failure and arrives in [onEmpty] instead. + * + * The reason is for logs and analytics, not for branching: whatever it is, the block has already + * collapsed or switched to [error]. Compare it with the constants of + * [MindboxEmbeddedBlockFailReason] and keep a fallback — a later SDK may add reasons. + * + * Delivered on the same rule as [onLoad]: once per outcome, again if the outcome changes. A + * failure that repeats with a different reason is the same outcome and is not delivered again. */ - onFail?: (failure: MindboxEmbeddedBlockFailure) => void + onFail?: (reason: MindboxEmbeddedBlockFailReason) => void /** * Whether the screen the block stands on is the one being looked at. `true` by default. @@ -115,20 +191,36 @@ export type MindboxEmbeddedBlockProps = { * * ``` * - * Both outcomes can be customized, the same way as in SwiftUI, Compose and Flutter: [placeholder] + * Both looks can be customized, the same way as in SwiftUI, Compose and Flutter: [placeholder] * replaces the stock loading shimmer, and [error] opts into showing a failure instead of collapsing. * Both stay ordinary RN nodes, drawn above the native view, so they resolve the context, the theme * and the handlers of the tree the block itself stands in. The wait for an answer is bounded by * [timeoutMs] — 30 seconds unless the host says otherwise. * + * What the block shows until the SDK has decided what goes into it is the [loadingStrategy]: a + * placeholder, nothing, or — by default — nothing until the place has shown content once on this + * device and a placeholder from then on. The content is revealed with the SDK's own animation — it + * fades in, and a block that started hidden grows to its height — unless [animatesReveal] is off. + * + * The outcome arrives through three callbacks, the same three as in SwiftUI, Compose and Flutter: + * [onLoad] when the content is shown, [onEmpty] when there is nothing to show at the place, and + * [onFail] with a reason when the block could not be shown. + * * The component is a thin layer over the native block: the native view holds the SDK's own container * — with its waiting budget and its web page — and this component only mirrors the container's * decisions in the RN layout. + * + * **iOS and Android.** On any other platform the block collapses right away and reports [onFail] + * with `internalError`, so a layout that hides its section on failure behaves the same everywhere. */ export const MindboxEmbeddedBlock = (props: MindboxEmbeddedBlockProps) => -const Block = ({ placeSystemName, height, timeoutMs, placeholder, error, onLoad, onFail, active = true, style }: MindboxEmbeddedBlockProps) => { - const [appearance, setAppearance] = useState('placeholder') +const Block = ({ placeSystemName, height, timeoutMs, loadingStrategy = MindboxEmbeddedBlockLoadingStrategy.automatic, animatesReveal = true, placeholder, error, onLoad, onEmpty, onFail, active = true, style }: MindboxEmbeddedBlockProps) => { + const creationTimeoutMs = useRef(timeoutMs).current + const creationLoadingStrategy = useRef(loadingStrategy).current + const creationAnimatesReveal = useRef(animatesReveal).current + + const [appearance, setAppearance] = useState(() => (IS_SUPPORTED ? firstLook(creationLoadingStrategy) : 'collapsed')) const blockHeight = Number.isFinite(height) ? Math.max(0, height) : 0 @@ -140,7 +232,7 @@ const Block = ({ placeSystemName, height, timeoutMs, placeholder, error, onLoad, // SDK trims the name before it resolves by it, so a padded name finds its place either way. useEffect(() => { if (placeSystemName.trim().length === 0) { - console.warn('[MindboxEmbeddedBlock] A block was created without a place system name: there is nothing to resolve by it, so the place collapses and reports onFail.') + console.warn('[MindboxEmbeddedBlock] A block was created without a place system name: there is nothing to resolve by it, so the place collapses and reports onEmpty.') } if (blockHeight <= 0) { console.warn(`[MindboxEmbeddedBlock] The block "${placeSystemName}" was created with height ${height}: it reserves no space, so nothing loads and no outcome is reported.`) @@ -149,66 +241,194 @@ const Block = ({ placeSystemName, height, timeoutMs, placeholder, error, onLoad, // eslint-disable-next-line react-hooks/exhaustive-deps }, []) - const creationTimeoutMs = useRef(timeoutMs).current - const hasWarnedAboutTimeout = useRef(false) + // The values fixed at creation: a new one is ignored and said once, per value. + const warnedCreationValues = useRef(new Set()) useEffect(() => { - if (timeoutMs === creationTimeoutMs || hasWarnedAboutTimeout.current) { - return + const warnIfIgnored = (name: string, given: unknown, kept: unknown) => { + if (given === kept || warnedCreationValues.current.has(name)) { + return + } + warnedCreationValues.current.add(name) + console.warn(`[MindboxEmbeddedBlock] The block "${placeSystemName}" was given ${name} ${String(given)} after creation and keeps ${String(kept)}: ${name} is fixed when the block is created. Remount the component — give it a new key — to build a block anew.`) } - hasWarnedAboutTimeout.current = true - console.warn(`[MindboxEmbeddedBlock] The block "${placeSystemName}" keeps the timeout it was created with; the new value is ignored. Remount the component — give it a new key — to change the timeout.`) - }, [timeoutMs, creationTimeoutMs, placeSystemName]) + warnIfIgnored('timeoutMs', timeoutMs, creationTimeoutMs) + warnIfIgnored('loadingStrategy', loadingStrategy, creationLoadingStrategy) + warnIfIgnored('animatesReveal', animatesReveal, creationAnimatesReveal) + }, [timeoutMs, creationTimeoutMs, loadingStrategy, creationLoadingStrategy, animatesReveal, creationAnimatesReveal, placeSystemName]) - const deliveredOutcome = useRef<'load' | 'fail' | null>(null) + // The callbacks are read through a ref at delivery time, so a host that passes a fresh closure + // on every render neither re-subscribes anything nor misses the one delivery of an outcome. + const callbacks = useRef({ onLoad, onEmpty, onFail }) + callbacks.current = { onLoad, onEmpty, onFail } - const handleAppearanceChange = useCallback((event) => { - const reported = event.nativeEvent.appearance - if (APPEARANCES.includes(reported)) { - setAppearance(reported as Appearance) - } - }, []) + /** + * The outcome delivered last — the deduplication key. Deliberately without the failure reason: + * a silent retry that fails differently is still the same outcome. + */ + const deliveredOutcome = useRef(null) - const handleLoad = useCallback(() => { - if (deliveredOutcome.current === 'load') { + const deliver = useCallback((outcome: Outcome, reason: string | null) => { + if (outcome === deliveredOutcome.current) { return } - deliveredOutcome.current = 'load' - onLoad?.() - }, [onLoad]) + deliveredOutcome.current = outcome + switch (outcome) { + case 'load': + callbacks.current.onLoad?.() + break + case 'empty': + callbacks.current.onEmpty?.() + break + case 'fail': + callbacks.current.onFail?.(reason || MindboxEmbeddedBlockFailReason.internalError) + break + } + }, []) - const handleFail = useCallback(() => { - if (deliveredOutcome.current === 'fail') { - return + // No native block to report: the place collapses and the host hears the same failure it would + // hear from a block that could not be shown. In an effect, after the first commit, as a native + // block's report would arrive after the first layout. + useEffect(() => { + if (!IS_SUPPORTED) { + deliver('fail', MindboxEmbeddedBlockFailReason.internalError) } - deliveredOutcome.current = 'fail' - onFail?.({}) - }, [onFail]) + }, [deliver]) + + /** The growth of a block that waited hidden: 0 to 1 over the SDK's reveal, 1 at rest. */ + const reveal = useRef(new Animated.Value(1)).current + /** The opacity of a host overlay the content is replacing: 1 to 0 over the SDK's reveal. */ + const overlayFade = useRef(new Animated.Value(1)).current + /** The overlay still fading out above the content, if any. */ + const [fadingOverlay, setFadingOverlay] = useState(null) + /** Tells a fade that ran its course from one that was interrupted and restarted. */ + const fadeGeneration = useRef(0) + const shownAppearance = useRef(appearance) + + /** + * Takes the block to [next]. The arrival of content is the one change that is animated, and only + * when the native block says so — it owns that decision, gates included — for as long as it + * says: a slot that was closed grows, and a host overlay the content replaces fades out above + * it. Everything else lands at once. + */ + const show = useCallback( + (next: Appearance, revealDurationMs?: number) => { + const previous = shownAppearance.current + const duration = revealDurationMs ?? 0 + const reveals = next === 'content' && duration > 0 + shownAppearance.current = next + setAppearance(next) + + if (reveals && previous === 'collapsed') { + reveal.setValue(0) + Animated.timing(reveal, { toValue: 1, duration, easing: REVEAL_EASING, useNativeDriver: false }).start() + } else { + reveal.stopAnimation() + reveal.setValue(1) + } + + // The native block fades its content in from transparent, and the host's stand-in under it + // is clear — so a placeholder or an error screen taken away in the same frame would leave the + // screen's background showing through the fade. SwiftUI and Compose fade their stand-ins out + // under the content for the same reason; here the overlay lies above the native view, so it + // fades out over the same duration instead. Any other change takes it away at once. + fadeGeneration.current += 1 + const generation = fadeGeneration.current + overlayFade.stopAnimation() + if (reveals && (previous === 'placeholder' || previous === 'error')) { + setFadingOverlay(previous) + overlayFade.setValue(1) + Animated.timing(overlayFade, { toValue: 0, duration, easing: REVEAL_EASING, useNativeDriver: false }).start(({ finished }) => { + if (finished && fadeGeneration.current === generation) { + setFadingOverlay(null) + } + }) + } else { + setFadingOverlay(null) + overlayFade.setValue(1) + } + }, + [reveal, overlayFade] + ) + + const handleAppearanceChange = useCallback( + (event) => { + const { appearance: reported, animated, revealDurationMs } = event.nativeEvent + if (APPEARANCES.includes(reported) && reported !== shownAppearance.current) { + show(reported as Appearance, animated ? revealDurationMs : undefined) + } + }, + [show] + ) + + const handleOutcome = useCallback( + (event) => { + const { outcome, reason } = event.nativeEvent + if (OUTCOMES.includes(outcome)) { + deliver(outcome as Outcome, reason) + } + }, + [deliver] + ) + + // The overlay of the current look, or the one still fading out above the content. + const shownOverlay: Overlay | null = appearance === 'placeholder' || appearance === 'error' ? appearance : fadingOverlay + const overlay = shownOverlay === 'placeholder' ? placeholder : shownOverlay === 'error' ? error : null + const isOverlayFading = shownOverlay != null && shownOverlay !== appearance - const overlay = appearance === 'placeholder' ? placeholder : appearance === 'error' ? error : null + // The height the layout is given: nothing for a collapsed block, the block's height otherwise — + // and, while a block that waited hidden is revealed, the part of it the growth has reached. + const slotHeight = useMemo(() => reveal.interpolate({ inputRange: [0, 1], outputRange: [0, blockHeight] }), [reveal, blockHeight]) return ( - - - {overlay != null ? ( - - {overlay} - - ) : null} - + {/* + The slot is what the layout sees; the block inside keeps its full height whatever the slot + is. A native view sized to nothing is never built — both native halves wait for a frame — + so a block that waits hidden would never load and never grow. With its own height under a + clipped slot of zero it runs its whole cycle unseen, as the native blocks do, and the slot + opens when the content arrives. + */} + + {IS_SUPPORTED ? : null} + {overlay != null ? ( + // An overlay on its way out is a picture, not a surface: touches go through to the content. + + {overlay} + + ) : null} + + ) } +/** + * The look a block starts with, before the native block exists to say. + * + * `placeholder` and `hidden` are decided by the strategy alone. `automatic` is decided by the SDK's + * memory of the place, which only the native side has: the native block reads it as it is built and + * reports its first look right away. Until that report an `automatic` block takes no space: a place + * that has never shown content must not flash reserved space, and one that has shows its placeholder + * a frame late rather than a frame early. + */ +const firstLook = (strategy: MindboxEmbeddedBlockLoadingStrategy): Appearance => (strategy === MindboxEmbeddedBlockLoadingStrategy.placeholder ? 'placeholder' : 'collapsed') + const styles = StyleSheet.create({ block: { width: '100%', overflow: 'hidden', }, + inside: { + position: 'absolute', + top: 0, + left: 0, + right: 0, + }, }) export default MindboxEmbeddedBlock diff --git a/src/MindboxEmbeddedBlockFailReason.ts b/src/MindboxEmbeddedBlockFailReason.ts new file mode 100644 index 0000000..b471408 --- /dev/null +++ b/src/MindboxEmbeddedBlockFailReason.ts @@ -0,0 +1,30 @@ +/** + * Why a block could not be shown — the payload of `MindboxEmbeddedBlock`'s `onFail`. + * + * Meant for logs and analytics on the host side, not for branching: whatever the reason, the block + * has already collapsed or switched to its error screen. A string rather than a closed union so a + * later SDK can add a reason without breaking an exhaustive `switch` — keep a fallback when + * matching. The raw values are the same on every platform: what the native iOS and Android blocks + * report under these names reaches React Native unchanged. + * + * The constants below are the ones this version knows; a later SDK may report a word that is not + * among them, and it arrives as it is. + */ +export type MindboxEmbeddedBlockFailReason = 'networkError' | 'internalError' | (string & {}) + +export const MindboxEmbeddedBlockFailReason = { + /** + * The content is unavailable because of the environment: the config could not be downloaded and + * nothing is cached, the SDK gave no answer within the block's waiting budget, the block's page + * could not be loaded, or — on iOS — the data the targeting needs could not be fetched. Typically + * a network problem. + */ + networkError: 'networkError', + + /** + * An error on the Mindbox side: the page loaded but never reported its content or reported + * something unusable, or the SDK failed inside. Also what a platform without a native block + * reports. + */ + internalError: 'internalError', +} as const diff --git a/src/MindboxEmbeddedBlockLoadingStrategy.ts b/src/MindboxEmbeddedBlockLoadingStrategy.ts new file mode 100644 index 0000000..e55e90a --- /dev/null +++ b/src/MindboxEmbeddedBlockLoadingStrategy.ts @@ -0,0 +1,43 @@ +/** + * What the block shows until the SDK has decided what goes into it — given at creation. + * + * Every place marked up in the app waits for the SDK on every launch, and a place with no campaign + * behind it would flash a placeholder and collapse each time. The strategy decides whether the + * block takes its space before the answer, and the SDK remembers per place whether content was + * ever shown there: nothing flashes where no content is expected, and where it is expected the + * space is taken as soon as the native side has read that memory — a frame after the block is + * mounted, not from the first frame. + * + * The same three values exist on every platform; `automatic` is the default everywhere. + */ +export type MindboxEmbeddedBlockLoadingStrategy = 'automatic' | 'placeholder' | 'hidden' + +export const MindboxEmbeddedBlockLoadingStrategy = { + /** + * Hidden until the place has shown content once on this device; a placeholder from then on. + * + * The memory is per place system name and survives a restart. It is dropped when the place + * answers with nothing to show — the campaign was switched off, the targeting did not match, the + * page rendered nothing — so the next launch starts hidden again. A failure keeps the memory: + * that is "could not", not "nothing here". + * + * The memory lives on the native side and reaches JS a moment after the block is mounted, so an + * `automatic` block takes no space until it has: a place that has shown content before gets its + * placeholder a frame late rather than a place that has not getting a frame of reserved space. + * + * At a place that has not shown content yet the block waits hidden, as under `hidden`: no + * placeholder, and no `error` on a failure — only `onFail` tells. + */ + automatic: 'automatic', + + /** Always a placeholder until the answer: the SDK shimmer or the host's own `placeholder`. */ + placeholder: 'placeholder', + + /** + * Hidden until the content is shown once: zero height, no placeholder, and no `error` on a + * failure — a block that never took its space does not take it for an error screen either. The + * outcome still arrives through `onFail`. Once content was shown the space is taken, and a later + * failure may keep it with the host's error screen, like on every platform. + */ + hidden: 'hidden', +} as const diff --git a/src/MindboxEmbeddedBlockNativeComponent.ts b/src/MindboxEmbeddedBlockNativeComponent.ts index 35a1c68..a999cfc 100644 --- a/src/MindboxEmbeddedBlockNativeComponent.ts +++ b/src/MindboxEmbeddedBlockNativeComponent.ts @@ -1,9 +1,26 @@ import type { ViewProps } from 'react-native' -import type { DirectEventHandler, Double, WithDefault } from 'react-native/Libraries/Types/CodegenTypes' +import type { DirectEventHandler, Double, Int32, WithDefault } from 'react-native/Libraries/Types/CodegenTypes' import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent' +/** + * The look the native block shows: `placeholder`, `content`, `error` or `collapsed`. `animated` is + * `true` for the one change that is the SDK's reveal of content — the native block owns that + * decision, gates included — and `revealDurationMs` is how long it takes; both are `false` and `0` + * for every other change. + */ type AppearanceChangeEvent = Readonly<{ appearance: string + animated: boolean + revealDurationMs: Int32 +}> + +/** + * How the load ended: `load`, `empty` or `fail`. The reason goes with a failure and is empty + * otherwise — an event payload has every field, so the absence is spelled as an empty string. + */ +type BlockOutcomeEvent = Readonly<{ + outcome: string + reason: string }> export interface NativeProps extends ViewProps { @@ -13,6 +30,11 @@ export interface NativeProps extends ViewProps { timeoutMs?: Double + /** `automatic`, `placeholder` or `hidden`; an empty word means `automatic`. */ + loadingStrategy?: string + + animatesReveal?: WithDefault + hasPlaceholder?: WithDefault hasErrorView?: WithDefault @@ -21,9 +43,7 @@ export interface NativeProps extends ViewProps { onAppearanceChange?: DirectEventHandler - onBlockLoad?: DirectEventHandler - - onBlockFail?: DirectEventHandler + onBlockOutcome?: DirectEventHandler } export default codegenNativeComponent('MindboxEmbeddedBlockView') diff --git a/src/__tests__/MindboxEmbeddedBlock.test.tsx b/src/__tests__/MindboxEmbeddedBlock.test.tsx index c89101e..0d4d4eb 100644 --- a/src/__tests__/MindboxEmbeddedBlock.test.tsx +++ b/src/__tests__/MindboxEmbeddedBlock.test.tsx @@ -4,6 +4,8 @@ import { act, create } from 'react-test-renderer' import type { ReactTestRenderer } from 'react-test-renderer' import { MindboxEmbeddedBlock } from '../MindboxEmbeddedBlock' +import { MindboxEmbeddedBlockFailReason } from '../MindboxEmbeddedBlockFailReason' +import { MindboxEmbeddedBlockLoadingStrategy } from '../MindboxEmbeddedBlockLoadingStrategy' jest.mock('../MindboxEmbeddedBlockNativeComponent', () => { const ReactActual = require('react') @@ -32,20 +34,36 @@ const asType = (component: unknown) => component as any const nativeProps = (renderer: ReactTestRenderer) => renderer.root.findByProps({ testID: 'native-block' }).props -const reportAppearance = (renderer: ReactTestRenderer, appearance: string) => { +const reportAppearance = (renderer: ReactTestRenderer, appearance: string, reveal: { animated: boolean; revealDurationMs: number } = { animated: false, revealDurationMs: 0 }) => { act(() => { - nativeProps(renderer).onAppearanceChange({ nativeEvent: { appearance } }) + nativeProps(renderer).onAppearanceChange({ nativeEvent: { appearance, ...reveal } }) }) } +/** The native block's report of how the load ended; an empty reason is what the event carries when there is none. */ +const reportOutcome = (renderer: ReactTestRenderer, outcome: string, reason = '') => { + act(() => { + nativeProps(renderer).onBlockOutcome({ nativeEvent: { outcome, reason } }) + }) +} + +/** The height the layout is given: the slot the block stands in. */ const frameHeight = (renderer: ReactTestRenderer) => { const frame = renderer.root.findAllByType(asType(View))[0] return StyleSheet.flatten(frame.props.style).height } +/** The height of the block inside the slot — what the native view is laid out in. */ +const insideHeight = (renderer: ReactTestRenderer) => { + const inside = renderer.root.findAllByType(asType(View))[1] + return StyleSheet.flatten(inside.props.style).height +} + +const placeholderBlock = (props: Partial> = {}) => + describe('MindboxEmbeddedBlock', () => { it('takes its height while loading and hands it back when the block collapses', () => { - const renderer = render() + const renderer = render(placeholderBlock()) expect(frameHeight(renderer)).toBe(104) @@ -55,19 +73,20 @@ describe('MindboxEmbeddedBlock', () => { }) it('resizes a live block in place when the height changes', () => { - const renderer = render() + const renderer = render(placeholderBlock({ height: 160 })) - update(renderer, ) + update(renderer, placeholderBlock({ height: 80 })) expect(frameHeight(renderer)).toBe(80) + expect(insideHeight(renderer)).toBe(80) expect(nativeProps(renderer).blockHeight).toBe(80) }) - it('says nothing about space around a name the SDK trims anyway', () => { + it('passes a name with spaces around it to the native block as given, and says nothing about it', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) - const renderer = render() + const renderer = render(placeholderBlock({ placeSystemName: ' stories ' })) - update(renderer, ) + update(renderer, placeholderBlock({ placeSystemName: ' stories ' })) expect(warn).not.toHaveBeenCalled() expect(nativeProps(renderer).placeSystemName).toBe(' stories ') @@ -76,9 +95,9 @@ describe('MindboxEmbeddedBlock', () => { it('warns once about a place system name that is not there at all', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) - const renderer = render() + const renderer = render(placeholderBlock({ placeSystemName: '' })) - update(renderer, ) + update(renderer, placeholderBlock({ placeSystemName: '' })) expect(warn).toHaveBeenCalledTimes(1) expect(warn.mock.calls[0][0]).toContain('without a place system name') @@ -88,24 +107,27 @@ describe('MindboxEmbeddedBlock', () => { it('calls a name of nothing but spaces a missing name, not a padded one', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) - render() + render(placeholderBlock({ placeSystemName: ' ' })) expect(warn).toHaveBeenCalledTimes(1) expect(warn.mock.calls[0][0]).toContain('without a place system name') warn.mockRestore() }) - it('hands the failure of a nameless place to the host and gives the space back', () => { + it('hands a nameless place to the host as an empty one and gives the space back', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) + const onEmpty = jest.fn() const onFail = jest.fn() - const renderer = render() + const renderer = render(placeholderBlock({ placeSystemName: '', onEmpty, onFail })) + + expect(warn.mock.calls[0][0]).toContain('reports onEmpty') + // What the native blocks report for a name of nothing: a place with nothing behind it. reportAppearance(renderer, 'collapsed') - act(() => { - nativeProps(renderer).onBlockFail() - }) + reportOutcome(renderer, 'empty') - expect(onFail).toHaveBeenCalledTimes(1) + expect(onEmpty).toHaveBeenCalledTimes(1) + expect(onFail).not.toHaveBeenCalled() expect(frameHeight(renderer)).toBe(0) warn.mockRestore() }) @@ -116,7 +138,7 @@ describe('MindboxEmbeddedBlock', () => { ['not a number', Number.NaN], ])('warns about a %s height that reserves no space and hands the layout zero', (_name, height) => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) - const renderer = render() + const renderer = render(placeholderBlock({ height })) expect(warn).toHaveBeenCalledTimes(1) expect(warn.mock.calls[0][0]).toContain('reserves no space') @@ -126,7 +148,7 @@ describe('MindboxEmbeddedBlock', () => { }) it('tells the native block the place, the height and whether the place is taken', () => { - const renderer = render(wait} active={false} />) + const renderer = render(placeholderBlock({ placeholder: wait, active: false })) expect(nativeProps(renderer)).toMatchObject({ placeSystemName: 'stories', @@ -138,31 +160,32 @@ describe('MindboxEmbeddedBlock', () => { }) it('sends zero for a timeout the host did not set', () => { - const renderer = render() + const renderer = render(placeholderBlock()) expect(nativeProps(renderer).timeoutMs).toBe(0) }) it('sends the timeout it was created with, in milliseconds', () => { - const renderer = render() + const renderer = render(placeholderBlock({ timeoutMs: 5000 })) expect(nativeProps(renderer).timeoutMs).toBe(5000) }) it('keeps the timeout it was created with and warns once about a change', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) - const renderer = render() + const renderer = render(placeholderBlock({ timeoutMs: 5000 })) - update(renderer, ) - update(renderer, ) + update(renderer, placeholderBlock({ timeoutMs: 1000 })) + update(renderer, placeholderBlock({ timeoutMs: 2000 })) expect(nativeProps(renderer).timeoutMs).toBe(5000) expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('timeoutMs') warn.mockRestore() }) it('draws the host placeholder over the loading block and the host error over the failed one', () => { - const renderer = render(loading} error={broken} />) + const renderer = render(placeholderBlock({ placeholder: loading, error: broken })) expect(renderer.root.findByType(asType(Text)).props.children).toBe('loading') @@ -175,27 +198,114 @@ describe('MindboxEmbeddedBlock', () => { expect(renderer.root.findByType(asType(Text)).props.children).toBe('broken') }) - it('delivers each outcome once and a changed outcome again', () => { - const onLoad = jest.fn() - const onFail = jest.fn() - const renderer = render() + describe('the outcome', () => { + it('delivers each outcome once and a changed outcome again', () => { + const onLoad = jest.fn() + const onFail = jest.fn() + const renderer = render(placeholderBlock({ onLoad, onFail })) + + reportOutcome(renderer, 'load') + reportOutcome(renderer, 'load') + + expect(onLoad).toHaveBeenCalledTimes(1) - act(() => { - nativeProps(renderer).onBlockLoad() - nativeProps(renderer).onBlockLoad() + reportOutcome(renderer, 'fail', 'networkError') + + expect(onFail).toHaveBeenCalledTimes(1) }) - expect(onLoad).toHaveBeenCalledTimes(1) + it('reports an empty place through onEmpty, with the space given back and no reason', () => { + const onEmpty = jest.fn() + const onFail = jest.fn() + const renderer = render(placeholderBlock({ onEmpty, onFail })) + + reportAppearance(renderer, 'collapsed') + reportOutcome(renderer, 'empty') + + expect(onEmpty).toHaveBeenCalledTimes(1) + expect(onEmpty).toHaveBeenCalledWith() + expect(onFail).not.toHaveBeenCalled() + expect(frameHeight(renderer)).toBe(0) + }) + + it('hands the failure reason to onFail as the native block spelled it', () => { + const onFail = jest.fn() + const renderer = render(placeholderBlock({ onFail })) + + reportOutcome(renderer, 'fail', 'networkError') - act(() => { - nativeProps(renderer).onBlockFail() + expect(onFail).toHaveBeenCalledWith(MindboxEmbeddedBlockFailReason.networkError) }) - expect(onFail).toHaveBeenCalledTimes(1) + it('passes a reason it does not know through as it is', () => { + const onFail = jest.fn() + const renderer = render(placeholderBlock({ onFail })) + + reportOutcome(renderer, 'fail', 'sideways') + + expect(onFail).toHaveBeenCalledWith('sideways') + }) + + it('calls a failure without a reason an internal error', () => { + const onFail = jest.fn() + const renderer = render(placeholderBlock({ onFail })) + + reportOutcome(renderer, 'fail') + + expect(onFail).toHaveBeenCalledWith(MindboxEmbeddedBlockFailReason.internalError) + }) + + it('delivers a failure that repeats with another reason once', () => { + const onFail = jest.fn() + const renderer = render(placeholderBlock({ onFail })) + + reportOutcome(renderer, 'fail', 'networkError') + reportOutcome(renderer, 'fail', 'internalError') + + expect(onFail).toHaveBeenCalledTimes(1) + expect(onFail).toHaveBeenCalledWith('networkError') + }) + + it('delivers a sequence of outcomes in order, repeats dropped', () => { + const delivered: Array = [] + const renderer = render(placeholderBlock({ onLoad: () => delivered.push('load'), onEmpty: () => delivered.push('empty'), onFail: (reason) => delivered.push(`fail:${reason}`) })) + + reportOutcome(renderer, 'empty') + reportOutcome(renderer, 'empty') + reportOutcome(renderer, 'load') + reportOutcome(renderer, 'fail', 'networkError') + + expect(delivered).toEqual(['empty', 'load', 'fail:networkError']) + }) + + it('ignores an outcome it does not know', () => { + const onLoad = jest.fn() + const onEmpty = jest.fn() + const onFail = jest.fn() + const renderer = render(placeholderBlock({ onLoad, onEmpty, onFail })) + + reportOutcome(renderer, 'sideways') + + expect(onLoad).not.toHaveBeenCalled() + expect(onEmpty).not.toHaveBeenCalled() + expect(onFail).not.toHaveBeenCalled() + }) + + it('calls the handler the host passed last, not the one it passed first', () => { + const first = jest.fn() + const second = jest.fn() + const renderer = render(placeholderBlock({ onLoad: first })) + + update(renderer, placeholderBlock({ onLoad: second })) + reportOutcome(renderer, 'load') + + expect(first).not.toHaveBeenCalled() + expect(second).toHaveBeenCalledTimes(1) + }) }) it('ignores an appearance it does not know, keeping the last known one', () => { - const renderer = render() + const renderer = render(placeholderBlock()) reportAppearance(renderer, 'collapsed') reportAppearance(renderer, 'sideways') @@ -205,16 +315,266 @@ describe('MindboxEmbeddedBlock', () => { it('builds a different place as a different block, with nothing remembered', () => { const onLoad = jest.fn() - const renderer = render() + const renderer = render(placeholderBlock({ onLoad })) + + reportOutcome(renderer, 'load') + update(renderer, placeholderBlock({ placeSystemName: 'banner', onLoad })) + reportOutcome(renderer, 'load') + + expect(onLoad).toHaveBeenCalledTimes(2) + }) - act(() => { - nativeProps(renderer).onBlockLoad() + describe('the strategy and the animation flag', () => { + it('tells the native block the strategy and the flag it was created with', () => { + const renderer = render() + + expect(nativeProps(renderer)).toMatchObject({ loadingStrategy: 'hidden', animatesReveal: false }) }) - update(renderer, ) - act(() => { - nativeProps(renderer).onBlockLoad() + + it('starts automatic and animated when the host says nothing', () => { + const renderer = render() + + expect(nativeProps(renderer)).toMatchObject({ loadingStrategy: 'automatic', animatesReveal: true }) }) - expect(onLoad).toHaveBeenCalledTimes(2) + it('names the strategies by the words the native blocks take', () => { + expect(MindboxEmbeddedBlockLoadingStrategy).toEqual({ automatic: 'automatic', placeholder: 'placeholder', hidden: 'hidden' }) + }) + + it('keeps the strategy and the flag it was created with and warns once about each change', () => { + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined) + const renderer = render(placeholderBlock({ animatesReveal: true })) + + update(renderer, ) + update(renderer, ) + + expect(nativeProps(renderer)).toMatchObject({ loadingStrategy: 'placeholder', animatesReveal: true }) + expect(warn).toHaveBeenCalledTimes(2) + expect(warn.mock.calls[0][0]).toContain('loadingStrategy') + expect(warn.mock.calls[1][0]).toContain('animatesReveal') + warn.mockRestore() + }) + }) + + describe('the first look', () => { + it('gives a placeholder block its height from the first frame', () => { + const renderer = render(placeholderBlock({ placeholder: loading })) + + expect(frameHeight(renderer)).toBe(104) + expect(renderer.root.findByType(asType(Text)).props.children).toBe('loading') + }) + + it('gives a hidden block no slot while the native view inside keeps the full height', () => { + const renderer = render(loading} />) + + expect(frameHeight(renderer)).toBe(0) + expect(insideHeight(renderer)).toBe(104) + expect(nativeProps(renderer).blockHeight).toBe(104) + expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) + }) + + it('keeps an automatic block at zero until the native block reports a placeholder, then shows it', () => { + const renderer = render(loading} />) + + expect(frameHeight(renderer)).toBe(0) + expect(insideHeight(renderer)).toBe(104) + expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) + + reportAppearance(renderer, 'placeholder') + + expect(frameHeight(renderer)).toBe(104) + expect(renderer.root.findByType(asType(Text)).props.children).toBe('loading') + }) + + it('keeps an automatic block at zero when the native block reports collapsed', () => { + const renderer = render() + + reportAppearance(renderer, 'collapsed') + + expect(frameHeight(renderer)).toBe(0) + }) + }) + + describe('the reveal', () => { + const hiddenBlock = () => + + beforeEach(() => { + jest.useFakeTimers('modern') + }) + + afterEach(() => { + jest.useRealTimers() + }) + + const tick = (ms: number) => { + act(() => { + jest.advanceTimersByTime(ms) + }) + } + + it('grows a block that waited hidden from zero to its height over the SDK reveal', () => { + const renderer = render(hiddenBlock()) + + reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) + + expect(frameHeight(renderer)).toBe(0) + + tick(125) + + expect(frameHeight(renderer)).toBeGreaterThan(30) + expect(frameHeight(renderer)).toBeLessThan(74) + + tick(125) + + expect(frameHeight(renderer)).toBe(104) + }) + + it('lands at once when the native block does not call the change a reveal', () => { + const renderer = render(hiddenBlock()) + + reportAppearance(renderer, 'content') + + expect(frameHeight(renderer)).toBe(104) + }) + + it('lands at once when the reveal comes without a duration', () => { + const renderer = render(hiddenBlock()) + + reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 0 }) + + expect(frameHeight(renderer)).toBe(104) + }) + + it('does not grow content that arrives into a placeholder: the space was taken already', () => { + const renderer = render(placeholderBlock()) + + reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) + + expect(frameHeight(renderer)).toBe(104) + + tick(125) + + expect(frameHeight(renderer)).toBe(104) + }) + + it('collapses at once in the middle of a reveal', () => { + const renderer = render(hiddenBlock()) + + reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) + tick(125) + reportAppearance(renderer, 'collapsed') + + expect(frameHeight(renderer)).toBe(0) + + tick(250) + + expect(frameHeight(renderer)).toBe(0) + }) + + it.each(['error', 'placeholder'])('takes the full height at once when %s arrives in the middle of a reveal', (appearance) => { + const renderer = render(loading} error={broken} />) + + reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) + tick(125) + const midway = frameHeight(renderer) + expect(midway).toBeGreaterThan(0) + expect(midway).toBeLessThan(104) + + reportAppearance(renderer, appearance) + + expect(frameHeight(renderer)).toBe(104) + + // The old growth is stopped, not left to finish on its own schedule. + tick(60) + + expect(frameHeight(renderer)).toBe(104) + }) + + describe('the host overlay under the reveal', () => { + /** The host's overlay layer: the view that holds the placeholder or the error screen. */ + const overlayHost = (renderer: ReactTestRenderer) => renderer.root.findAll((node) => node.type === View && (node.props.pointerEvents === 'box-none' || node.props.pointerEvents === 'none'))[0] + + const overlayOpacity = (renderer: ReactTestRenderer) => StyleSheet.flatten(overlayHost(renderer).props.style).opacity + + it('keeps the host placeholder above the arriving content and fades it out over the reveal', () => { + const renderer = render(placeholderBlock({ placeholder: loading })) + + reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) + + expect(renderer.root.findByType(asType(Text)).props.children).toBe('loading') + expect(overlayHost(renderer).props.pointerEvents).toBe('none') + expect(overlayOpacity(renderer)).toBe(1) + + tick(125) + + expect(overlayOpacity(renderer)).toBeGreaterThan(0.2) + expect(overlayOpacity(renderer)).toBeLessThan(0.8) + + tick(125) + + expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) + }) + + it('fades the host error screen out the same way when content replaces it', () => { + const renderer = render(placeholderBlock({ error: broken })) + + reportAppearance(renderer, 'error') + reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) + + expect(renderer.root.findByType(asType(Text)).props.children).toBe('broken') + expect(overlayHost(renderer).props.pointerEvents).toBe('none') + + tick(250) + + expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) + }) + + it('takes the placeholder away at once when the content is not a reveal', () => { + const renderer = render(placeholderBlock({ placeholder: loading })) + + reportAppearance(renderer, 'content') + + expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) + }) + + it('takes a fading overlay away at once when the look changes again', () => { + const renderer = render(placeholderBlock({ placeholder: loading })) + + reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) + tick(125) + reportAppearance(renderer, 'collapsed') + + expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) + + tick(250) + + expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) + }) + + it('shows the placeholder again, opaque and touchable, when a reload follows the reveal', () => { + const renderer = render(placeholderBlock({ placeholder: loading })) + + reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) + tick(250) + reportAppearance(renderer, 'placeholder') + + expect(renderer.root.findByType(asType(Text)).props.children).toBe('loading') + expect(overlayHost(renderer).props.pointerEvents).toBe('box-none') + expect(overlayOpacity(renderer)).toBeUndefined() + }) + }) + }) +}) + +describe('MindboxEmbeddedBlockFailReason', () => { + it('names the reasons by the raw values the native blocks report', () => { + expect(MindboxEmbeddedBlockFailReason.networkError).toBe('networkError') + expect(MindboxEmbeddedBlockFailReason.internalError).toBe('internalError') + }) + + it('is a string, so a word a later SDK adds is still a reason', () => { + const reason: MindboxEmbeddedBlockFailReason = 'quotaExceeded' + + expect(reason).toBe('quotaExceeded') }) }) diff --git a/src/__tests__/MindboxEmbeddedBlock.unsupported.test.tsx b/src/__tests__/MindboxEmbeddedBlock.unsupported.test.tsx new file mode 100644 index 0000000..6f9a2ae --- /dev/null +++ b/src/__tests__/MindboxEmbeddedBlock.unsupported.test.tsx @@ -0,0 +1,54 @@ +import React from 'react' +import { StyleSheet, View } from 'react-native' +import { act, create } from 'react-test-renderer' +import type { ReactTestRenderer } from 'react-test-renderer' + +/** + * A platform without the native block — anything but iOS and Android. `Platform.OS` is read when + * the component module loads, so the platform is set before the component is required, in a test + * file of its own. + */ +jest.mock('react-native/Libraries/Utilities/Platform', () => ({ + OS: 'web', + select: (specifics: Record) => specifics.default, +})) + +jest.mock('../MindboxEmbeddedBlockNativeComponent', () => { + const ReactActual = require('react') + const { View: RNView } = require('react-native') + return { + __esModule: true, + default: (props: unknown) => ReactActual.createElement(RNView, { ...(props as object), testID: 'native-block' }), + } +}) + +const { MindboxEmbeddedBlock } = require('../MindboxEmbeddedBlock') + +const render = (element: React.ReactElement): ReactTestRenderer => { + let renderer: ReactTestRenderer + act(() => { + renderer = create(element as any) + }) + return renderer! +} + +const frameHeight = (renderer: ReactTestRenderer) => { + const frame = renderer.root.findAllByType(View as any)[0] + return StyleSheet.flatten(frame.props.style).height +} + +describe('MindboxEmbeddedBlock on a platform without the native block', () => { + it('takes no space, builds no native view and reports an internal error', () => { + const onLoad = jest.fn() + const onEmpty = jest.fn() + const onFail = jest.fn() + const renderer = render() + + expect(frameHeight(renderer)).toBe(0) + expect(renderer.root.findAllByProps({ testID: 'native-block' })).toHaveLength(0) + expect(onFail).toHaveBeenCalledTimes(1) + expect(onFail).toHaveBeenCalledWith('internalError') + expect(onLoad).not.toHaveBeenCalled() + expect(onEmpty).not.toHaveBeenCalled() + }) +}) diff --git a/src/index.tsx b/src/index.tsx index 68868bc..422afce 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -496,4 +496,8 @@ export { InAppCallback, CopyPayloadInAppCallback, EmptyInAppCallback, UrlInAppCa export { MindboxEmbeddedBlock } from './MindboxEmbeddedBlock' -export type { MindboxEmbeddedBlockProps, MindboxEmbeddedBlockFailure } from './MindboxEmbeddedBlock' +export type { MindboxEmbeddedBlockProps } from './MindboxEmbeddedBlock' + +export { MindboxEmbeddedBlockFailReason } from './MindboxEmbeddedBlockFailReason' + +export { MindboxEmbeddedBlockLoadingStrategy } from './MindboxEmbeddedBlockLoadingStrategy' From 50364749f68954f2decb93759bbbe4c008a2ac99 Mon Sep 17 00:00:00 2001 From: Egor Kitselyuk Date: Thu, 8 Oct 2026 16:45:53 +0300 Subject: [PATCH 06/16] MOBILE-389: Add disableTrackingIds support --- .../java/com/mindboxsdk/MindboxSdkModule.kt | 3 ++ src/__tests__/index.test.ts | 48 +++++++++++++++++++ src/index.tsx | 7 ++- src/types/InitializationData.ts | 11 +++++ 4 files changed, 68 insertions(+), 1 deletion(-) diff --git a/android/src/main/java/com/mindboxsdk/MindboxSdkModule.kt b/android/src/main/java/com/mindboxsdk/MindboxSdkModule.kt index 5797f5d..aada3c7 100644 --- a/android/src/main/java/com/mindboxsdk/MindboxSdkModule.kt +++ b/android/src/main/java/com/mindboxsdk/MindboxSdkModule.kt @@ -65,6 +65,9 @@ class MindboxSdkModule(private val reactContext: ReactApplicationContext) : Reac if (payload.has("shouldIncludeVersionCode")) { configurationBuilder.shouldIncludeVersionCode(payload.optBoolean("shouldIncludeVersionCode", true)) } + if (payload.has("disableTrackingIds")) { + configurationBuilder.disableTrackingIds(payload.optBoolean("disableTrackingIds", false)) + } val configuration = configurationBuilder.build() val handler = Handler(context.mainLooper) diff --git a/src/__tests__/index.test.ts b/src/__tests__/index.test.ts index 9c1a85a..11299be 100644 --- a/src/__tests__/index.test.ts +++ b/src/__tests__/index.test.ts @@ -545,6 +545,54 @@ describe('Testing Mindbox RN SDK', () => { expect(JSON.parse(calledWith)).not.toHaveProperty('shouldIncludeVersionCode') }) + it('initialize passes disableTrackingIds true to native', async () => { + const { + NativeModules: { MindboxSdk: MindboxSdkNative }, + } = require('react-native') + const MindboxSdk = require('../index').default + + expect.assertions(1) + + await MindboxSdk.initialize({ + ...initializationData, + disableTrackingIds: true, + }) + + const calledWith = (MindboxSdkNative.initialize as jest.Mock).mock.calls.slice(-1)[0][0] + expect(JSON.parse(calledWith)).toMatchObject({ disableTrackingIds: true }) + }) + + it('initialize passes disableTrackingIds false to native', async () => { + const { + NativeModules: { MindboxSdk: MindboxSdkNative }, + } = require('react-native') + const MindboxSdk = require('../index').default + + expect.assertions(1) + + await MindboxSdk.initialize({ + ...initializationData, + disableTrackingIds: false, + }) + + const calledWith = (MindboxSdkNative.initialize as jest.Mock).mock.calls.slice(-1)[0][0] + expect(JSON.parse(calledWith)).toMatchObject({ disableTrackingIds: false }) + }) + + it('initialize does not include disableTrackingIds in payload when not provided', async () => { + const { + NativeModules: { MindboxSdk: MindboxSdkNative }, + } = require('react-native') + const MindboxSdk = require('../index').default + + expect.assertions(1) + + await MindboxSdk.initialize(initializationData) + + const calledWith = (MindboxSdkNative.initialize as jest.Mock).mock.calls.slice(-1)[0][0] + expect(JSON.parse(calledWith)).not.toHaveProperty('disableTrackingIds') + }) + it('getDeviceUUID method works correctly', async () => { const MindboxSdk = require('../index').default diff --git a/src/index.tsx b/src/index.tsx index c2c8273..827f65f 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -84,6 +84,7 @@ class MindboxSdkClass { * previousUuid: '', * operationsDomain: 'anonymizer.example.com', * shouldIncludeVersionCode: false, // Android only (ignored on iOS). Default value is true + * disableTrackingIds: true, // Android only (ignored on iOS). Default value is false * }); */ public async initialize(initializationData: InitializationData) { @@ -99,7 +100,7 @@ class MindboxSdkClass { throw new Error('Wrong initialization data!') } - const { domain, endpointId, subscribeCustomerIfCreated, shouldCreateCustomer, previousInstallId, previousUuid, operationsDomain, shouldIncludeVersionCode } = initializationData + const { domain, endpointId, subscribeCustomerIfCreated, shouldCreateCustomer, previousInstallId, previousUuid, operationsDomain, shouldIncludeVersionCode, disableTrackingIds } = initializationData if (!domain || !endpointId) { this._initializing = false @@ -135,6 +136,10 @@ class MindboxSdkClass { payload.shouldIncludeVersionCode = shouldIncludeVersionCode } + if (typeof disableTrackingIds !== 'undefined') { + payload.disableTrackingIds = disableTrackingIds + } + try { const payloadString = JSON.stringify(payload) this._initialized = await MindboxSdkNative.initialize(payloadString) diff --git a/src/types/InitializationData.ts b/src/types/InitializationData.ts index 46789ac..3d79155 100644 --- a/src/types/InitializationData.ts +++ b/src/types/InitializationData.ts @@ -12,4 +12,15 @@ export type InitializationData = { * Default value is true. */ shouldIncludeVersionCode?: boolean + /** + * Android only, ignored on iOS. Turns off collection of the device tracking identifier + * (GAID from Google Mobile Services, OAID from Huawei Mobile Services) that the SDK otherwise + * reports to Mindbox together with the application events. Pass true to stop the collection. + * This is the only supported way to opt out: removing the AD_ID permission affects the whole app + * and does not stop OAID collection. The SDK never requests a runtime permission for it, and + * RuStore provides no tracking identifier. The value is applied on every initialization, so it + * can be turned on or off in a later app version. + * Default value is false (the identifier is collected). + */ + disableTrackingIds?: boolean } From f1621a737529d4bd3650d3df1fd7ea97264fca5d Mon Sep 17 00:00:00 2001 From: Egor Kitselyuk Date: Thu, 8 Oct 2026 16:48:03 +0300 Subject: [PATCH 07/16] MOBILE-389: Document when disableTrackingIds takes effect --- src/types/InitializationData.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/types/InitializationData.ts b/src/types/InitializationData.ts index 3d79155..f6f83c0 100644 --- a/src/types/InitializationData.ts +++ b/src/types/InitializationData.ts @@ -19,7 +19,9 @@ export type InitializationData = { * This is the only supported way to opt out: removing the AD_ID permission affects the whole app * and does not stop OAID collection. The SDK never requests a runtime permission for it, and * RuStore provides no tracking identifier. The value is applied on every initialization, so it - * can be turned on or off in a later app version. + * can be turned on or off in a later app version. A changed value takes effect once initialize + * has run in that version; native work started earlier (push services set up at app start, + * background token refresh) still uses the previous value. * Default value is false (the identifier is collected). */ disableTrackingIds?: boolean From aeef73b529f61ff79e86962170279c1db5d023da Mon Sep 17 00:00:00 2001 From: Sergey Sozinov <103035673+sergeysozinov@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:43:25 +0300 Subject: [PATCH 08/16] MOBILE-588: Let the embedded block's props reach the native view on Android (#227) --- .../MindboxEmbeddedBlockViewManager.kt | 9 ++ ...dboxEmbeddedBlockViewManager.props.test.ts | 113 ++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 src/__tests__/MindboxEmbeddedBlockViewManager.props.test.ts diff --git a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt index 45db945..90a3884 100644 --- a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt @@ -6,6 +6,7 @@ import com.facebook.react.uimanager.SimpleViewManager import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.UIManagerHelper import com.facebook.react.uimanager.ViewManagerDelegate +import com.facebook.react.uimanager.annotations.ReactProp import com.facebook.react.uimanager.events.Event import com.facebook.react.viewmanagers.MindboxEmbeddedBlockViewManagerDelegate import com.facebook.react.viewmanagers.MindboxEmbeddedBlockViewManagerInterface @@ -48,32 +49,40 @@ internal class MindboxEmbeddedBlockViewManager : view: MindboxEmbeddedBlockHostView, ): MindboxEmbeddedBlockHostView? = null + @ReactProp(name = "placeSystemName") override fun setPlaceSystemName(view: MindboxEmbeddedBlockHostView, value: String?) { view.setPlaceSystemName(value) } + @ReactProp(name = "blockHeight", defaultDouble = 0.0) override fun setBlockHeight(view: MindboxEmbeddedBlockHostView, value: Double) = Unit + @ReactProp(name = "timeoutMs", defaultDouble = 0.0) override fun setTimeoutMs(view: MindboxEmbeddedBlockHostView, value: Double) { view.setTimeoutMs(value) } + @ReactProp(name = "loadingStrategy") override fun setLoadingStrategy(view: MindboxEmbeddedBlockHostView, value: String?) { view.setLoadingStrategy(value) } + @ReactProp(name = "animatesReveal", defaultBoolean = true) override fun setAnimatesReveal(view: MindboxEmbeddedBlockHostView, value: Boolean) { view.setAnimatesReveal(value) } + @ReactProp(name = "hasPlaceholder", defaultBoolean = false) override fun setHasPlaceholder(view: MindboxEmbeddedBlockHostView, value: Boolean) { view.setHasPlaceholder(value) } + @ReactProp(name = "hasErrorView", defaultBoolean = false) override fun setHasErrorView(view: MindboxEmbeddedBlockHostView, value: Boolean) { view.setHasErrorView(value) } + @ReactProp(name = "hostVisible", defaultBoolean = true) override fun setHostVisible(view: MindboxEmbeddedBlockHostView, value: Boolean) { view.setHostVisible(value) } diff --git a/src/__tests__/MindboxEmbeddedBlockViewManager.props.test.ts b/src/__tests__/MindboxEmbeddedBlockViewManager.props.test.ts new file mode 100644 index 0000000..271b0b5 --- /dev/null +++ b/src/__tests__/MindboxEmbeddedBlockViewManager.props.test.ts @@ -0,0 +1,113 @@ +import { readFileSync } from 'fs' +import { join } from 'path' + +type PropKind = 'boolean' | 'number' | 'string' + +type SpecProp = { + name: string + kind: PropKind + defaultValue: boolean | number | undefined +} + +type ReactPropAnnotation = { + name: string + setter: string + defaultBoolean: boolean + defaultDouble: number +} + +const NUMBER_TYPES = ['Double', 'Float', 'Int32'] + +const readSource = (...segments: string[]) => readFileSync(join(__dirname, '..', '..', ...segments), 'utf8') + +const kindOf = (type: string): PropKind => { + if (type === 'boolean') { + return 'boolean' + } + return NUMBER_TYPES.includes(type) ? 'number' : 'string' +} + +const literalOf = (literal: string): boolean | number | undefined => { + if (literal === 'true' || literal === 'false') { + return literal === 'true' + } + const number = Number(literal) + return Number.isNaN(number) ? undefined : number +} + +const toSpecProp = (name: string, type: string): SpecProp => { + const withDefault = /^WithDefault<\s*(\w+)\s*,\s*(.+?)\s*>$/.exec(type) + const kind = kindOf(withDefault ? withDefault[1] : type) + if (withDefault) { + return { name, kind, defaultValue: literalOf(withDefault[2]) } + } + const implicitDefaults: Record = { boolean: false, number: 0, string: undefined } + return { name, kind, defaultValue: implicitDefaults[kind] } +} + +const parseSpecProps = (source: string): SpecProp[] => { + const body = /interface NativeProps extends ViewProps \{([\s\S]*?)\n\}/.exec(source)?.[1] ?? '' + const declarations = body.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '') + return Array.from(declarations.matchAll(/^\s*(\w+)\?:\s*(.+?)\s*$/gm)) + .filter(([, , type]) => !type.includes('EventHandler<')) + .map(([, name, type]) => toSpecProp(name, type)) +} + +const parseAnnotations = (source: string): ReactPropAnnotation[] => + Array.from(source.matchAll(/@ReactProp\(([^)]*)\)\s*override fun (\w+)\(/g)).map(([, args, setter]) => { + const argument = (key: string) => new RegExp(`${key}\\s*=\\s*"?([^",\\s)]+)`).exec(args)?.[1] + return { + name: argument('name') ?? '', + setter, + defaultBoolean: argument('defaultBoolean') === 'true', + defaultDouble: Number(argument('defaultDouble') ?? 0), + } + }) + +const setterOf = (prop: string) => `set${prop[0].toUpperCase()}${prop.slice(1)}` + +const specSource = readSource('src', 'MindboxEmbeddedBlockNativeComponent.ts') +const viewManagerSource = readSource('android', 'src', 'main', 'java', 'com', 'mindboxsdk', 'embedded', 'MindboxEmbeddedBlockViewManager.kt') + +const specProps = parseSpecProps(specSource) +const annotations = parseAnnotations(viewManagerSource) + +describe('MindboxEmbeddedBlockViewManager props on Android without bridgeless', () => { + it('reads the props of the codegen spec, leaving the events out', () => { + const names = specProps.map((prop) => prop.name) + + expect(names).toContain('placeSystemName') + expect(names).not.toContain('onBlockOutcome') + }) + + it('puts @ReactProp on the setter of every prop of the spec', () => { + const missing = specProps.filter((prop) => !annotations.some((annotation) => annotation.name === prop.name && annotation.setter === setterOf(prop.name))) + + expect(missing.map((prop) => prop.name)).toEqual([]) + }) + + it('gives every @ReactProp the default of the spec', () => { + const mismatched = specProps.flatMap((prop) => { + const annotation = annotations.find((candidate) => candidate.name === prop.name) + if (!annotation || prop.kind === 'string') { + return [] + } + const actual = prop.kind === 'boolean' ? annotation.defaultBoolean : annotation.defaultDouble + return actual === prop.defaultValue ? [] : [`${prop.name}: @ReactProp default ${actual}, spec default ${prop.defaultValue}`] + }) + + expect(mismatched).toEqual([]) + }) + + it('puts @ReactProp on no prop the spec does not have', () => { + const unknown = annotations.filter((annotation) => !specProps.some((prop) => prop.name === annotation.name)) + + expect(unknown.map((annotation) => annotation.name)).toEqual([]) + }) + + it('puts every @ReactProp right on an overriding setter', () => { + const annotationCount = (viewManagerSource.match(/@ReactProp\(/g) ?? []).length + + expect(annotations).toHaveLength(annotationCount) + }) +}) From ac0e4e1ce7ae660b24eef420dc4c0b7f1d39268b Mon Sep 17 00:00:00 2001 From: Sergei Semko <28645140+justSmK@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:14:24 +0300 Subject: [PATCH 09/16] fix: Take the GitLab host from a secret and fail on a non-201 trigger (#228) GitLab moved to a new host, and the old one now redirects the trigger API to its sign-in page. curl --location followed the redirect and the script counted the resulting 200 as success, so a manual distribute run went green without creating any pipeline. The trigger API answers 201 on success, so anything else now fails. The host comes from the GITLAB_HOST secret, which keeps it out of the public logs and lets the next move happen without a code change. --- .github/workflows/distribute-develop-mission.yml | 1 + .github/workflows/distribute-manual.yml | 1 + .../distribute-release-support-mission.yml | 1 + .github/workflows/distribute-reusable.yml | 13 ++++++++++--- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/distribute-develop-mission.yml b/.github/workflows/distribute-develop-mission.yml index 1ada48d..2df774a 100644 --- a/.github/workflows/distribute-develop-mission.yml +++ b/.github/workflows/distribute-develop-mission.yml @@ -19,3 +19,4 @@ jobs: branch: ${{ github.base_ref }} secrets: GITLAB_TRIGGER_TOKEN: ${{ secrets.GITLAB_TRIGGER_TOKEN }} + GITLAB_HOST: ${{ secrets.GITLAB_HOST }} diff --git a/.github/workflows/distribute-manual.yml b/.github/workflows/distribute-manual.yml index fa435d4..5aaa5ac 100644 --- a/.github/workflows/distribute-manual.yml +++ b/.github/workflows/distribute-manual.yml @@ -19,3 +19,4 @@ jobs: app_ref: ${{ inputs.app_ref }} # optional override for GitLab ref secrets: GITLAB_TRIGGER_TOKEN: ${{ secrets.GITLAB_TRIGGER_TOKEN }} + GITLAB_HOST: ${{ secrets.GITLAB_HOST }} diff --git a/.github/workflows/distribute-release-support-mission.yml b/.github/workflows/distribute-release-support-mission.yml index 0c22fc8..8d45c2c 100644 --- a/.github/workflows/distribute-release-support-mission.yml +++ b/.github/workflows/distribute-release-support-mission.yml @@ -21,3 +21,4 @@ jobs: branch: ${{ github.event.pull_request.head.ref }} secrets: GITLAB_TRIGGER_TOKEN: ${{ secrets.GITLAB_TRIGGER_TOKEN }} + GITLAB_HOST: ${{ secrets.GITLAB_HOST }} diff --git a/.github/workflows/distribute-reusable.yml b/.github/workflows/distribute-reusable.yml index 0783d8d..87b2b5c 100644 --- a/.github/workflows/distribute-reusable.yml +++ b/.github/workflows/distribute-reusable.yml @@ -13,6 +13,8 @@ on: secrets: GITLAB_TRIGGER_TOKEN: required: true + GITLAB_HOST: + required: true permissions: contents: read @@ -65,7 +67,7 @@ jobs: - name: Trigger build workflow in react-native-app repo (override strict; else same->develop) shell: bash env: - GITLAB_HOST: mindbox.gitlab.yandexcloud.net + GITLAB_HOST: ${{ secrets.GITLAB_HOST }} APP_PROJECT_ID: "1512" DEFAULT_APP_REF: develop @@ -77,6 +79,11 @@ jobs: run: | set -euo pipefail + if [[ -z "${GITLAB_HOST:-}" ]]; then + echo "::error::Secret GITLAB_HOST is empty: set it to the GitLab host name, without https://" + exit 1 + fi + # Trim override so " " becomes empty APP_REF_OVERRIDE="$(printf '%s' "${APP_REF_OVERRIDE:-}" | xargs)" @@ -108,7 +115,7 @@ jobs: tmp_body="$(mktemp)" local code - code="$(curl -sS -o "$tmp_body" -w '%{http_code}' --location \ + code="$(curl -sS -o "$tmp_body" -w '%{http_code}' \ --retry 3 --retry-all-errors --retry-delay 2 \ "https://${GITLAB_HOST}/api/v4/projects/${APP_PROJECT_ID}/trigger/pipeline" \ --form "token=${GITLAB_TRIGGER_TOKEN}" \ @@ -124,7 +131,7 @@ jobs: echo "Response body:" echo "$body" - if [[ "$code" == "200" || "$code" == "201" ]]; then + if [[ "$code" == "201" ]]; then local web_url web_url="$( printf '%s\n' "$body" | From a5e494a90187614e66cb6a72df6a77db95b46da4 Mon Sep 17 00:00:00 2001 From: Sergei Semko <28645140+justSmK@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:14:31 +0300 Subject: [PATCH 10/16] fix: Take the GitLab host from a secret and fail on a non-201 trigger (#229) GitLab moved to a new host, and the old one now redirects the trigger API to its sign-in page. curl --location followed the redirect and the script counted the resulting 200 as success, so a manual distribute run went green without creating any pipeline. The trigger API answers 201 on success, so anything else now fails. The host comes from the GITLAB_HOST secret, which keeps it out of the public logs and lets the next move happen without a code change. --- .github/workflows/distribute-develop-mission.yml | 1 + .github/workflows/distribute-manual.yml | 1 + .../distribute-release-support-mission.yml | 1 + .github/workflows/distribute-reusable.yml | 13 ++++++++++--- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/distribute-develop-mission.yml b/.github/workflows/distribute-develop-mission.yml index 1ada48d..2df774a 100644 --- a/.github/workflows/distribute-develop-mission.yml +++ b/.github/workflows/distribute-develop-mission.yml @@ -19,3 +19,4 @@ jobs: branch: ${{ github.base_ref }} secrets: GITLAB_TRIGGER_TOKEN: ${{ secrets.GITLAB_TRIGGER_TOKEN }} + GITLAB_HOST: ${{ secrets.GITLAB_HOST }} diff --git a/.github/workflows/distribute-manual.yml b/.github/workflows/distribute-manual.yml index fa435d4..5aaa5ac 100644 --- a/.github/workflows/distribute-manual.yml +++ b/.github/workflows/distribute-manual.yml @@ -19,3 +19,4 @@ jobs: app_ref: ${{ inputs.app_ref }} # optional override for GitLab ref secrets: GITLAB_TRIGGER_TOKEN: ${{ secrets.GITLAB_TRIGGER_TOKEN }} + GITLAB_HOST: ${{ secrets.GITLAB_HOST }} diff --git a/.github/workflows/distribute-release-support-mission.yml b/.github/workflows/distribute-release-support-mission.yml index 0c22fc8..8d45c2c 100644 --- a/.github/workflows/distribute-release-support-mission.yml +++ b/.github/workflows/distribute-release-support-mission.yml @@ -21,3 +21,4 @@ jobs: branch: ${{ github.event.pull_request.head.ref }} secrets: GITLAB_TRIGGER_TOKEN: ${{ secrets.GITLAB_TRIGGER_TOKEN }} + GITLAB_HOST: ${{ secrets.GITLAB_HOST }} diff --git a/.github/workflows/distribute-reusable.yml b/.github/workflows/distribute-reusable.yml index 0783d8d..87b2b5c 100644 --- a/.github/workflows/distribute-reusable.yml +++ b/.github/workflows/distribute-reusable.yml @@ -13,6 +13,8 @@ on: secrets: GITLAB_TRIGGER_TOKEN: required: true + GITLAB_HOST: + required: true permissions: contents: read @@ -65,7 +67,7 @@ jobs: - name: Trigger build workflow in react-native-app repo (override strict; else same->develop) shell: bash env: - GITLAB_HOST: mindbox.gitlab.yandexcloud.net + GITLAB_HOST: ${{ secrets.GITLAB_HOST }} APP_PROJECT_ID: "1512" DEFAULT_APP_REF: develop @@ -77,6 +79,11 @@ jobs: run: | set -euo pipefail + if [[ -z "${GITLAB_HOST:-}" ]]; then + echo "::error::Secret GITLAB_HOST is empty: set it to the GitLab host name, without https://" + exit 1 + fi + # Trim override so " " becomes empty APP_REF_OVERRIDE="$(printf '%s' "${APP_REF_OVERRIDE:-}" | xargs)" @@ -108,7 +115,7 @@ jobs: tmp_body="$(mktemp)" local code - code="$(curl -sS -o "$tmp_body" -w '%{http_code}' --location \ + code="$(curl -sS -o "$tmp_body" -w '%{http_code}' \ --retry 3 --retry-all-errors --retry-delay 2 \ "https://${GITLAB_HOST}/api/v4/projects/${APP_PROJECT_ID}/trigger/pipeline" \ --form "token=${GITLAB_TRIGGER_TOKEN}" \ @@ -124,7 +131,7 @@ jobs: echo "Response body:" echo "$body" - if [[ "$code" == "200" || "$code" == "201" ]]; then + if [[ "$code" == "201" ]]; then local web_url web_url="$( printf '%s\n' "$body" | From 2e8000abfcc0ee43b6aea4ee4c7256fd68cc959a Mon Sep 17 00:00:00 2001 From: Sergei Semko <28645140+justSmK@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:49:44 +0300 Subject: [PATCH 11/16] MOBILE-0000: Drop comments from the embedded block code (#230) Only comments change. The tests' layout helpers and one test name now say what their comments did. --- MindboxSdk.podspec | 9 +-- .../mindboxsdk/embedded/EmbeddedBlockWire.kt | 5 -- .../embedded/MindboxEmbeddedBlockEvents.kt | 15 +--- .../embedded/MindboxEmbeddedBlockHostView.kt | 12 +-- ios/EmbeddedBlock/EmbeddedBlockWire.swift | 4 - .../MindboxEmbeddedBlockHost.swift | 21 +----- ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm | 45 +---------- src/MindboxEmbeddedBlock.tsx | 74 +------------------ src/MindboxEmbeddedBlockNativeComponent.ts | 11 --- src/__tests__/MindboxEmbeddedBlock.test.tsx | 68 ++++++++--------- .../MindboxEmbeddedBlock.unsupported.test.tsx | 10 +-- src/react-native-children.d.ts | 15 +--- src/react-native-codegen.d.ts | 25 +------ 13 files changed, 47 insertions(+), 267 deletions(-) diff --git a/MindboxSdk.podspec b/MindboxSdk.podspec index 0da7d1b..263433f 100644 --- a/MindboxSdk.podspec +++ b/MindboxSdk.podspec @@ -18,14 +18,7 @@ Pod::Spec.new do |s| s.dependency "Mindbox", "2.16.0-rc" s.dependency "MindboxNotifications", "2.16.0-rc" - # The embedded block is a native component, and on the new renderer that means a Fabric component: - # this brings in the renderer's own pods and, the part that decides everything, defines - # `RCT_NEW_ARCH_ENABLED` for our sources — what `MindboxEmbeddedBlockView.mm` splits on. React - # Native defines it for a library's own pod only through this call and nowhere else, so without it - # the file compiles its old-renderer half even on a React Native that no longer has one. - # - # On the old renderer the same call settles for React-Core and leaves the flag undefined, which is - # how the other half of that file gets compiled instead. + # Only this call defines RCT_NEW_ARCH_ENABLED for the pod, which MindboxEmbeddedBlockView.mm splits on. if respond_to?(:install_modules_dependencies, true) install_modules_dependencies(s) else diff --git a/android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt b/android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt index 954941b..6a1be4a 100644 --- a/android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt +++ b/android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt @@ -4,17 +4,12 @@ import cloud.mindbox.mobile_sdk.annotations.InternalMindboxApi import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockAppearance import cloud.mindbox.mobile_sdk.embedded.MindboxEmbeddedBlockLoadingStrategy -/** - * The words the block speaks to JS in: the same ones on iOS, the same ones the Flutter plugin - * uses. A contract with the JS side, not derived from anything. - */ @OptIn(InternalMindboxApi::class) internal object EmbeddedBlockWire { const val OUTCOME_LOAD = "load" const val OUTCOME_EMPTY = "empty" const val OUTCOME_FAIL = "fail" - /** `null` for a word this SDK does not know; an empty word is the default, `automatic`. */ fun loadingStrategyOf(word: String?): MindboxEmbeddedBlockLoadingStrategy? = when (word) { null, "", "automatic" -> MindboxEmbeddedBlockLoadingStrategy.AUTOMATIC "placeholder" -> MindboxEmbeddedBlockLoadingStrategy.PLACEHOLDER diff --git a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt index 53f41bd..9a5927f 100644 --- a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt @@ -4,11 +4,6 @@ import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap import com.facebook.react.uimanager.events.Event -/** - * The look the native block shows. `animated` is `true` for the one change that is the SDK's - * reveal of content — the block owns that decision, gates included — and `revealDurationMs` is - * how long it takes; `false` and `0` for every other change. - */ internal class AppearanceChangeEvent( surfaceId: Int, viewTag: Int, @@ -18,9 +13,7 @@ internal class AppearanceChangeEvent( ) : Event(surfaceId, viewTag) { override fun getEventName(): String = EVENT_NAME - // React Native coalesces same-named events of one view that are still queued when a frame is - // dispatched, keeping the last. The JS side reads every change — a reveal is content arriving - // where a placeholder or nothing stood — so none may be folded into the next. + // React Native keeps only the last queued event of a name per view; JS needs every look change. override fun canCoalesce(): Boolean = false override fun getEventData(): WritableMap = Arguments.createMap().apply { @@ -34,10 +27,6 @@ internal class AppearanceChangeEvent( } } -/** - * How the load ended: `load`, `empty` or `fail`, the reason going with a failure. An event payload - * has every field, so a missing reason is spelled as an empty string. - */ internal class BlockOutcomeEvent( surfaceId: Int, viewTag: Int, @@ -46,7 +35,7 @@ internal class BlockOutcomeEvent( ) : Event(surfaceId, viewTag) { override fun getEventName(): String = EVENT_NAME - // Every outcome is promised to the host once it changes; two in one frame must both arrive. + // React Native keeps only the last queued event of a name per view; JS needs every outcome. override fun canCoalesce(): Boolean = false override fun getEventData(): WritableMap = Arguments.createMap().apply { diff --git a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt index 48fc5b5..1644d40 100644 --- a/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt @@ -18,17 +18,14 @@ import cloud.mindbox.mobile_sdk.logger.Level @OptIn(InternalMindboxApi::class) internal class MindboxEmbeddedBlockHostView(context: Context) : FrameLayout(context) { - /** The appearance word, whether this change is the SDK's animated reveal, and how long it takes. */ var onAppearance: ((appearance: String, isRevealAnimated: Boolean, revealDurationMs: Int) -> Unit)? = null - /** The outcome word and, for a failure, the reason's raw value. */ var onOutcome: ((outcome: String, reason: String?) -> Unit)? = null private var blockView: MindboxEmbeddedBlockView? = null private var placeSystemName: String? = null private var timeoutMs: Long? = null private var loadingStrategy: MindboxEmbeddedBlockLoadingStrategy = MindboxEmbeddedBlockLoadingStrategy.AUTOMATIC - /** A strategy word this SDK did not know, kept to be logged once the block is built and the place is known. */ private var unknownLoadingStrategyWord: String? = null private var animatesReveal: Boolean = true private var hostVisible: Boolean = true @@ -90,10 +87,7 @@ internal class MindboxEmbeddedBlockHostView(context: Context) : FrameLayout(cont } } - // Fixed at creation, as the timeout is: the JS side warns the host about a later value rather - // than applying it, and the native block takes both only through its constructor. A word this - // SDK does not know is read as `automatic` and logged when the block is built — Fabric sets the - // props in no fixed order, and here the place name may not have arrived yet. + // An unknown word is logged once the block is built: Fabric sets props in no fixed order. fun setLoadingStrategy(word: String?) { if (blockView != null) { return @@ -192,10 +186,6 @@ internal class MindboxEmbeddedBlockHostView(context: Context) : FrameLayout(cont } }, ) - // `isRevealAnimated` is read while the observer runs: the block sets it right before it - // calls, for that one call. The block owns the gates — `animatesReveal`, a window to animate - // in, animations enabled on the device, "only the arrival of content" — and this host only - // passes its word on; the growth of a block that waited hidden is then the JS side's. block.setAppearanceObserver { appearance -> onAppearance?.invoke( EmbeddedBlockWire.nameOf(appearance), diff --git a/ios/EmbeddedBlock/EmbeddedBlockWire.swift b/ios/EmbeddedBlock/EmbeddedBlockWire.swift index 6f4fe58..c4a2426 100644 --- a/ios/EmbeddedBlock/EmbeddedBlockWire.swift +++ b/ios/EmbeddedBlock/EmbeddedBlockWire.swift @@ -1,13 +1,10 @@ @_spi(Internal) import Mindbox -/// The words the block speaks to JS in: the same ones on Android, the same ones the Flutter plugin -/// uses. A contract with the JS side, not derived from anything. enum EmbeddedBlockWire { static let outcomeLoad = "load" static let outcomeEmpty = "empty" static let outcomeFail = "fail" - /// `nil` for a word this SDK does not know; an empty word is the default, `automatic`. static func loadingStrategy(of word: String?) -> MindboxEmbeddedBlockLoadingStrategy? { switch word { case nil, "", "automatic": return .automatic @@ -26,7 +23,6 @@ enum EmbeddedBlockWire { } } - /// The SDK's reveal, in whole milliseconds — what JS animates the growth of a hidden block over. static var revealDurationMs: Int { Int((MindboxEmbeddedBlockView.revealAnimationDuration * 1000).rounded()) } diff --git a/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift b/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift index dc3bd71..a912330 100644 --- a/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift +++ b/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift @@ -4,12 +4,8 @@ import MindboxLogger @objc(MindboxEmbeddedBlockHost) public final class MindboxEmbeddedBlockHost: NSObject { - /// The appearance word, whether this change is the SDK's animated reveal, and how long it takes. - /// Given at creation and never replaced: the block reports its first look the moment it is - /// observed, and a callback wired afterwards would miss it. private let onAppearance: (NSString, Bool, Int) -> Void - /// The outcome word and, for a failure, the reason's raw value. private let onOutcome: (NSString, NSString?) -> Void @objc public var view: UIView { blockView } @@ -17,14 +13,6 @@ public final class MindboxEmbeddedBlockHost: NSObject { private let blockView: MindboxEmbeddedBlockView private var isTornDown = false - /// `loadingStrategy` is a word — `automatic`, `placeholder` or `hidden`; a word this SDK does not - /// know is logged and read as `automatic`. Both it and `animatesReveal` are fixed here, as the - /// native block takes them only through its initializer. - /// - /// The callbacks are taken here too, not assigned later: subscribing to the block hands out its - /// current look at once — for an `automatic` block, the place's memory — and that first report - /// is the one JS has no other way to learn. Android wires its emitters before the block exists - /// for the same reason. @objc public init(placeSystemName: String, height: CGFloat, timeoutMs: Double, @@ -55,12 +43,7 @@ public final class MindboxEmbeddedBlockHost: NSObject { } blockView.delegate = self - // `isRevealAnimated` is read while the observer runs: the block sets it right before it - // calls, for that one call. The block owns the gates — `animatesReveal`, a window to animate - // in, Reduce Motion off, "only the arrival of content" — and this host only passes its word - // on; the growth of a block that waited hidden is then the JS side's. - // The observer fires synchronously with the current look, so this comes last in `init`, - // with both callbacks already in place. + // Last in init: the observer reports the current look synchronously, and JS learns the first look only from it. blockView.setAppearanceObserver { [weak self] appearance in guard let self, !self.isTornDown else { return } self.onAppearance(EmbeddedBlockWire.name(of: appearance) as NSString, @@ -108,8 +91,6 @@ public final class MindboxEmbeddedBlockHost: NSObject { } } -// All three methods are implemented on purpose: the protocol gives each an empty default, so a -// host that still spelled the old `DidFail(_:)` would compile and silently hear no failure. extension MindboxEmbeddedBlockHost: MindboxEmbeddedBlockViewDelegate { public func mindboxEmbeddedBlockViewDidLoad(_ blockView: MindboxEmbeddedBlockView) { guard !isTornDown else { return } diff --git a/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm b/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm index 0204815..86c8f8c 100644 --- a/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm +++ b/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm @@ -1,11 +1,3 @@ -// The embedded block on iOS, in both renderers. -// -// The block itself lives in `MindboxEmbeddedBlockHost` — plain UIKit, no React in it — and each -// renderer only carries props to it and its two signals back — the look and the outcome. Fabric does that through a component -// view and a C++ event emitter; the old renderer through a view manager and direct event blocks. -// The order of the calls into the host is kept the same in both, so a block behaves the same way -// whichever renderer the host app runs. - #if __has_include("MindboxSdk-Swift.h") #import "MindboxSdk-Swift.h" #elif __has_include() @@ -101,9 +93,7 @@ - (void)finalizeUpdates:(RNComponentViewUpdateMask)updateMask return; } - // The callbacks go into the host's initializer: the block reports its first look the moment the - // host subscribes to it, and the event emitter is already in place here — Fabric sets it before - // `finalizeUpdates:` on every mount — so that first report reaches JS. + // Fabric sets the event emitter before finalizeUpdates:, so the host's first report reaches JS. __weak MindboxEmbeddedBlockViewComponentView *weakSelf = self; _host = [[MindboxEmbeddedBlockHost alloc] initWithPlaceSystemName:@(_placeSystemName.c_str()) @@ -129,9 +119,6 @@ - (void)invalidate _placeSystemName = ""; } -// The emitter is set before the host exists and lives as long as the view does, so the guards -// below state an invariant rather than wait for anything: a report with no emitter has nobody to -// go to and is dropped. - (void)emitAppearance:(NSString *)appearance animated:(BOOL)animated revealDurationMs:(NSInteger)revealDurationMs { if (!_eventEmitter) { @@ -150,7 +137,6 @@ - (void)emitOutcome:(NSString *)outcome reason:(NSString *_Nullable)reason return; } - // The payload has every field: a reason that is not there is an empty string. std::static_pointer_cast(_eventEmitter) ->onBlockOutcome({.outcome = std::string([outcome UTF8String]), .reason = std::string([(reason ?: @"") UTF8String])}); @@ -179,18 +165,7 @@ - (void)dropHost #import #import -/** - * The block's place in the old renderer. - * - * An `RCTView` and not a bare `UIView`: the view manager the block is exported through is an - * `RCTViewManager`, and the standard view props it brings — the border, the shadow, the overflow — - * are written to an `RCTView`. - * - * The host is built once the place has both its props and a size, which is why the attempt is made - * from `didSetProps:` and from `layoutSubviews`: the props of a transaction and the frame of a - * layout pass do not arrive together, and either can be the last of the two. This is what - * `finalizeUpdates:` does for the block under Fabric. - */ +// An RCTView: RCTViewManager writes the standard view props to it. @interface MindboxEmbeddedBlockPaperView : RCTView @property (nonatomic, copy) NSString *placeSystemName; @@ -232,8 +207,6 @@ - (void)didSetProps:(NSArray *)changedProps { [super didSetProps:changedProps]; - // A different name is a different block, built from scratch in place of the old one — the same - // rule the JS side states and the Fabric path follows. if (_host != nil && ![_builtPlaceSystemName isEqualToString:(_placeSystemName ?: @"")]) { [self dropHost]; } @@ -262,15 +235,9 @@ - (void)buildHostIfPossible } _builtPlaceSystemName = _placeSystemName ?: @""; - // Taken once, when the block is created: the container cannot re-budget a running wait, and the - // JS side warns the host about a new value rather than applying it. _builtTimeoutMs = _timeoutMs; - // The strategy and the animation flag are taken once as well: the native block takes them only - // through its initializer. - // The callbacks go into the host's initializer, as under Fabric: the block reports its first - // look the moment the host subscribes to it. The event blocks are props, set before - // `didSetProps:` and before any layout pass, so they are in place whichever of the two builds. + // The event blocks are props, set before didSetProps: and any layout pass, so the host's first report reaches JS. __weak MindboxEmbeddedBlockPaperView *weakSelf = self; _host = [[MindboxEmbeddedBlockHost alloc] initWithPlaceSystemName:_builtPlaceSystemName @@ -291,7 +258,6 @@ - (void)buildHostIfPossible onOutcome:^(NSString *outcome, NSString *_Nullable reason) { MindboxEmbeddedBlockPaperView *strongSelf = weakSelf; if (strongSelf.onBlockOutcome != nil) { - // The same shape as under Fabric: every field present, a missing reason is empty. strongSelf.onBlockOutcome(@{@"outcome" : outcome, @"reason" : reason ?: @""}); } }]; @@ -318,10 +284,7 @@ - (void)dropHost @end -/** - * The exported component. React Native drops the `Manager` suffix when it names the component, so - * this is the `MindboxEmbeddedBlockView` the JS side asks for — the same name Fabric registers. - */ +// React Native drops the Manager suffix: this registers MindboxEmbeddedBlockView, the name Fabric uses. @interface MindboxEmbeddedBlockViewManager : RCTViewManager @end diff --git a/src/MindboxEmbeddedBlock.tsx b/src/MindboxEmbeddedBlock.tsx index ba5b0a5..828f446 100644 --- a/src/MindboxEmbeddedBlock.tsx +++ b/src/MindboxEmbeddedBlock.tsx @@ -7,17 +7,7 @@ import type { NativeProps } from './MindboxEmbeddedBlockNativeComponent' import { MindboxEmbeddedBlockFailReason } from './MindboxEmbeddedBlockFailReason' import { MindboxEmbeddedBlockLoadingStrategy } from './MindboxEmbeddedBlockLoadingStrategy' -/** - * The handlers are typed by the props they are handed to, not by a second spelling of the same - * events. - * - * Spelling them out again would mean naming `NativeSyntheticEvent` here as well, and the two names - * only agree while both resolve to the same React Native. They do not always: a checkout that sits - * under a folder carrying its own React Native resolves this file's import and the spec's to - * different copies, and `bob build` then refuses to write the definitions over a `currentTarget` - * that is a number on one side and a view on the other. Taking the type from the prop leaves - * nothing to disagree about. - */ +// Typed from the spec's props: a second `NativeSyntheticEvent` import breaks `bob build` when two React Native copies resolve. type AppearanceChangeHandler = NonNullable type BlockOutcomeHandler = NonNullable @@ -25,21 +15,14 @@ type Appearance = 'placeholder' | 'content' | 'error' | 'collapsed' const APPEARANCES: Array = ['placeholder', 'content', 'error', 'collapsed'] -/** How the load ended — the three words the native blocks report, the same on both platforms. */ type Outcome = 'load' | 'empty' | 'fail' const OUTCOMES: Array = ['load', 'empty', 'fail'] -/** iOS and Android have the native block; nothing else does. */ const IS_SUPPORTED = Platform.OS === 'ios' || Platform.OS === 'android' -/** A host overlay drawn above the native block: the host's placeholder or its error screen. */ type Overlay = 'placeholder' | 'error' -/** - * The curve of the SDK's reveal on each platform, so the slot and the overlay move with the native - * fade: Material's standard curve on Android, ease-in-out on iOS. - */ const REVEAL_EASING = Platform.OS === 'android' ? Easing.bezier(0.4, 0, 0.2, 1) : Easing.inOut(Easing.ease) export type MindboxEmbeddedBlockProps = { @@ -224,12 +207,6 @@ const Block = ({ placeSystemName, height, timeoutMs, loadingStrategy = MindboxEm const blockHeight = Number.isFinite(height) ? Math.max(0, height) : 0 - // The warnings live in effects, not in the render body: React may run a render more than once - // for a single commit (StrictMode, a suspended tree), and a ref flipped during render would not - // keep the word from being said twice. An effect runs once per commit. - // - // Only the empty name is worth a word. Space around a real name is not a mistake to report: the - // SDK trims the name before it resolves by it, so a padded name finds its place either way. useEffect(() => { if (placeSystemName.trim().length === 0) { console.warn('[MindboxEmbeddedBlock] A block was created without a place system name: there is nothing to resolve by it, so the place collapses and reports onEmpty.') @@ -237,11 +214,9 @@ const Block = ({ placeSystemName, height, timeoutMs, loadingStrategy = MindboxEm if (blockHeight <= 0) { console.warn(`[MindboxEmbeddedBlock] The block "${placeSystemName}" was created with height ${height}: it reserves no space, so nothing loads and no outcome is reported.`) } - // Creation only: the name remounts the component through its key, and the height is live. // eslint-disable-next-line react-hooks/exhaustive-deps }, []) - // The values fixed at creation: a new one is ignored and said once, per value. const warnedCreationValues = useRef(new Set()) useEffect(() => { const warnIfIgnored = (name: string, given: unknown, kept: unknown) => { @@ -256,15 +231,9 @@ const Block = ({ placeSystemName, height, timeoutMs, loadingStrategy = MindboxEm warnIfIgnored('animatesReveal', animatesReveal, creationAnimatesReveal) }, [timeoutMs, creationTimeoutMs, loadingStrategy, creationLoadingStrategy, animatesReveal, creationAnimatesReveal, placeSystemName]) - // The callbacks are read through a ref at delivery time, so a host that passes a fresh closure - // on every render neither re-subscribes anything nor misses the one delivery of an outcome. const callbacks = useRef({ onLoad, onEmpty, onFail }) callbacks.current = { onLoad, onEmpty, onFail } - /** - * The outcome delivered last — the deduplication key. Deliberately without the failure reason: - * a silent retry that fails differently is still the same outcome. - */ const deliveredOutcome = useRef(null) const deliver = useCallback((outcome: Outcome, reason: string | null) => { @@ -285,31 +254,18 @@ const Block = ({ placeSystemName, height, timeoutMs, loadingStrategy = MindboxEm } }, []) - // No native block to report: the place collapses and the host hears the same failure it would - // hear from a block that could not be shown. In an effect, after the first commit, as a native - // block's report would arrive after the first layout. useEffect(() => { if (!IS_SUPPORTED) { deliver('fail', MindboxEmbeddedBlockFailReason.internalError) } }, [deliver]) - /** The growth of a block that waited hidden: 0 to 1 over the SDK's reveal, 1 at rest. */ const reveal = useRef(new Animated.Value(1)).current - /** The opacity of a host overlay the content is replacing: 1 to 0 over the SDK's reveal. */ const overlayFade = useRef(new Animated.Value(1)).current - /** The overlay still fading out above the content, if any. */ const [fadingOverlay, setFadingOverlay] = useState(null) - /** Tells a fade that ran its course from one that was interrupted and restarted. */ const fadeGeneration = useRef(0) const shownAppearance = useRef(appearance) - /** - * Takes the block to [next]. The arrival of content is the one change that is animated, and only - * when the native block says so — it owns that decision, gates included — for as long as it - * says: a slot that was closed grows, and a host overlay the content replaces fades out above - * it. Everything else lands at once. - */ const show = useCallback( (next: Appearance, revealDurationMs?: number) => { const previous = shownAppearance.current @@ -326,11 +282,6 @@ const Block = ({ placeSystemName, height, timeoutMs, loadingStrategy = MindboxEm reveal.setValue(1) } - // The native block fades its content in from transparent, and the host's stand-in under it - // is clear — so a placeholder or an error screen taken away in the same frame would leave the - // screen's background showing through the fade. SwiftUI and Compose fade their stand-ins out - // under the content for the same reason; here the overlay lies above the native view, so it - // fades out over the same duration instead. Any other change takes it away at once. fadeGeneration.current += 1 const generation = fadeGeneration.current overlayFade.stopAnimation() @@ -370,34 +321,22 @@ const Block = ({ placeSystemName, height, timeoutMs, loadingStrategy = MindboxEm [deliver] ) - // The overlay of the current look, or the one still fading out above the content. const shownOverlay: Overlay | null = appearance === 'placeholder' || appearance === 'error' ? appearance : fadingOverlay const overlay = shownOverlay === 'placeholder' ? placeholder : shownOverlay === 'error' ? error : null const isOverlayFading = shownOverlay != null && shownOverlay !== appearance - // The height the layout is given: nothing for a collapsed block, the block's height otherwise — - // and, while a block that waited hidden is revealed, the part of it the growth has reached. const slotHeight = useMemo(() => reveal.interpolate({ inputRange: [0, 1], outputRange: [0, blockHeight] }), [reveal, blockHeight]) return ( - {/* - The slot is what the layout sees; the block inside keeps its full height whatever the slot - is. A native view sized to nothing is never built — both native halves wait for a frame — - so a block that waits hidden would never load and never grow. With its own height under a - clipped slot of zero it runs its whole cycle unseen, as the native blocks do, and the slot - opens when the content arrives. - */} + {/* A native view of zero size never loads, so the block keeps its full height under a collapsed slot. */} {IS_SUPPORTED ? : null} {overlay != null ? ( - // An overlay on its way out is a picture, not a surface: touches go through to the content. {overlay} @@ -407,15 +346,6 @@ const Block = ({ placeSystemName, height, timeoutMs, loadingStrategy = MindboxEm ) } -/** - * The look a block starts with, before the native block exists to say. - * - * `placeholder` and `hidden` are decided by the strategy alone. `automatic` is decided by the SDK's - * memory of the place, which only the native side has: the native block reads it as it is built and - * reports its first look right away. Until that report an `automatic` block takes no space: a place - * that has never shown content must not flash reserved space, and one that has shows its placeholder - * a frame late rather than a frame early. - */ const firstLook = (strategy: MindboxEmbeddedBlockLoadingStrategy): Appearance => (strategy === MindboxEmbeddedBlockLoadingStrategy.placeholder ? 'placeholder' : 'collapsed') const styles = StyleSheet.create({ diff --git a/src/MindboxEmbeddedBlockNativeComponent.ts b/src/MindboxEmbeddedBlockNativeComponent.ts index a999cfc..1b97277 100644 --- a/src/MindboxEmbeddedBlockNativeComponent.ts +++ b/src/MindboxEmbeddedBlockNativeComponent.ts @@ -2,22 +2,12 @@ import type { ViewProps } from 'react-native' import type { DirectEventHandler, Double, Int32, WithDefault } from 'react-native/Libraries/Types/CodegenTypes' import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent' -/** - * The look the native block shows: `placeholder`, `content`, `error` or `collapsed`. `animated` is - * `true` for the one change that is the SDK's reveal of content — the native block owns that - * decision, gates included — and `revealDurationMs` is how long it takes; both are `false` and `0` - * for every other change. - */ type AppearanceChangeEvent = Readonly<{ appearance: string animated: boolean revealDurationMs: Int32 }> -/** - * How the load ended: `load`, `empty` or `fail`. The reason goes with a failure and is empty - * otherwise — an event payload has every field, so the absence is spelled as an empty string. - */ type BlockOutcomeEvent = Readonly<{ outcome: string reason: string @@ -30,7 +20,6 @@ export interface NativeProps extends ViewProps { timeoutMs?: Double - /** `automatic`, `placeholder` or `hidden`; an empty word means `automatic`. */ loadingStrategy?: string animatesReveal?: WithDefault diff --git a/src/__tests__/MindboxEmbeddedBlock.test.tsx b/src/__tests__/MindboxEmbeddedBlock.test.tsx index 0d4d4eb..9089c8d 100644 --- a/src/__tests__/MindboxEmbeddedBlock.test.tsx +++ b/src/__tests__/MindboxEmbeddedBlock.test.tsx @@ -40,21 +40,18 @@ const reportAppearance = (renderer: ReactTestRenderer, appearance: string, revea }) } -/** The native block's report of how the load ended; an empty reason is what the event carries when there is none. */ const reportOutcome = (renderer: ReactTestRenderer, outcome: string, reason = '') => { act(() => { nativeProps(renderer).onBlockOutcome({ nativeEvent: { outcome, reason } }) }) } -/** The height the layout is given: the slot the block stands in. */ -const frameHeight = (renderer: ReactTestRenderer) => { +const slotHeight = (renderer: ReactTestRenderer) => { const frame = renderer.root.findAllByType(asType(View))[0] return StyleSheet.flatten(frame.props.style).height } -/** The height of the block inside the slot — what the native view is laid out in. */ -const insideHeight = (renderer: ReactTestRenderer) => { +const nativeBlockHeight = (renderer: ReactTestRenderer) => { const inside = renderer.root.findAllByType(asType(View))[1] return StyleSheet.flatten(inside.props.style).height } @@ -65,11 +62,11 @@ describe('MindboxEmbeddedBlock', () => { it('takes its height while loading and hands it back when the block collapses', () => { const renderer = render(placeholderBlock()) - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) reportAppearance(renderer, 'collapsed') - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) }) it('resizes a live block in place when the height changes', () => { @@ -77,8 +74,8 @@ describe('MindboxEmbeddedBlock', () => { update(renderer, placeholderBlock({ height: 80 })) - expect(frameHeight(renderer)).toBe(80) - expect(insideHeight(renderer)).toBe(80) + expect(slotHeight(renderer)).toBe(80) + expect(nativeBlockHeight(renderer)).toBe(80) expect(nativeProps(renderer).blockHeight).toBe(80) }) @@ -122,13 +119,12 @@ describe('MindboxEmbeddedBlock', () => { expect(warn.mock.calls[0][0]).toContain('reports onEmpty') - // What the native blocks report for a name of nothing: a place with nothing behind it. reportAppearance(renderer, 'collapsed') reportOutcome(renderer, 'empty') expect(onEmpty).toHaveBeenCalledTimes(1) expect(onFail).not.toHaveBeenCalled() - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) warn.mockRestore() }) @@ -142,7 +138,7 @@ describe('MindboxEmbeddedBlock', () => { expect(warn).toHaveBeenCalledTimes(1) expect(warn.mock.calls[0][0]).toContain('reserves no space') - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) expect(nativeProps(renderer).blockHeight).toBe(0) warn.mockRestore() }) @@ -225,7 +221,7 @@ describe('MindboxEmbeddedBlock', () => { expect(onEmpty).toHaveBeenCalledTimes(1) expect(onEmpty).toHaveBeenCalledWith() expect(onFail).not.toHaveBeenCalled() - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) }) it('hands the failure reason to onFail as the native block spelled it', () => { @@ -310,7 +306,7 @@ describe('MindboxEmbeddedBlock', () => { reportAppearance(renderer, 'collapsed') reportAppearance(renderer, 'sideways') - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) }) it('builds a different place as a different block, with nothing remembered', () => { @@ -360,15 +356,15 @@ describe('MindboxEmbeddedBlock', () => { it('gives a placeholder block its height from the first frame', () => { const renderer = render(placeholderBlock({ placeholder: loading })) - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) expect(renderer.root.findByType(asType(Text)).props.children).toBe('loading') }) it('gives a hidden block no slot while the native view inside keeps the full height', () => { const renderer = render(loading} />) - expect(frameHeight(renderer)).toBe(0) - expect(insideHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(0) + expect(nativeBlockHeight(renderer)).toBe(104) expect(nativeProps(renderer).blockHeight).toBe(104) expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) }) @@ -376,13 +372,13 @@ describe('MindboxEmbeddedBlock', () => { it('keeps an automatic block at zero until the native block reports a placeholder, then shows it', () => { const renderer = render(loading} />) - expect(frameHeight(renderer)).toBe(0) - expect(insideHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(0) + expect(nativeBlockHeight(renderer)).toBe(104) expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) reportAppearance(renderer, 'placeholder') - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) expect(renderer.root.findByType(asType(Text)).props.children).toBe('loading') }) @@ -391,7 +387,7 @@ describe('MindboxEmbeddedBlock', () => { reportAppearance(renderer, 'collapsed') - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) }) }) @@ -417,16 +413,16 @@ describe('MindboxEmbeddedBlock', () => { reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) tick(125) - expect(frameHeight(renderer)).toBeGreaterThan(30) - expect(frameHeight(renderer)).toBeLessThan(74) + expect(slotHeight(renderer)).toBeGreaterThan(30) + expect(slotHeight(renderer)).toBeLessThan(74) tick(125) - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) }) it('lands at once when the native block does not call the change a reveal', () => { @@ -434,7 +430,7 @@ describe('MindboxEmbeddedBlock', () => { reportAppearance(renderer, 'content') - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) }) it('lands at once when the reveal comes without a duration', () => { @@ -442,7 +438,7 @@ describe('MindboxEmbeddedBlock', () => { reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 0 }) - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) }) it('does not grow content that arrives into a placeholder: the space was taken already', () => { @@ -450,11 +446,11 @@ describe('MindboxEmbeddedBlock', () => { reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) tick(125) - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) }) it('collapses at once in the middle of a reveal', () => { @@ -464,34 +460,32 @@ describe('MindboxEmbeddedBlock', () => { tick(125) reportAppearance(renderer, 'collapsed') - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) tick(250) - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) }) - it.each(['error', 'placeholder'])('takes the full height at once when %s arrives in the middle of a reveal', (appearance) => { + it.each(['error', 'placeholder'])('takes the full height at once and stops the growth when %s arrives in the middle of a reveal', (appearance) => { const renderer = render(loading} error={broken} />) reportAppearance(renderer, 'content', { animated: true, revealDurationMs: 250 }) tick(125) - const midway = frameHeight(renderer) + const midway = slotHeight(renderer) expect(midway).toBeGreaterThan(0) expect(midway).toBeLessThan(104) reportAppearance(renderer, appearance) - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) - // The old growth is stopped, not left to finish on its own schedule. tick(60) - expect(frameHeight(renderer)).toBe(104) + expect(slotHeight(renderer)).toBe(104) }) describe('the host overlay under the reveal', () => { - /** The host's overlay layer: the view that holds the placeholder or the error screen. */ const overlayHost = (renderer: ReactTestRenderer) => renderer.root.findAll((node) => node.type === View && (node.props.pointerEvents === 'box-none' || node.props.pointerEvents === 'none'))[0] const overlayOpacity = (renderer: ReactTestRenderer) => StyleSheet.flatten(overlayHost(renderer).props.style).opacity diff --git a/src/__tests__/MindboxEmbeddedBlock.unsupported.test.tsx b/src/__tests__/MindboxEmbeddedBlock.unsupported.test.tsx index 6f9a2ae..9cf6b71 100644 --- a/src/__tests__/MindboxEmbeddedBlock.unsupported.test.tsx +++ b/src/__tests__/MindboxEmbeddedBlock.unsupported.test.tsx @@ -3,11 +3,7 @@ import { StyleSheet, View } from 'react-native' import { act, create } from 'react-test-renderer' import type { ReactTestRenderer } from 'react-test-renderer' -/** - * A platform without the native block — anything but iOS and Android. `Platform.OS` is read when - * the component module loads, so the platform is set before the component is required, in a test - * file of its own. - */ +// `Platform.OS` is read when the component module loads, so it is mocked before the require below. jest.mock('react-native/Libraries/Utilities/Platform', () => ({ OS: 'web', select: (specifics: Record) => specifics.default, @@ -32,7 +28,7 @@ const render = (element: React.ReactElement): ReactTestRenderer => { return renderer! } -const frameHeight = (renderer: ReactTestRenderer) => { +const slotHeight = (renderer: ReactTestRenderer) => { const frame = renderer.root.findAllByType(View as any)[0] return StyleSheet.flatten(frame.props.style).height } @@ -44,7 +40,7 @@ describe('MindboxEmbeddedBlock on a platform without the native block', () => { const onFail = jest.fn() const renderer = render() - expect(frameHeight(renderer)).toBe(0) + expect(slotHeight(renderer)).toBe(0) expect(renderer.root.findAllByProps({ testID: 'native-block' })).toHaveLength(0) expect(onFail).toHaveBeenCalledTimes(1) expect(onFail).toHaveBeenCalledWith('internalError') diff --git a/src/react-native-children.d.ts b/src/react-native-children.d.ts index 0e177d0..ae505a7 100644 --- a/src/react-native-children.d.ts +++ b/src/react-native-children.d.ts @@ -1,17 +1,4 @@ -/** - * `children` on the React Native views this package draws with. - * - * `@types/react-native@0.62.13` — the version this repo pins — describes `ViewProps` and - * `TextProps` without `children`, so nesting anything inside a `` is an error. It never came - * up before: until the embedded block there was no JSX under `src/` at all. - * - * This is an augmentation, not a redeclaration: the top-level `export {}` is what makes the file a - * module, and without it the `declare module` below would replace React Native's typings instead of - * adding to them. - * - * Delete this file together with the `@types/react-native` dependency, once the pinned React Native - * is one that ships its own TypeScript types. - */ +// `@types/react-native` 0.62.13 lacks `children` on `ViewProps` and `TextProps`; delete this file with that dependency. export {} diff --git a/src/react-native-codegen.d.ts b/src/react-native-codegen.d.ts index e315266..fce0e82 100644 --- a/src/react-native-codegen.d.ts +++ b/src/react-native-codegen.d.ts @@ -1,21 +1,4 @@ -/** - * The codegen vocabulary, for the React Native this repo pins. - * - * A native component's spec has to name its prop types in the words the native codegen reads — - * `Double`, `WithDefault`, `DirectEventHandler` — and import them, along with - * `codegenNativeComponent`, from these exact paths. React Native 0.63 ships both files as plain - * JavaScript with no declarations next to them, so TypeScript has nothing to go on and the spec - * would be an implicit `any`. - * - * Declared here rather than worked around: the paths are what the generator expects, and a spec - * written any other way stops producing the Android view manager delegate and the iOS component - * descriptor. What the runtime does with the two modules is unaffected — on the old renderer - * `codegenNativeComponent` falls back to `requireNativeComponent`, on the new one the generated - * view config takes over. - * - * Delete this file once the pinned React Native is 0.71 or later: from there React Native ships - * its own TypeScript types and these declarations become its own. - */ +// React Native 0.63 ships the codegen modules without type declarations; delete this file once the pinned React Native is 0.71 or later. declare module 'react-native/Libraries/Types/CodegenTypes' { import type { NativeSyntheticEvent } from 'react-native' @@ -25,16 +8,10 @@ declare module 'react-native/Libraries/Types/CodegenTypes' { export type Int32 = number export type UnsafeMixed = unknown - /** - * A prop the native side gives a default to. Left out on the JS side, it crosses the boundary as - * that default, which is why the JS type stays optional. - */ export type WithDefault = Type | undefined - /** An event the native view sends to this view's own handler. */ export type DirectEventHandler = (event: NativeSyntheticEvent) => void - /** An event the native view sends up the tree. */ export type BubblingEventHandler = (event: NativeSyntheticEvent) => void } From b351dac7d1ad423a786a1056aef30e4684a92750 Mon Sep 17 00:00:00 2001 From: Sergei Semko <28645140+justSmK@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:51:10 +0300 Subject: [PATCH 12/16] MOBILE-0000: Cut the public API docs down to the host contract (#231) One line per public member, worded as in the native SDKs; the README drops its embedded block section. A failed targeting fetch is documented under onEmpty, not networkError, and the advice to hide the section in onEmpty is gone. --- CHANGELOG.md | 2 +- README.md | 96 +------------ src/MindboxEmbeddedBlock.tsx | 156 ++++----------------- src/MindboxEmbeddedBlockFailReason.ts | 26 +--- src/MindboxEmbeddedBlockLoadingStrategy.ts | 38 +---- 5 files changed, 40 insertions(+), 278 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d1537b..0b38a34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## [Unreleased] ### Changes -- **Breaking since `2.16.0-rc`:** `onFail` of `MindboxEmbeddedBlock` reports failures only; a place with nothing to show arrives in the new `onEmpty`. A host that hid its section in `onFail` — as the previous README showed — moves that to `onEmpty`. +- **Breaking since `2.16.0-rc`:** `onFail` of `MindboxEmbeddedBlock` reports failures only; a place with nothing to show arrives in the new `onEmpty`. - **Breaking since `2.16.0-rc`:** the `MindboxEmbeddedBlockFailure` type is removed; `onFail` receives a `MindboxEmbeddedBlockFailReason` string instead of an empty object. - **Breaking since `2.16.0-rc`:** `MindboxEmbeddedBlock` starts by `loadingStrategy="automatic"` — hidden until the place has shown content once on this device — instead of always showing a placeholder; `loadingStrategy="placeholder"` restores the previous look. - Add `MindboxEmbeddedBlock` — an embedded block for a place from the admin panel, a native component for both the old and the new architecture. diff --git a/README.md b/README.md index a785507..4643a13 100644 --- a/README.md +++ b/README.md @@ -17,9 +17,7 @@ Follow the installation process detailed [here](https://developers.mindbox.ru/do ```markdown npm i --save mindbox-sdk ``` - The package requires React Native 0.71 or newer: the embedded block is a native component whose - glue is generated by React Native Codegen, and the Android module applies the - `com.facebook.react` Gradle plugin to run it. Both work on the old and the new architecture. + The package requires React Native 0.71 or newer, on the old or the new architecture. 2. For iOS, make sure to install the pods: ```markdown @@ -34,98 +32,6 @@ Initialize the Mindbox SDK in your React Native app. You can find the necessary Learn how to send events to Mindbox. Different operations and their usage are detailed [here](https://developers.mindbox.ru/docs/integration-actions-react-native). -### Embedded Blocks - -Mark a place in your layout with `MindboxEmbeddedBlock` and the SDK decides what goes into it from -the admin panel — the app never learns what the content is, and it can change without a release. -The host owns the size: pass the `height` the block should occupy. A place that ends up without -content collapses to zero height and hands the space back. - -```tsx -import { MindboxEmbeddedBlock } from 'mindbox-sdk'; - - -``` - -The outcome arrives through three callbacks, the same three as in SwiftUI, Compose and Flutter: -`onLoad` when the content is shown, `onEmpty` when there is nothing to show at the place, and -`onFail` with a `MindboxEmbeddedBlockFailReason` when the block could not be shown. An empty place -is a normal outcome, not a breakage, and comes with no reason; a block whose place system name is -empty is such a place too. A failure's reason — `networkError` -or `internalError` — is for logs and analytics, not for branching: by the time it arrives the block -has already collapsed or switched to `error`. A later SDK may add reasons, so keep a fallback when -matching. - -Both looks can be customized, the same way as in SwiftUI, Compose and Flutter: `placeholder` -replaces the stock loading shimmer, and `error` opts into showing a failure instead of collapsing. -An empty place always collapses — a host cannot fill the space of a block that was never meant to -be there. - -```tsx -} - error={} - onEmpty={() => setShowStoriesSection(false)} - onFail={(reason) => console.log(`stories failed: ${reason}`)} -/> -``` - -How long a block may wait for its content before it gives the place back is `timeoutMs`. Left out, -it is the SDK's own budget of 30 seconds. The wait is the user's: it is counted only while the -screen the block stands on is the one being looked at — and since every React Native screen lives -in the same native window, the block cannot see that for itself. Pass `active` from the navigation -(`useIsFocused()` in React Navigation), or a block behind a pushed screen will spend its budget on -a screen nobody is looking at. - -```tsx - -``` - -What the block shows until the SDK has decided what goes into it is `loadingStrategy`, the same -three choices as in SwiftUI, Compose and Flutter. `automatic` — the default — keeps the block hidden -until the place has shown content once on this device and puts a placeholder there from then on: -nothing flashes where no content is expected, and where it is expected the space is taken as soon -as the native side has read the place's memory — a frame after the block is mounted, so what stands -below moves down by the block's height once. `placeholder` takes the space from the first frame, -worth naming for a place that always has a campaign behind it. `hidden` never takes it until the -content is shown. - -A block that waits hidden — `hidden`, and `automatic` at a place that has not shown content yet — -draws neither `placeholder` nor `error` until its content has been shown once: a failure keeps it -collapsed, and only `onFail` tells. With the default strategy that is every place on a fresh -install, so a host that counts on its `error` screen names `loadingStrategy="placeholder"`. - -The content is revealed with the SDK's own animation — it fades in, and a block that started hidden -grows to its height — unless `animatesReveal` is off; the system's reduced-motion setting turns it -off as well. Turn it off to animate the block's container yourself in `onLoad` — keeping in mind -that a block that waited hidden is only starting to grow from zero at that moment. A host -`placeholder` the content replaces fades out above it over the same reveal. - -```tsx - -``` - -`height` is live: a new value resizes a block already on screen in place — the same content, no -reload. It has to be positive, though: a block given no space to occupy is never loaded and reports -no outcome. `timeoutMs`, `loadingStrategy` and `animatesReveal` are fixed when the block is created -— a new value is ignored with a warning; give the component a new `key` to build a block anew. - -Available on iOS and Android. On any other platform the block collapses right away and reports -`onFail` with `internalError`, so a layout that hides its section on failure behaves the same -everywhere. - ### Push Notifications Mindbox SDK aids in handling push notifications. It offers configurations and usage instructions, found in the SDK documentation [Android(FCM)](https://developers.mindbox.ru/docs/firebase-send-push-notifications-react-native), [Android(HCM)](https://developers.mindbox.ru/docs/huawei-send-push-notifications-react-native), [IOS](https://developers.mindbox.ru/docs/ios-send-push-notifications-react-native) and [IOS(Rich)](https://developers.mindbox.ru/docs/ios-send-rich-push-react-native). diff --git a/src/MindboxEmbeddedBlock.tsx b/src/MindboxEmbeddedBlock.tsx index 828f446..169c23d 100644 --- a/src/MindboxEmbeddedBlock.tsx +++ b/src/MindboxEmbeddedBlock.tsx @@ -27,136 +27,57 @@ const REVEAL_EASING = Platform.OS === 'android' ? Easing.bezier(0.4, 0, 0.2, 1) export type MindboxEmbeddedBlockProps = { /** - * The name of the place from the admin panel. A different name is a different block, built from - * scratch in place of the old one. - * - * Passed down as given. Whitespace around the name is not part of it: the native blocks ignore - * it, so a name pasted from the admin panel with a stray space still finds its place. The name - * itself is matched the way the native SDK matches it. A name that is empty — or nothing but - * spaces — is no name at all, so the place resolves to nothing: the block collapses and reports - * [onEmpty], as for any place with nothing behind it. The component warns about that. + * The place's system name from the admin panel, matched ignoring letter case and surrounding + * whitespace. A new name builds a new block. */ placeSystemName: string /** - * The height the block occupies while it loads and while it is shown. A place that ends up without - * content collapses to zero height and hands the space back. - * - * Live: a new value resizes a block already on screen in place — the same content, no reload — - * exactly as the SwiftUI, Compose and Flutter wrappers behave. - * - * It has to be a positive number. A block given no space to occupy is never loaded at all — a page - * laid out in a zero viewport does not lay itself out again once the space arrives — and reports - * neither outcome. The component warns about such a height. + * The block's height while it is not collapsed; a new value resizes the block in place. A block + * created without a positive height loads nothing until it gets one. */ height: number /** - * How long the block waits to find out what to show, in milliseconds. Covers the wait for the - * answer — the config and the targeting — not the whole life of the block: a page that has already - * arrived gets its own time to render. When the wait runs out, the block collapses and reports - * [onFail]. - * - * The budget is the user's, not the clock's: it ticks only while the screen with the block is - * actually looked at (see [active]). Omitted means the SDK's own default of 30 seconds; zero and - * negative values mean it too. The value is taken once, when the block is created — the same rule as - * in the SwiftUI, Compose and Flutter wrappers — so a new value on a live block is ignored with a - * warning. Remount the component (give it a new `key`) to change it. + * How long, in milliseconds, the block waits for the SDK to choose its content before it fails with + * `networkError`, counted while its screen is shown (see `active`). Omitted, zero or negative means + * 30 seconds. */ timeoutMs?: number - /** - * What the block shows until the SDK answers — see [MindboxEmbeddedBlockLoadingStrategy]. - * - * `automatic` — the default — keeps the block hidden until the place has shown content once on - * this device and puts a placeholder there from then on. A block that takes its space up front - * keeps the layout still at the price of flashing where there is nothing to show; a block that - * waits hidden never flashes at the price of the layout growing when content arrives. A place - * that always has a campaign behind it is worth an explicit `placeholder`. - * - * A block that waits hidden — `hidden`, and `automatic` at a place that has not shown content - * yet — draws neither [placeholder] nor [error] until its content has been shown once: a failure - * keeps it collapsed, and only [onFail] tells. - * - * Fixed when the block is created, as [timeoutMs] is: a new value on a live block is ignored with - * a warning. Remount the component (give it a new `key`) to build a block anew. - */ + /** What the block shows while it loads; `automatic` by default. */ loadingStrategy?: MindboxEmbeddedBlockLoadingStrategy /** - * Whether the SDK animates the reveal of the content — a fade, and the growth of a block that - * waited hidden. `true` by default; the system's reduced-motion setting turns the animation off - * as well. Turn it off to animate the block's container yourself in [onLoad]. - * - * Fixed when the block is created, as [timeoutMs] is. + * Whether the SDK animates the content's appearance; `true` by default. Set `false` to animate the + * block's container yourself in `onLoad`. */ animatesReveal?: boolean - /** - * Drawn instead of the SDK shimmer while the block is loading. Fills the whole place, as the native - * placeholder does. Not drawn by a block that waits hidden — see [loadingStrategy] — until its - * content has been shown once. - * - * When the content arrives with the SDK's reveal, the placeholder fades out over it rather than - * vanishing a frame before the content is opaque. - */ + /** Shown instead of the SDK's shimmer while the block loads. */ placeholder?: React.ReactNode /** - * Drawn instead of collapsing when the block cannot be shown. - * - * Applies only to failures: an empty place — one with nothing behind its place system name — always - * collapses, so a host cannot fill the space of a block that was never meant to be there. Nor is it - * drawn by a block that waits hidden — see [loadingStrategy] — which never took the space: with the - * default strategy, a place that has not shown content on this device yet simply stays collapsed - * on a failure, and only [onFail] tells. + * Shown, instead of collapsing, when the block fails while it takes its height. Pass it from the + * start: adding it later does not expand a collapsed block. */ error?: React.ReactNode - /** - * The content is shown: the block has taken its height and is visible. A block that waited hidden - * is only starting to grow from zero at this moment — a host that measures the block here, or - * scrolls to it, sees it still at almost no height until the reveal is over. - * - * Delivered once per outcome, not once per lifetime: the same outcome is never repeated, and an - * outcome that actually changed — a place that filled up after a failure — is delivered again. - * The native block reports the same way, so every wrapper of the SDK calls back alike. - */ + /** Called when the content is shown. */ onLoad?: () => void /** - * There is nothing to show at the place: no campaign behind its name, the targeting or the A/B - * group did not match, the show budget is spent, or the page rendered nothing. A normal outcome, - * not a breakage: the block collapses, [error] does not apply, and no reason is given — which of - * these it was is the SDK's business. - * - * Delivered on the same rule as [onLoad]: once per outcome, again if the outcome changes. + * Called when the block collapses because the place has nothing to show or the data its targeting + * needs could not be fetched. */ onEmpty?: () => void - /** - * The block could not be shown: the SDK had no config or never answered, the page could not be - * loaded, the content is malformed or the SDK hit an internal error. The block collapses, or keeps - * its height and draws [error] when one is given — unless it was waiting hidden, see - * [loadingStrategy]: a block that never took its space stays collapsed whatever [error] says. An - * empty place is not a failure and arrives in [onEmpty] instead. - * - * The reason is for logs and analytics, not for branching: whatever it is, the block has already - * collapsed or switched to [error]. Compare it with the constants of - * [MindboxEmbeddedBlockFailReason] and keep a fallback — a later SDK may add reasons. - * - * Delivered on the same rule as [onLoad]: once per outcome, again if the outcome changes. A - * failure that repeats with a different reason is the same outcome and is not delivered again. - */ + /** Called when the block fails; it collapses or shows `error`. */ onFail?: (reason: MindboxEmbeddedBlockFailReason) => void /** - * Whether the screen the block stands on is the one being looked at. `true` by default. - * - * The native container watches its window, and in RN that is not enough: a native stack keeps the - * screens below the top one in the window, so leaving a screen never takes the block out of it. - * Left alone, the block would spend its whole waiting budget behind another screen and collapse - * before the user came back. Pass `useIsFocused()` — or whatever the app's navigation calls it. + * Whether the block's screen is the one in front; `true` by default. Pass `useIsFocused()` or its + * equivalent: screens under the top one stay in the native window, so the block cannot tell. */ active?: boolean @@ -164,37 +85,22 @@ export type MindboxEmbeddedBlockProps = { } /** - * An embedded Mindbox block. + * Shows the Mindbox embedded block configured for a place in the admin panel. * - * The app marks a *place* by its [placeSystemName] and never learns what goes into it — that is the - * config's decision, and it can change without an app release. **The host owns the size**: pass the - * [height] the block should occupy. + * Give it a height and let the layout set its position and width. Keep it in the layout rather than + * removing it in `onEmpty`: a collapsed block still shows content the place gets later. + * `timeoutMs`, `loadingStrategy` and `animatesReveal` are read only when the block is created; give + * the component a new `key` to change them. On platforms other than iOS and Android the block + * collapses and reports `onFail` with `internalError`. * * ```tsx - * + * } + * onFail={(reason) => console.log(`stories failed: ${reason}`)} + * /> * ``` - * - * Both looks can be customized, the same way as in SwiftUI, Compose and Flutter: [placeholder] - * replaces the stock loading shimmer, and [error] opts into showing a failure instead of collapsing. - * Both stay ordinary RN nodes, drawn above the native view, so they resolve the context, the theme - * and the handlers of the tree the block itself stands in. The wait for an answer is bounded by - * [timeoutMs] — 30 seconds unless the host says otherwise. - * - * What the block shows until the SDK has decided what goes into it is the [loadingStrategy]: a - * placeholder, nothing, or — by default — nothing until the place has shown content once on this - * device and a placeholder from then on. The content is revealed with the SDK's own animation — it - * fades in, and a block that started hidden grows to its height — unless [animatesReveal] is off. - * - * The outcome arrives through three callbacks, the same three as in SwiftUI, Compose and Flutter: - * [onLoad] when the content is shown, [onEmpty] when there is nothing to show at the place, and - * [onFail] with a reason when the block could not be shown. - * - * The component is a thin layer over the native block: the native view holds the SDK's own container - * — with its waiting budget and its web page — and this component only mirrors the container's - * decisions in the RN layout. - * - * **iOS and Android.** On any other platform the block collapses right away and reports [onFail] - * with `internalError`, so a layout that hides its section on failure behaves the same everywhere. */ export const MindboxEmbeddedBlock = (props: MindboxEmbeddedBlockProps) => diff --git a/src/MindboxEmbeddedBlockFailReason.ts b/src/MindboxEmbeddedBlockFailReason.ts index b471408..08a57c7 100644 --- a/src/MindboxEmbeddedBlockFailReason.ts +++ b/src/MindboxEmbeddedBlockFailReason.ts @@ -1,30 +1,10 @@ -/** - * Why a block could not be shown — the payload of `MindboxEmbeddedBlock`'s `onFail`. - * - * Meant for logs and analytics on the host side, not for branching: whatever the reason, the block - * has already collapsed or switched to its error screen. A string rather than a closed union so a - * later SDK can add a reason without breaking an exhaustive `switch` — keep a fallback when - * matching. The raw values are the same on every platform: what the native iOS and Android blocks - * report under these names reaches React Native unchanged. - * - * The constants below are the ones this version knows; a later SDK may report a word that is not - * among them, and it arrives as it is. - */ +/** Why a block failed, for logs and analytics. Later SDK versions may add reasons, so keep a fallback when matching. */ export type MindboxEmbeddedBlockFailReason = 'networkError' | 'internalError' | (string & {}) export const MindboxEmbeddedBlockFailReason = { - /** - * The content is unavailable because of the environment: the config could not be downloaded and - * nothing is cached, the SDK gave no answer within the block's waiting budget, the block's page - * could not be loaded, or — on iOS — the data the targeting needs could not be fetched. Typically - * a network problem. - */ + /** The SDK could not get the content: no network or config, no answer within `timeoutMs`, or the page did not load. */ networkError: 'networkError', - /** - * An error on the Mindbox side: the page loaded but never reported its content or reported - * something unusable, or the SDK failed inside. Also what a platform without a native block - * reports. - */ + /** The page did not report usable content or the SDK failed inside; also reported off iOS and Android. */ internalError: 'internalError', } as const diff --git a/src/MindboxEmbeddedBlockLoadingStrategy.ts b/src/MindboxEmbeddedBlockLoadingStrategy.ts index e55e90a..aecf3d8 100644 --- a/src/MindboxEmbeddedBlockLoadingStrategy.ts +++ b/src/MindboxEmbeddedBlockLoadingStrategy.ts @@ -1,43 +1,13 @@ -/** - * What the block shows until the SDK has decided what goes into it — given at creation. - * - * Every place marked up in the app waits for the SDK on every launch, and a place with no campaign - * behind it would flash a placeholder and collapse each time. The strategy decides whether the - * block takes its space before the answer, and the SDK remembers per place whether content was - * ever shown there: nothing flashes where no content is expected, and where it is expected the - * space is taken as soon as the native side has read that memory — a frame after the block is - * mounted, not from the first frame. - * - * The same three values exist on every platform; `automatic` is the default everywhere. - */ +/** What a block shows while it loads, set when the block is created. */ export type MindboxEmbeddedBlockLoadingStrategy = 'automatic' | 'placeholder' | 'hidden' export const MindboxEmbeddedBlockLoadingStrategy = { - /** - * Hidden until the place has shown content once on this device; a placeholder from then on. - * - * The memory is per place system name and survives a restart. It is dropped when the place - * answers with nothing to show — the campaign was switched off, the targeting did not match, the - * page rendered nothing — so the next launch starts hidden again. A failure keeps the memory: - * that is "could not", not "nothing here". - * - * The memory lives on the native side and reaches JS a moment after the block is mounted, so an - * `automatic` block takes no space until it has: a place that has shown content before gets its - * placeholder a frame late rather than a place that has not getting a frame of reserved space. - * - * At a place that has not shown content yet the block waits hidden, as under `hidden`: no - * placeholder, and no `error` on a failure — only `onFail` tells. - */ + /** `placeholder` if the place has shown content on this device and has not come out empty since, otherwise `hidden`. */ automatic: 'automatic', - /** Always a placeholder until the answer: the SDK shimmer or the host's own `placeholder`. */ + /** A placeholder at the block's height: the host's `placeholder` or the SDK's shimmer. */ placeholder: 'placeholder', - /** - * Hidden until the content is shown once: zero height, no placeholder, and no `error` on a - * failure — a block that never took its space does not take it for an error screen either. The - * outcome still arrives through `onFail`. Once content was shown the space is taken, and a later - * failure may keep it with the host's error screen, like on every platform. - */ + /** Zero height until the content is shown. */ hidden: 'hidden', } as const From 6541c9a5b92e4b61d276d095acee48d2d6129b1d Mon Sep 17 00:00:00 2001 From: Sergei Semko <28645140+justSmK@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:55:16 +0300 Subject: [PATCH 13/16] MOBILE-0000: Use a GitHub App token instead of the PAT in release flows (#233) Release PRs and the master-to-develop merge-back were opened and merged with PAT_FOR_TRIGGERING_BRANCH_PROTECTION, a personal token of an org admin account, only because events made with GITHUB_TOKEN start no workflows. An installation token of the mindbox-mobile-ci App starts them the same way, covers only this repository and the permissions of its step, and expires within an hour. The key comes from the org secret MOBILE_CI_APP_PRIVATE_KEY and the client ID from the org variable MOBILE_CI_APP_CLIENT_ID. Release and merge-back PRs are now authored by mindbox-mobile-ci[bot]. --- .../manual-prepare_release_branch.yml | 10 +++++++++- .github/workflows/publish-common-trigger.yml | 4 ++-- .github/workflows/publish-reusable.yml | 19 +++++++++++++------ 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/.github/workflows/manual-prepare_release_branch.yml b/.github/workflows/manual-prepare_release_branch.yml index ee69f99..85f4845 100644 --- a/.github/workflows/manual-prepare_release_branch.yml +++ b/.github/workflows/manual-prepare_release_branch.yml @@ -180,9 +180,17 @@ jobs: runs-on: ubuntu-latest needs: bump_and_branch steps: + - name: Create App token + id: app-token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + client-id: ${{ vars.MOBILE_CI_APP_CLIENT_ID }} + private-key: ${{ secrets.MOBILE_CI_APP_PRIVATE_KEY }} + permission-contents: read + permission-pull-requests: write - name: Build PR body and open PR env: - GITHUB_TOKEN: ${{ secrets.PAT_FOR_TRIGGERING_BRANCH_PROTECTION }} + GH_TOKEN: ${{ steps.app-token.outputs.token }} SRC: ${{ needs.bump_and_branch.outputs.release_branch }} DST: ${{ github.event.inputs.target_branch }} REPO: ${{ github.repository }} diff --git a/.github/workflows/publish-common-trigger.yml b/.github/workflows/publish-common-trigger.yml index 64b732a..def21e0 100644 --- a/.github/workflows/publish-common-trigger.yml +++ b/.github/workflows/publish-common-trigger.yml @@ -35,7 +35,7 @@ jobs: with: branch: ${{ github.ref_name }} secrets: - PAT_FOR_TRIGGERING_BRANCH_PROTECTION: ${{ secrets.PAT_FOR_TRIGGERING_BRANCH_PROTECTION }} + MOBILE_CI_APP_PRIVATE_KEY: ${{ secrets.MOBILE_CI_APP_PRIVATE_KEY }} publish-from-pr: if: github.event_name == 'pull_request' && github.event.pull_request.merged == true @@ -46,4 +46,4 @@ jobs: with: branch: ${{ github.base_ref }} secrets: - PAT_FOR_TRIGGERING_BRANCH_PROTECTION: ${{ secrets.PAT_FOR_TRIGGERING_BRANCH_PROTECTION }} + MOBILE_CI_APP_PRIVATE_KEY: ${{ secrets.MOBILE_CI_APP_PRIVATE_KEY }} diff --git a/.github/workflows/publish-reusable.yml b/.github/workflows/publish-reusable.yml index 79ff146..9d95560 100644 --- a/.github/workflows/publish-reusable.yml +++ b/.github/workflows/publish-reusable.yml @@ -7,7 +7,7 @@ on: required: true type: string secrets: - PAT_FOR_TRIGGERING_BRANCH_PROTECTION: + MOBILE_CI_APP_PRIVATE_KEY: required: true permissions: @@ -106,19 +106,26 @@ jobs: startsWith(github.head_ref, 'release/') && github.base_ref == 'master' runs-on: ubuntu-latest - env: - # gh uses this PAT, not the workflow GITHUB_TOKEN — needed so the merge PR - # re-triggers branch-protection checks. Job-level `permissions:` only scope - # the workflow token, so they don't apply to these gh calls. - GITHUB_TOKEN: ${{ secrets.PAT_FOR_TRIGGERING_BRANCH_PROTECTION }} steps: + - name: Create App token + id: app-token + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + client-id: ${{ vars.MOBILE_CI_APP_CLIENT_ID }} + private-key: ${{ secrets.MOBILE_CI_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write - name: Checkout develop branch uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: develop - name: Create Pull Request + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} run: gh pr create --base develop --head master --title "Merge 'master' into 'develop' after release" --body "Automated Pull Request to merge 'master' into 'develop' after release" - name: Merge Pull Request + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} run: | pr_number=$(gh pr list --base develop --head master --json number --jq '.[0].number') gh pr merge "$pr_number" --merge --auto From 18073c7067ded2ef5558afe52bc679d2ea3db0df Mon Sep 17 00:00:00 2001 From: Sergey Sozinov <103035673+sergeysozinov@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:57:03 +0300 Subject: [PATCH 14/16] MOBILE-385: Raise compileSdk and targetSdk to 36 --- android/gradle.properties | 6 +++--- example/exampleApp/android/build.gradle | 7 +++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/android/gradle.properties b/android/gradle.properties index 03eae95..aad61de 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -1,4 +1,4 @@ MindboxSdk_kotlinVersion=1.5.31 -MindboxSdk_compileSdkVersion=29 -MindboxSdk_buildToolsVersion=29.0.2 -MindboxSdk_targetSdkVersion=29 +MindboxSdk_compileSdkVersion=36 +MindboxSdk_buildToolsVersion=35.0.0 +MindboxSdk_targetSdkVersion=36 diff --git a/example/exampleApp/android/build.gradle b/example/exampleApp/android/build.gradle index d2f118c..3f8450f 100644 --- a/example/exampleApp/android/build.gradle +++ b/example/exampleApp/android/build.gradle @@ -2,8 +2,8 @@ buildscript { ext { buildToolsVersion = "34.0.0" minSdkVersion = 23 - compileSdkVersion = 35 - targetSdkVersion = 35 + compileSdkVersion = 36 + targetSdkVersion = 36 ndkVersion = "26.1.10909125" kotlinVersion = "1.8.0" cmakeVersion = "3.22.1" @@ -12,7 +12,6 @@ buildscript { google() mavenCentral() maven { url 'https://developer.huawei.com/repo/' } - maven {url 'https://artifactory-external.vkpartner.ru/artifactory/maven'} } dependencies { classpath("com.android.tools.build:gradle:8.6.0") @@ -38,7 +37,7 @@ allprojects { maven { url 'https://www.jitpack.io' } maven { url "https://plugins.gradle.org/m2/" } maven { url 'https://developer.huawei.com/repo/' } - maven {url 'https://artifactory-external.vkpartner.ru/artifactory/maven'} + maven { url 'https://nexus-external.rustore.ru/repository/maven-rustore-exposed' } } } From 53ad9dfe19cc21bc326019534127b29ea62ea842 Mon Sep 17 00:00:00 2001 From: Sergey Sozinov <103035673+sergeysozinov@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:43:25 +0300 Subject: [PATCH 15/16] Merge pull request #236 from mindbox-cloud/fix_changelog MOBILE-0000: Drop the hand-written Unreleased section from the changelog --- CHANGELOG.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b38a34..6171e58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,15 +1,5 @@ # Changelog -## [Unreleased] - -### Changes -- **Breaking since `2.16.0-rc`:** `onFail` of `MindboxEmbeddedBlock` reports failures only; a place with nothing to show arrives in the new `onEmpty`. -- **Breaking since `2.16.0-rc`:** the `MindboxEmbeddedBlockFailure` type is removed; `onFail` receives a `MindboxEmbeddedBlockFailReason` string instead of an empty object. -- **Breaking since `2.16.0-rc`:** `MindboxEmbeddedBlock` starts by `loadingStrategy="automatic"` — hidden until the place has shown content once on this device — instead of always showing a placeholder; `loadingStrategy="placeholder"` restores the previous look. -- Add `MindboxEmbeddedBlock` — an embedded block for a place from the admin panel, a native component for both the old and the new architecture. -- `MindboxEmbeddedBlock` reports three outcomes, as the native SwiftUI and Compose blocks do: `onLoad`, `onEmpty` and `onFail` with a `MindboxEmbeddedBlockFailReason` (`networkError` or `internalError`). -- `MindboxEmbeddedBlock` takes a `loadingStrategy` — `automatic` (the default: hidden until the place has shown content once on this device, a placeholder from then on), `placeholder` or `hidden` — and `animatesReveal`, as the native SwiftUI and Compose blocks do. A block that waited hidden grows to its height with the SDK's reveal when its content arrives. - ## [2.16.0-rc] - 2026-09-11 ### Changes From b38a8a6ea6e6620d508b080a23090d8f0b64c689 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 30 Oct 2026 13:44:46 +0000 Subject: [PATCH 16/16] Bump RN SDK versions: core=2.16.0, android=2.16.0, ios=2.16.0 --- CHANGELOG.md | 7 +++++++ MindboxSdk.podspec | 4 ++-- android/build.gradle | 4 ++-- package.json | 2 +- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6171e58..d0a2cb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [Unreleased] + +### Changes +- Upgrade Android SDK dependency to v2.16.0 +- Upgrade iOS SDK dependency to v2.16.0 + + ## [2.16.0-rc] - 2026-09-11 ### Changes diff --git a/MindboxSdk.podspec b/MindboxSdk.podspec index 263433f..c1aba8d 100644 --- a/MindboxSdk.podspec +++ b/MindboxSdk.podspec @@ -15,8 +15,8 @@ Pod::Spec.new do |s| s.source_files = "ios/**/*.{h,m,mm,swift}" - s.dependency "Mindbox", "2.16.0-rc" - s.dependency "MindboxNotifications", "2.16.0-rc" + s.dependency "Mindbox", "2.16.0" + s.dependency "MindboxNotifications", "2.16.0" # Only this call defines RCT_NEW_ARCH_ENABLED for the pod, which MindboxEmbeddedBlockView.mm splits on. if respond_to?(:install_modules_dependencies, true) diff --git a/android/build.gradle b/android/build.gradle index 3c3b60e..253a345 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -127,7 +127,7 @@ dependencies { // noinspection GradleDynamicVersion api 'com.facebook.react:react-native:+' implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - api 'cloud.mindbox:mobile-sdk:2.16.0-rc' + api 'cloud.mindbox:mobile-sdk:2.16.0' implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.7" - compileOnly 'cloud.mindbox:mindbox-common:2.16.0-rc' + compileOnly 'cloud.mindbox:mindbox-common:2.16.0' } diff --git a/package.json b/package.json index 3797986..c1044f8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "mindbox-sdk", "version": "2.16.0-rc", - "target-version": "2.16.0-rc", + "target-version": "2.16.0", "description": "SDK for integration React Native mobile apps with Mindbox", "main": "lib/commonjs/index", "module": "lib/module/index",