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" | diff --git a/.github/workflows/manual-prepare_release_branch.yml b/.github/workflows/manual-prepare_release_branch.yml index ee69f99..3b33976 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 ############################################################################## @@ -180,9 +183,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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 62748b8..d0a2cb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # 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 +- 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 b5e72a2..c1aba8d 100644 --- a/MindboxSdk.podspec +++ b/MindboxSdk.podspec @@ -15,8 +15,13 @@ Pod::Spec.new do |s| s.source_files = "ios/**/*.{h,m,mm,swift}" - s.dependency "React-Core" + s.dependency "Mindbox", "2.16.0" + s.dependency "MindboxNotifications", "2.16.0" - s.dependency "Mindbox", "2.15.3" - s.dependency "MindboxNotifications", "2.15.3" + # 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 + s.dependency "React-Core" + end end diff --git a/README.md b/README.md index 2d8c1e9..4643a13 100644 --- a/README.md +++ b/README.md @@ -17,6 +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, on the old or the new architecture. 2. For iOS, make sure to install the pods: ```markdown diff --git a/android/build.gradle b/android/build.gradle index 4126851..253a345 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] @@ -126,5 +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' + implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.7" + compileOnly 'cloud.mindbox:mindbox-common:2.16.0' } 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/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/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/EmbeddedBlockWire.kt b/android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt new file mode 100644 index 0000000..6a1be4a --- /dev/null +++ b/android/src/main/java/com/mindboxsdk/embedded/EmbeddedBlockWire.kt @@ -0,0 +1,26 @@ +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 + +@OptIn(InternalMindboxApi::class) +internal object EmbeddedBlockWire { + const val OUTCOME_LOAD = "load" + const val OUTCOME_EMPTY = "empty" + const val OUTCOME_FAIL = "fail" + + 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 new file mode 100644 index 0000000..9a5927f --- /dev/null +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockEvents.kt @@ -0,0 +1,49 @@ +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, + private val isRevealAnimated: Boolean, + private val revealDurationMs: Int, +) : Event(surfaceId, viewTag) { + override fun getEventName(): String = EVENT_NAME + + // 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 { + putString("appearance", appearance) + putBoolean("animated", isRevealAnimated) + putInt("revealDurationMs", if (isRevealAnimated) revealDurationMs else 0) + } + + companion object { + const val EVENT_NAME = "topAppearanceChange" + } +} + +internal class BlockOutcomeEvent( + surfaceId: Int, + viewTag: Int, + private val outcome: String, + private val reason: String?, +) : Event(surfaceId, viewTag) { + override fun getEventName(): String = EVENT_NAME + + // 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 { + putString("outcome", outcome) + putString("reason", reason.orEmpty()) + } + + companion object { + 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 new file mode 100644 index 0000000..1644d40 --- /dev/null +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockHostView.kt @@ -0,0 +1,248 @@ +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.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: ((appearance: String, isRevealAnimated: Boolean, revealDurationMs: Int) -> Unit)? = null + + 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 + 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 + + 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() + } + } + + // 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 + } + + 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 + } + + 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, + ) + } + 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 = context, + placeSystemName = place, + timeoutMs = timeoutMs, + loadingStrategy = loadingStrategy, + animatesReveal = animatesReveal, + ) + blockView = block + + syncStandIns() + block.setHostVisible(hostVisible) + block.setListener( + object : MindboxEmbeddedBlockListener { + override fun onLoad(view: MindboxEmbeddedBlockView) { + onOutcome?.invoke(EmbeddedBlockWire.OUTCOME_LOAD, null) + } + + 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( + EmbeddedBlockWire.nameOf(appearance), + block.isRevealAnimated, + MindboxEmbeddedBlockView.REVEAL_ANIMATION_DURATION_MS.toInt(), + ) + } + + 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 + } +} 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..90a3884 --- /dev/null +++ b/android/src/main/java/com/mindboxsdk/embedded/MindboxEmbeddedBlockViewManager.kt @@ -0,0 +1,107 @@ +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.annotations.ReactProp +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, isRevealAnimated, revealDurationMs -> + dispatch(view) { surfaceId, tag -> AppearanceChangeEvent(surfaceId, tag, appearance, isRevealAnimated, revealDurationMs) } + } + view.onOutcome = { outcome, reason -> + dispatch(view) { surfaceId, tag -> BlockOutcomeEvent(surfaceId, tag, outcome, reason) } + } + } + + 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 + + @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) + } + + override fun getExportedCustomDirectEventTypeConstants(): MutableMap = mutableMapOf( + AppearanceChangeEvent.EVENT_NAME to mutableMapOf("registrationName" to "onAppearanceChange"), + BlockOutcomeEvent.EVENT_NAME to mutableMapOf("registrationName" to "onBlockOutcome"), + ) + + 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" + } +} 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' } } } 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 diff --git a/ios/EmbeddedBlock/EmbeddedBlockWire.swift b/ios/EmbeddedBlock/EmbeddedBlockWire.swift new file mode 100644 index 0000000..c4a2426 --- /dev/null +++ b/ios/EmbeddedBlock/EmbeddedBlockWire.swift @@ -0,0 +1,29 @@ +@_spi(Internal) import Mindbox + +enum EmbeddedBlockWire { + static let outcomeLoad = "load" + static let outcomeEmpty = "empty" + static let outcomeFail = "fail" + + 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" + } + } + + static var revealDurationMs: Int { + Int((MindboxEmbeddedBlockView.revealAnimationDuration * 1000).rounded()) + } +} diff --git a/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift b/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift new file mode 100644 index 0000000..a912330 --- /dev/null +++ b/ios/EmbeddedBlock/MindboxEmbeddedBlockHost.swift @@ -0,0 +1,110 @@ +import UIKit +@_spi(Internal) import Mindbox +import MindboxLogger + +@objc(MindboxEmbeddedBlockHost) +public final class MindboxEmbeddedBlockHost: NSObject { + private let onAppearance: (NSString, Bool, Int) -> Void + + 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: String, + animatesReveal: Bool, + onAppearance: @escaping (NSString, Bool, Int) -> Void, + onOutcome: @escaping (NSString, NSString?) -> Void) { + let timeout: TimeInterval? = timeoutMs == 0 ? nil : timeoutMs / 1000 + 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 { + Logger.common(message: "[EmbeddedBlock] A React Native block was created without a place system name and has nothing to resolve", + 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 + // 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, + self.blockView.isRevealAnimated, + EmbeddedBlockWire.revealDurationMs) + } + } + + @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 + blockView.setAppearanceObserver(nil) + blockView.delegate = nil + blockView.release() + } + + private static func makeStandIn() -> UIView { + let standIn = UIView() + standIn.backgroundColor = .clear + standIn.isUserInteractionEnabled = false + return standIn + } +} + +extension MindboxEmbeddedBlockHost: MindboxEmbeddedBlockViewDelegate { + public func mindboxEmbeddedBlockViewDidLoad(_ blockView: MindboxEmbeddedBlockView) { + guard !isTornDown else { return } + onOutcome(EmbeddedBlockWire.outcomeLoad as NSString, nil) + } + + 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 new file mode 100644 index 0000000..86c8f8c --- /dev/null +++ b/ios/EmbeddedBlock/MindboxEmbeddedBlockView.mm @@ -0,0 +1,314 @@ +#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 + +#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; + std::string _loadingStrategy; + BOOL _animatesReveal; + BOOL _hasPlaceholder; + BOOL _hasErrorView; + BOOL _isHostVisible; +} + ++ (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; + _animatesReveal = 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; + _loadingStrategy = next.loadingStrategy; + _animatesReveal = next.animatesReveal; + _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; + } + + // 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()) + 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]; + + self.contentView = _host.view; +} + +- (void)invalidate +{ + [self dropHost]; + _placeSystemName = ""; +} + +- (void)emitAppearance:(NSString *)appearance animated:(BOOL)animated revealDurationMs:(NSInteger)revealDurationMs +{ + if (!_eventEmitter) { + return; + } + + std::static_pointer_cast(_eventEmitter) + ->onAppearanceChange({.appearance = std::string([appearance UTF8String]), + .animated = static_cast(animated), + .revealDurationMs = static_cast(animated ? revealDurationMs : 0)}); +} + +- (void)emitOutcome:(NSString *)outcome reason:(NSString *_Nullable)reason +{ + if (!_eventEmitter) { + return; + } + + std::static_pointer_cast(_eventEmitter) + ->onBlockOutcome({.outcome = std::string([outcome UTF8String]), + .reason = std::string([(reason ?: @"") UTF8String])}); +} + +- (void)dropHost +{ + if (_host == nil) { + return; + } + + [_host tearDown]; + self.contentView = nil; + _host = nil; +} + +@end + +Class MindboxEmbeddedBlockViewCls(void) +{ + return MindboxEmbeddedBlockViewComponentView.class; +} + +#else // RCT_NEW_ARCH_ENABLED + +#import +#import + +// An RCTView: RCTViewManager writes the standard view props to it. +@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 onBlockOutcome; + +@end + +@implementation MindboxEmbeddedBlockPaperView { + MindboxEmbeddedBlockHost *_host; + NSString *_builtPlaceSystemName; + double _builtTimeoutMs; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + _hostVisible = YES; + _animatesReveal = YES; + } + + return self; +} + +- (void)dealloc +{ + [_host tearDown]; +} + +- (void)didSetProps:(NSArray *)changedProps +{ + [super didSetProps:changedProps]; + + 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 ?: @""; + _builtTimeoutMs = _timeoutMs; + + // 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 + 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) { + strongSelf.onBlockOutcome(@{@"outcome" : outcome, @"reason" : reason ?: @""}); + } + }]; + [_host setStandInsWithHasPlaceholder:_hasPlaceholder hasErrorView:_hasErrorView]; + [_host setHostVisible:_hostVisible]; + + 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 + +// React Native drops the Manager suffix: this registers MindboxEmbeddedBlockView, the name Fabric uses. +@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(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(onBlockOutcome, RCTDirectEventBlock) + +@end + +#endif // RCT_NEW_ARCH_ENABLED diff --git a/package.json b/package.json index d16806b..c1044f8 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "mindbox-sdk", - "version": "2.15.3", - "target-version": "2.15.3", + "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", @@ -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..169c23d --- /dev/null +++ b/src/MindboxEmbeddedBlock.tsx @@ -0,0 +1,270 @@ +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' + +// 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 + +type Appearance = 'placeholder' | 'content' | 'error' | 'collapsed' + +const APPEARANCES: Array = ['placeholder', 'content', 'error', 'collapsed'] + +type Outcome = 'load' | 'empty' | 'fail' + +const OUTCOMES: Array = ['load', 'empty', 'fail'] + +const IS_SUPPORTED = Platform.OS === 'ios' || Platform.OS === 'android' + +type Overlay = 'placeholder' | 'error' + +const REVEAL_EASING = Platform.OS === 'android' ? Easing.bezier(0.4, 0, 0.2, 1) : Easing.inOut(Easing.ease) + +export type MindboxEmbeddedBlockProps = { + /** + * 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 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, 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 while it loads; `automatic` by default. */ + loadingStrategy?: MindboxEmbeddedBlockLoadingStrategy + + /** + * Whether the SDK animates the content's appearance; `true` by default. Set `false` to animate the + * block's container yourself in `onLoad`. + */ + animatesReveal?: boolean + + /** Shown instead of the SDK's shimmer while the block loads. */ + placeholder?: React.ReactNode + + /** + * 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 + + /** Called when the content is shown. */ + onLoad?: () => void + + /** + * Called when the block collapses because the place has nothing to show or the data its targeting + * needs could not be fetched. + */ + onEmpty?: () => void + + /** Called when the block fails; it collapses or shows `error`. */ + onFail?: (reason: MindboxEmbeddedBlockFailReason) => void + + /** + * 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 + + style?: StyleProp +} + +/** + * Shows the Mindbox embedded block configured for a place in the admin panel. + * + * 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}`)} + * /> + * ``` + */ +export const MindboxEmbeddedBlock = (props: MindboxEmbeddedBlockProps) => + +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 + + 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.') + } + 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.`) + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + const warnedCreationValues = useRef(new Set()) + useEffect(() => { + 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.`) + } + warnIfIgnored('timeoutMs', timeoutMs, creationTimeoutMs) + warnIfIgnored('loadingStrategy', loadingStrategy, creationLoadingStrategy) + warnIfIgnored('animatesReveal', animatesReveal, creationAnimatesReveal) + }, [timeoutMs, creationTimeoutMs, loadingStrategy, creationLoadingStrategy, animatesReveal, creationAnimatesReveal, placeSystemName]) + + const callbacks = useRef({ onLoad, onEmpty, onFail }) + callbacks.current = { onLoad, onEmpty, onFail } + + const deliveredOutcome = useRef(null) + + const deliver = useCallback((outcome: Outcome, reason: string | null) => { + if (outcome === deliveredOutcome.current) { + return + } + 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 + } + }, []) + + useEffect(() => { + if (!IS_SUPPORTED) { + deliver('fail', MindboxEmbeddedBlockFailReason.internalError) + } + }, [deliver]) + + const reveal = useRef(new Animated.Value(1)).current + const overlayFade = useRef(new Animated.Value(1)).current + const [fadingOverlay, setFadingOverlay] = useState(null) + const fadeGeneration = useRef(0) + const shownAppearance = useRef(appearance) + + 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) + } + + 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] + ) + + 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 slotHeight = useMemo(() => reveal.interpolate({ inputRange: [0, 1], outputRange: [0, blockHeight] }), [reveal, blockHeight]) + + return ( + + {/* A native view of zero size never loads, so the block keeps its full height under a collapsed slot. */} + + {IS_SUPPORTED ? : null} + {overlay != null ? ( + + {overlay} + + ) : null} + + + ) +} + +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..08a57c7 --- /dev/null +++ b/src/MindboxEmbeddedBlockFailReason.ts @@ -0,0 +1,10 @@ +/** 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 SDK could not get the content: no network or config, no answer within `timeoutMs`, or the page did not load. */ + networkError: 'networkError', + + /** 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 new file mode 100644 index 0000000..aecf3d8 --- /dev/null +++ b/src/MindboxEmbeddedBlockLoadingStrategy.ts @@ -0,0 +1,13 @@ +/** What a block shows while it loads, set when the block is created. */ +export type MindboxEmbeddedBlockLoadingStrategy = 'automatic' | 'placeholder' | 'hidden' + +export const MindboxEmbeddedBlockLoadingStrategy = { + /** `placeholder` if the place has shown content on this device and has not come out empty since, otherwise `hidden`. */ + automatic: 'automatic', + + /** A placeholder at the block's height: the host's `placeholder` or the SDK's shimmer. */ + placeholder: 'placeholder', + + /** Zero height until the content is shown. */ + hidden: 'hidden', +} as const diff --git a/src/MindboxEmbeddedBlockNativeComponent.ts b/src/MindboxEmbeddedBlockNativeComponent.ts new file mode 100644 index 0000000..1b97277 --- /dev/null +++ b/src/MindboxEmbeddedBlockNativeComponent.ts @@ -0,0 +1,38 @@ +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' + +type AppearanceChangeEvent = Readonly<{ + appearance: string + animated: boolean + revealDurationMs: Int32 +}> + +type BlockOutcomeEvent = Readonly<{ + outcome: string + reason: string +}> + +export interface NativeProps extends ViewProps { + placeSystemName?: string + + blockHeight?: Double + + timeoutMs?: Double + + loadingStrategy?: string + + animatesReveal?: WithDefault + + hasPlaceholder?: WithDefault + + hasErrorView?: WithDefault + + hostVisible?: WithDefault + + onAppearanceChange?: DirectEventHandler + + onBlockOutcome?: 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..9089c8d --- /dev/null +++ b/src/__tests__/MindboxEmbeddedBlock.test.tsx @@ -0,0 +1,574 @@ +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' +import { MindboxEmbeddedBlockFailReason } from '../MindboxEmbeddedBlockFailReason' +import { MindboxEmbeddedBlockLoadingStrategy } from '../MindboxEmbeddedBlockLoadingStrategy' + +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, reveal: { animated: boolean; revealDurationMs: number } = { animated: false, revealDurationMs: 0 }) => { + act(() => { + nativeProps(renderer).onAppearanceChange({ nativeEvent: { appearance, ...reveal } }) + }) +} + +const reportOutcome = (renderer: ReactTestRenderer, outcome: string, reason = '') => { + act(() => { + nativeProps(renderer).onBlockOutcome({ nativeEvent: { outcome, reason } }) + }) +} + +const slotHeight = (renderer: ReactTestRenderer) => { + const frame = renderer.root.findAllByType(asType(View))[0] + return StyleSheet.flatten(frame.props.style).height +} + +const nativeBlockHeight = (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(placeholderBlock()) + + expect(slotHeight(renderer)).toBe(104) + + reportAppearance(renderer, 'collapsed') + + expect(slotHeight(renderer)).toBe(0) + }) + + it('resizes a live block in place when the height changes', () => { + const renderer = render(placeholderBlock({ height: 160 })) + + update(renderer, placeholderBlock({ height: 80 })) + + expect(slotHeight(renderer)).toBe(80) + expect(nativeBlockHeight(renderer)).toBe(80) + expect(nativeProps(renderer).blockHeight).toBe(80) + }) + + 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(placeholderBlock({ placeSystemName: ' stories ' })) + + update(renderer, placeholderBlock({ placeSystemName: ' stories ' })) + + 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(placeholderBlock({ placeSystemName: '' })) + + update(renderer, placeholderBlock({ placeSystemName: '' })) + + 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(placeholderBlock({ placeSystemName: ' ' })) + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('without a place system name') + warn.mockRestore() + }) + + 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(placeholderBlock({ placeSystemName: '', onEmpty, onFail })) + + expect(warn.mock.calls[0][0]).toContain('reports onEmpty') + + reportAppearance(renderer, 'collapsed') + reportOutcome(renderer, 'empty') + + expect(onEmpty).toHaveBeenCalledTimes(1) + expect(onFail).not.toHaveBeenCalled() + expect(slotHeight(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(placeholderBlock({ height })) + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('reserves no space') + expect(slotHeight(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(placeholderBlock({ placeholder: 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(placeholderBlock()) + + expect(nativeProps(renderer).timeoutMs).toBe(0) + }) + + it('sends the timeout it was created with, in milliseconds', () => { + 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(placeholderBlock({ timeoutMs: 5000 })) + + 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(placeholderBlock({ placeholder: 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') + }) + + 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) + + reportOutcome(renderer, 'fail', 'networkError') + + expect(onFail).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(slotHeight(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') + + expect(onFail).toHaveBeenCalledWith(MindboxEmbeddedBlockFailReason.networkError) + }) + + 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(placeholderBlock()) + + reportAppearance(renderer, 'collapsed') + reportAppearance(renderer, 'sideways') + + expect(slotHeight(renderer)).toBe(0) + }) + + it('builds a different place as a different block, with nothing remembered', () => { + const onLoad = jest.fn() + const renderer = render(placeholderBlock({ onLoad })) + + reportOutcome(renderer, 'load') + update(renderer, placeholderBlock({ placeSystemName: 'banner', onLoad })) + reportOutcome(renderer, 'load') + + expect(onLoad).toHaveBeenCalledTimes(2) + }) + + 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 }) + }) + + it('starts automatic and animated when the host says nothing', () => { + const renderer = render() + + expect(nativeProps(renderer)).toMatchObject({ loadingStrategy: 'automatic', animatesReveal: true }) + }) + + 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(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(slotHeight(renderer)).toBe(0) + expect(nativeBlockHeight(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(slotHeight(renderer)).toBe(0) + expect(nativeBlockHeight(renderer)).toBe(104) + expect(renderer.root.findAllByType(asType(Text))).toHaveLength(0) + + reportAppearance(renderer, 'placeholder') + + expect(slotHeight(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(slotHeight(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(slotHeight(renderer)).toBe(0) + + tick(125) + + expect(slotHeight(renderer)).toBeGreaterThan(30) + expect(slotHeight(renderer)).toBeLessThan(74) + + tick(125) + + expect(slotHeight(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(slotHeight(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(slotHeight(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(slotHeight(renderer)).toBe(104) + + tick(125) + + expect(slotHeight(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(slotHeight(renderer)).toBe(0) + + tick(250) + + expect(slotHeight(renderer)).toBe(0) + }) + + 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 = slotHeight(renderer) + expect(midway).toBeGreaterThan(0) + expect(midway).toBeLessThan(104) + + reportAppearance(renderer, appearance) + + expect(slotHeight(renderer)).toBe(104) + + tick(60) + + expect(slotHeight(renderer)).toBe(104) + }) + + describe('the host overlay under the reveal', () => { + 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..9cf6b71 --- /dev/null +++ b/src/__tests__/MindboxEmbeddedBlock.unsupported.test.tsx @@ -0,0 +1,50 @@ +import React from 'react' +import { StyleSheet, View } from 'react-native' +import { act, create } from 'react-test-renderer' +import type { ReactTestRenderer } from 'react-test-renderer' + +// `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, +})) + +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 slotHeight = (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(slotHeight(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/__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) + }) +}) 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..7ac2ec5 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) @@ -493,3 +498,11 @@ export default MindboxSdk export { LogLevel } from './LogLevel' export { InAppCallback, CopyPayloadInAppCallback, EmptyInAppCallback, UrlInAppCallback } from './InAppCallback' + +export { MindboxEmbeddedBlock } from './MindboxEmbeddedBlock' + +export type { MindboxEmbeddedBlockProps } from './MindboxEmbeddedBlock' + +export { MindboxEmbeddedBlockFailReason } from './MindboxEmbeddedBlockFailReason' + +export { MindboxEmbeddedBlockLoadingStrategy } from './MindboxEmbeddedBlockLoadingStrategy' diff --git a/src/react-native-children.d.ts b/src/react-native-children.d.ts new file mode 100644 index 0000000..ae505a7 --- /dev/null +++ b/src/react-native-children.d.ts @@ -0,0 +1,13 @@ +// `@types/react-native` 0.62.13 lacks `children` on `ViewProps` and `TextProps`; delete this file with that dependency. + +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..fce0e82 --- /dev/null +++ b/src/react-native-codegen.d.ts @@ -0,0 +1,30 @@ +// 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' + + export type Double = number + export type Float = number + export type Int32 = number + export type UnsafeMixed = unknown + + export type WithDefault = Type | undefined + + export type DirectEventHandler = (event: NativeSyntheticEvent) => void + + 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/src/types/InitializationData.ts b/src/types/InitializationData.ts index 46789ac..f6f83c0 100644 --- a/src/types/InitializationData.ts +++ b/src/types/InitializationData.ts @@ -12,4 +12,17 @@ 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. 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 } 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==