diff --git a/AGENTS.md b/AGENTS.md index 2e0b1b2..46c4fff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,7 @@ cd example && bun install - Keep PRs small and scoped to one objective. - If you change public APIs, update `README.md` and any types. - **Docs (`docs/`)**: When you add, change, or remove public API, setup steps, or user-facing behavior, create, update, or delete the relevant pages under `docs/docs/` so the Docusaurus docs stay in sync. Examples: new hook option → `docs/docs/api/use-payment-checkout.md`; plugin config change → `docs/docs/setup/expo-plugin.md`; new guide → add under `docs/docs/guides/` and reference in `docs/sidebars.ts`. All docs content is in English. -- **Code snippets** in `README.md` and `docs/docs/` must compile (`bun run check:docs`): include their imports, and wrap pay button `onPress` handlers with `callback()`. Mark a snippet that cannot compile on its own (type listings, short fragments, server code) with `no-check` after the language, as in ` ```ts no-check `. Snippets that render `ApplePayButton` or `GooglePayButton` cannot be `no-check`. +- **Code snippets** in `README.md` and `docs/docs/` must compile (`bun run check:docs`): include their imports. Mark a snippet that cannot compile on its own (type listings, short fragments, server code) with `no-check` after the language, as in ` ```ts no-check `. Snippets that render `ApplePayButton` or `GooglePayButton` cannot be `no-check`. - If you touch native code, validate both iOS and Android paths. - Avoid drive-by refactors and formatting-only changes. diff --git a/CHANGELOG.md b/CHANGELOG.md index 81c97f5..03a5f01 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,12 @@ All notable changes to this project are documented in this file. still accepts every card type on Android; `'3DS'` and `'EMV'` have no effect there. The button and the readiness check leave credit cards out too. +- **`disabled` on `ApplePayButton` and `GooglePayButton`** ignores taps, for example while a + payment is in progress. The button looks the same: Apple's guidelines ask not to make the Apple + Pay button appear unavailable, and Google's do not allow changing the Google Pay button's color. +- **`ApplePayButtonType`, `ApplePayButtonStyle`, `GooglePayButtonType`, `GooglePayButtonTheme`, + `ApplePayButtonProps` and `GooglePayButtonProps` are exported.** + ### Changed - **`usePaymentCheckout` no longer treats a cancel as an error.** When the user closes the sheet, @@ -122,6 +128,14 @@ All notable changes to this project are documented in this file. - **iOS: `HybridPaymentHandler.openPaymentSetup()`** opens Wallet so the user can add a card, for a "Set up Apple Pay" button (`ApplePayButton` with `buttonType="setUp"`). It does nothing on Android. +- **The pay buttons take a plain function as `onPress`: remove `callback()`.** `ApplePayButton` + and `GooglePayButton` are now React components around the native views, so + `onPress={callback(handlePay)}` becomes `onPress={handlePay}`, and the `react-native-nitro-modules` + import can go. A wrapped `onPress` still works, but no longer type-checks, and logs a warning in + development. The props are `ViewProps` plus the button's own; `hybridRef` is gone. +- **Each pay button renders nothing on the other platform,** with a warning in development, instead + of failing, since that native view does not exist there. + ### Deprecated - **`PaymentResult.transactionId`.** It is a random ID generated on the device for each successful @@ -130,6 +144,13 @@ All notable changes to this project are documented in this file. ### Fixed +- **iOS: `ApplePayButton` keeps its `PKPaymentButton` across re-renders.** Every prop update + removed the button and created a new one, so an `onPress` with a new identity on each render + rebuilt it on every parent re-render. It is now rebuilt only when `buttonType` or `buttonStyle` + changes. +- **Android: `GooglePayButton`'s `radius` is in dp, as documented.** It was passed to Google Pay as + pixels, so corners were about a third of the requested size on a typical phone. Apps that + enlarged `radius` to compensate should set it back. - **Android: `supportedNetworks` limits the cards the payer can choose.** Android ignored it and always offered Visa, Mastercard, Amex and Discover, so a merchant whose gateway refuses Amex still received Amex tokens, and JCB or Interac could not be enabled. The payment request, the diff --git a/README.md b/README.md index cf4ae24..56d21ed 100644 --- a/README.md +++ b/README.md @@ -190,7 +190,6 @@ import { formatAmount, } from '@gmisoftware/react-native-pay' import { Platform, View, Text, Button, ActivityIndicator } from 'react-native' -import { callback } from 'react-native-nitro-modules' function CheckoutScreen() { const { @@ -286,7 +285,7 @@ function CheckoutScreen() { ) : ( @@ -294,7 +293,7 @@ function CheckoutScreen() { buttonType="buy" theme="dark" radius={4} - onPress={callback(handlePay)} + onPress={handlePay} style={{ width: '100%', height: 48 }} /> ) @@ -565,7 +564,7 @@ iOS only: opens Wallet so the user can add a card. Call it from an `ApplePayButt ### Button Components -Both buttons are Nitro views, so `onPress` must be wrapped with `callback()` from `react-native-nitro-modules`. A bare function does not reach the native button, and tapping it does nothing. +Each button renders nothing on the other platform and, in development, logs a warning. `disabled` makes the button ignore taps, for example while a payment is in progress. It does not dim the button: Apple's guidelines ask not to make the Apple Pay button appear unavailable, and Google's do not allow changing the Google Pay button's color. #### `ApplePayButton` (iOS) @@ -592,7 +591,8 @@ interface ApplePayButtonProps { buttonStyle: "white" | "whiteOutline" | "black"; - onPress?: () => void; // wrap with callback() from react-native-nitro-modules + onPress?: () => void; + disabled?: boolean; // ignores taps while true style?: ViewStyle; } ``` @@ -601,7 +601,6 @@ interface ApplePayButtonProps { ```tsx import { ApplePayButton } from "@gmisoftware/react-native-pay"; -import { callback } from "react-native-nitro-modules"; const handlePayment = async () => { // Call startPayment() from usePaymentCheckout here @@ -610,7 +609,7 @@ const handlePayment = async () => { ``` @@ -642,7 +641,8 @@ interface GooglePayButtonProps { googlePayAllowedAuthMethods?: string[]; // as PaymentRequest.googlePayAllowedAuthMethods merchantCapabilities?: string[]; // as PaymentRequest.merchantCapabilities - onPress?: () => void; // wrap with callback() from react-native-nitro-modules + onPress?: () => void; + disabled?: boolean; // ignores taps while true style?: ViewStyle; } ``` @@ -651,7 +651,6 @@ interface GooglePayButtonProps { ```tsx import { GooglePayButton } from "@gmisoftware/react-native-pay"; -import { callback } from "react-native-nitro-modules"; const handlePayment = async () => { // Call startPayment() from usePaymentCheckout here @@ -661,7 +660,7 @@ const handlePayment = async () => { buttonType="buy" theme="dark" radius={8} - onPress={callback(handlePayment)} + onPress={handlePayment} style={{ width: '100%', height: 48 }} /> ``` @@ -966,7 +965,6 @@ import { GooglePayButton, } from '@gmisoftware/react-native-pay' import { Platform } from 'react-native' -import { callback } from 'react-native-nitro-modules' // 1. Check availability, against the environment you pay in const { isSupported } = await HybridPaymentHandler.payServiceStatus({ @@ -1007,7 +1005,7 @@ const handlePayment = async () => { } } -// 4. Render the button. onPress must be wrapped with callback(). +// 4. Render the button. function PaymentButton() { if (!isSupported) return null @@ -1015,13 +1013,13 @@ function PaymentButton() { ) : ( ) } diff --git a/docs/docs/api/components.md b/docs/docs/api/components.md index cfe9052..90f34f7 100644 --- a/docs/docs/api/components.md +++ b/docs/docs/api/components.md @@ -1,6 +1,6 @@ # Button components -Native payment buttons: **ApplePayButton** (iOS) and **GooglePayButton** (Android). Use the one that matches the platform; the library does not render both on the same screen. +Native payment buttons: **ApplePayButton** (iOS) and **GooglePayButton** (Android). Use the one that matches the platform. On the other platform a button renders nothing and, in development, logs a warning. ## ApplePayButton (iOS only) @@ -12,7 +12,8 @@ Renders the system Apple Pay button. Only available on iOS. |------|------|----------|-------------| | `buttonType` | `ApplePayButtonType` | Yes | Button label type. | | `buttonStyle` | `ApplePayButtonStyle` | Yes | Visual style. | -| `onPress` | `() => void`, wrapped with `callback()` | No | Called when the user taps the button. Must be wrapped, see [Nitro and onPress](#nitro-and-onpress). | +| `onPress` | `() => void` | No | Called when the user taps the button. | +| `disabled` | `boolean` | No | Ignores taps while `true`. See [Disabled buttons](#disabled-buttons). | | `style` | `ViewStyle` | No | Layout/style (e.g. width, height). | **ApplePayButtonType:** @@ -25,7 +26,6 @@ Renders the system Apple Pay button. Only available on iOS. ```tsx import { ApplePayButton } from '@gmisoftware/react-native-pay' -import { callback } from 'react-native-nitro-modules' const handlePayment = async () => { // Call startPayment() from usePaymentCheckout here @@ -34,15 +34,11 @@ const handlePayment = async () => { ``` -### Nitro and onPress - -`ApplePayButton` is a Nitro view, so `onPress` must be wrapped with `callback()` from `react-native-nitro-modules`. A bare function does not reach the native button, and tapping it does nothing. See [Troubleshooting: Nitro callback for onPress](/docs/troubleshooting#nitro-callback-for-onpress). - --- ## GooglePayButton (Android only) @@ -55,11 +51,12 @@ Renders the Google Pay button. Only available on Android. |------|------|----------|-------------| | `buttonType` | `GooglePayButtonType` | Yes | Button label type. | | `theme` | `'dark' \| 'light'` | Yes | Button theme. | -| `radius` | `number` | No | Corner radius in dp. | +| `radius` | `number` | No | Corner radius in dp, like other React Native sizes. | | `supportedNetworks` | `string[]` | No | The card networks your payment accepts, as in `PaymentRequest.supportedNetworks`. Default: `visa`, `mastercard`, `amex`, `discover`. | | `googlePayAllowedAuthMethods` | `string[]` | No | As in `PaymentRequest.googlePayAllowedAuthMethods`. Default: both. | | `merchantCapabilities` | `string[]` | No | As in `PaymentRequest.merchantCapabilities`. `'Debit'` without `'Credit'` leaves credit cards out. Default: every card type. | -| `onPress` | `() => void`, wrapped with `callback()` | No | Called when the user taps the button. Must be wrapped, see [Nitro and onPress](#nitro-and-onpress). | +| `onPress` | `() => void` | No | Called when the user taps the button. | +| `disabled` | `boolean` | No | Ignores taps while `true`. See [Disabled buttons](#disabled-buttons). | | `style` | `ViewStyle` | No | Layout/style (e.g. width, height). | The button can show the payer's card, so give it the same `supportedNetworks`, `googlePayAllowedAuthMethods` and `merchantCapabilities` as the payment, under the same names. Otherwise it may show a card the payment then refuses. With `usePaymentCheckout`, pass them from `paymentRequest`. With an unknown network, auth method or merchant capability, the button keeps its previous configuration, or does not appear on the first render, and logs an error in debug builds. @@ -71,7 +68,6 @@ The button can show the payer's card, so give it the same `supportedNetworks`, ` ```tsx import { GooglePayButton } from '@gmisoftware/react-native-pay' -import { callback } from 'react-native-nitro-modules' const handlePayment = async () => { // Call startPayment() from usePaymentCheckout here @@ -82,14 +78,38 @@ const handlePayment = async () => { theme="dark" radius={8} supportedNetworks={['visa', 'mastercard']} - onPress={callback(handlePayment)} + onPress={handlePayment} style={{ width: '100%', height: 48 }} /> ``` -### Nitro and onPress +--- + +## Disabled buttons -Same as Apple: `onPress` must be wrapped, as in `onPress={callback(handlePayment)}`. See [Troubleshooting: Nitro callback for onPress](/docs/troubleshooting#nitro-callback-for-onpress). +With `disabled`, the button ignores taps, for example while a payment is in progress. It looks the same as an enabled button. Apple's [Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/apple-pay) ask you not to make the Apple Pay button appear unavailable, and Google's [brand guidelines](https://developers.google.com/pay/api/android/guides/brand-guidelines) do not allow changing the Google Pay button's color. If the payment cannot start yet, for example before the payer picks a size, Apple suggests keeping the button enabled and explaining the problem after the tap. + +```tsx +import { ApplePayButton, usePaymentCheckout } from '@gmisoftware/react-native-pay' + +function PayButton() { + const { startPayment, isProcessing } = usePaymentCheckout({ + merchantName: 'Your Store', + currencyCode: 'USD', + countryCode: 'US', + }) + + return ( + + ) +} +``` --- @@ -100,7 +120,6 @@ Render one button per platform: ```tsx import { Platform } from 'react-native' import { ApplePayButton, GooglePayButton } from '@gmisoftware/react-native-pay' -import { callback } from 'react-native-nitro-modules' const handlePayment = async () => { // Call startPayment() from usePaymentCheckout here @@ -109,9 +128,9 @@ const handlePayment = async () => { const style = { width: '100%', height: 48 } as const {Platform.OS === 'ios' ? ( - + ) : ( - + )} ``` diff --git a/docs/docs/examples.md b/docs/docs/examples.md index abee8f7..89d2e4e 100644 --- a/docs/docs/examples.md +++ b/docs/docs/examples.md @@ -13,7 +13,6 @@ import { GooglePayButton, usePaymentCheckout, } from '@gmisoftware/react-native-pay' -import { callback } from 'react-native-nitro-modules' const { isSupported, @@ -51,7 +50,7 @@ const handlePayment = async () => { ) : ( @@ -59,7 +58,7 @@ const handlePayment = async () => { buttonType="buy" theme="dark" radius={8} - onPress={callback(handlePayment)} + onPress={handlePayment} style={{ width: '100%', height: 56 }} /> )} @@ -71,7 +70,6 @@ const handlePayment = async () => { - **Status** — Check whether the device can make payments or only set up cards. - **Cart UI** — Add/clear items and display total. - **Result handling** — Success and error messages; reset and clear cart after success. -- **Nitro `callback`** — Buttons use `callback(handlePayment)` (see [Troubleshooting: Nitro callback for onPress](/docs/troubleshooting#nitro-callback-for-onpress)). ## Run the example @@ -102,10 +100,10 @@ Use the checkout screen in the example app as a reference for: 2. Shows a loading state while `isCheckingStatus` is true. 3. Renders “Quick Add” buttons that call `addItems` or `addItem`. 4. Displays the cart (items + total) and a “Clear” action. -5. Renders **ApplePayButton** on iOS and **GooglePayButton** on Android with `callback(handlePayment)`. +5. Renders **ApplePayButton** on iOS and **GooglePayButton** on Android with `onPress={handlePayment}`. 6. On successful payment, shows an alert and calls `reset()` and `clearItems()`. -Copy these patterns into your app: config setup, cart handling, button usage, and native-safe `onPress` handlers. +Copy these patterns into your app: config setup, cart handling, and button usage. ## Plugin config in the example diff --git a/docs/docs/guides/availability.md b/docs/docs/guides/availability.md index c9b507d..4ad67ed 100644 --- a/docs/docs/guides/availability.md +++ b/docs/docs/guides/availability.md @@ -29,7 +29,6 @@ In the example below, the checkout screen owns the hook and the cart, and `Walle ```tsx import { useEffect } from 'react' import { AppState, Button, Platform, View } from 'react-native' -import { callback } from 'react-native-nitro-modules' import { ApplePayButton, GooglePayButton, @@ -80,7 +79,7 @@ function WalletButton({ checkout }: { checkout: UsePaymentCheckoutReturn }) { ) } @@ -89,13 +88,13 @@ function WalletButton({ checkout }: { checkout: UsePaymentCheckoutReturn }) { ) : ( HybridPaymentHandler.openPaymentSetup())} + onPress={() => HybridPaymentHandler.openPaymentSetup()} /> ) } diff --git a/docs/docs/guides/manual-flow.md b/docs/docs/guides/manual-flow.md index 5b2c31f..4e26354 100644 --- a/docs/docs/guides/manual-flow.md +++ b/docs/docs/guides/manual-flow.md @@ -62,12 +62,11 @@ To charge the token before the Apple Pay sheet closes, pass `startPayment(paymen ## 4. Render the button -Use the platform-specific button, and pass it `status.isSupported` from step 1 so it stays hidden when payments are unavailable. Its `onPress` must be wrapped with `callback()` from `react-native-nitro-modules`, or the tap does nothing: +Use the platform-specific button, and pass it `status.isSupported` from step 1 so it stays hidden when payments are unavailable: ```tsx import { Platform } from 'react-native' import { ApplePayButton, GooglePayButton } from '@gmisoftware/react-native-pay' -import { callback } from 'react-native-nitro-modules' function PaymentButton({ isSupported, @@ -82,13 +81,13 @@ function PaymentButton({ ) : ( ) } diff --git a/docs/docs/guides/server-processing.md b/docs/docs/guides/server-processing.md index 748f43e..5cdcdb2 100644 --- a/docs/docs/guides/server-processing.md +++ b/docs/docs/guides/server-processing.md @@ -32,7 +32,7 @@ function useOrderPayment() { return clearItems }, [addItem, clearItems]) - // Pass this to the pay button's onPress, wrapped with callback(). + // Pass this to the pay button's onPress. return async () => { const result = await startPayment() if (result?.status === 'success' && result.token) { diff --git a/docs/docs/integrations/przelewy24.md b/docs/docs/integrations/przelewy24.md index 1ce70e1..bf9c323 100644 --- a/docs/docs/integrations/przelewy24.md +++ b/docs/docs/integrations/przelewy24.md @@ -65,7 +65,6 @@ import { GooglePayButton, usePaymentCheckout, } from '@gmisoftware/react-native-pay' -import {callback} from 'react-native-nitro-modules' export function CheckoutWithPrzelewy24() { const {startPayment, isSupported, isProcessing} = usePaymentCheckout({ @@ -104,7 +103,7 @@ export function CheckoutWithPrzelewy24() { ) : ( @@ -112,7 +111,7 @@ export function CheckoutWithPrzelewy24() { buttonType="buy" theme="dark" radius={4} - onPress={callback(onPayPress)} + onPress={onPayPress} style={{width: '100%', height: 48}} /> )} diff --git a/docs/docs/quick-start.md b/docs/docs/quick-start.md index 655a5b5..4eb038a 100644 --- a/docs/docs/quick-start.md +++ b/docs/docs/quick-start.md @@ -53,7 +53,6 @@ import { formatAmount, } from '@gmisoftware/react-native-pay' import { Platform, View, Text, Button, ActivityIndicator } from 'react-native' -import { callback } from 'react-native-nitro-modules' function CheckoutScreen() { const { @@ -111,9 +110,9 @@ function CheckoutScreen() { ) : ( Platform.OS === 'ios' ? ( - + ) : ( - + ) )} @@ -123,17 +122,13 @@ function CheckoutScreen() { If you are integrating with Przelewy24, follow the provider cookbook: [Przelewy24](/docs/integrations/przelewy24). -## 5. Wrap `onPress` with `callback()` - -`ApplePayButton` and `GooglePayButton` are Nitro views, so their `onPress` must be wrapped with `callback()` from `react-native-nitro-modules`, as in the screen above. A bare function does not reach the native button, and tapping it does nothing. See [Troubleshooting: Nitro callback for onPress](/docs/troubleshooting#nitro-callback-for-onpress). - -## 6. Run and test +## 5. Run and test - **iOS:** Real device with a card in Wallet; Simulator has limited support. - **Android:** Real device or emulator with Google Play Services; add a card in Google Pay. - For **Google Pay**, configure `googlePayMerchantId`, `googlePayEnvironment`, `googlePayGateway`, and `googlePayGatewayMerchantId` when you move to a real gateway (see [Android setup](/docs/setup/android-google-pay) and [API: usePaymentCheckout](/docs/api/use-payment-checkout)). -## 7. Before you ship +## 6. Before you ship - [ ] `react-native-nitro-modules` and `@gmisoftware/react-native-pay` installed. - [ ] Native config done (Expo plugin + prebuild, or bare iOS entitlements + Android manifest). diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 16f4336..aca3a9e 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -113,27 +113,26 @@ adb logcat -s HybridPaymentHandler HybridGooglePayButton Payment errors don't depend on logs: they reach your app in `result.error`. -## Nitro callback for onPress +## Pay button `onPress` and `callback()` -`ApplePayButton` and `GooglePayButton` are Nitro views. Nitro passes a function prop to native code only when it is wrapped with `callback()` from `react-native-nitro-modules`, so `onPress` must always be wrapped. A bare function does not reach the native button: tapping it does nothing, and TypeScript reports `Type '() => Promise' is not assignable to type 'NitroViewWrappedCallback<...>'`. +`ApplePayButton` and `GooglePayButton` take a plain function as `onPress`. Earlier versions required wrapping it with `callback()` from `react-native-nitro-modules`. That is no longer needed: remove the wrapper, and the `callback` import if nothing else uses it. ```tsx import { Platform } from 'react-native' import { ApplePayButton, GooglePayButton } from '@gmisoftware/react-native-pay' -import { callback } from 'react-native-nitro-modules' const handlePay = async () => { // Call startPayment() from usePaymentCheckout here } {Platform.OS === 'ios' ? ( - + ) : ( - + )} ``` -Use this pattern anywhere you pass handlers to `ApplePayButton` or `GooglePayButton`. +A wrapped `onPress` still works, but TypeScript reports `Type 'NitroViewWrappedCallback<...>' is not assignable to type '() => void'`, and development builds log a warning. ## Build / native module issues diff --git a/example/app/(tabs)/index.tsx b/example/app/(tabs)/index.tsx index 52a8833..e6620df 100644 --- a/example/app/(tabs)/index.tsx +++ b/example/app/(tabs)/index.tsx @@ -17,7 +17,6 @@ import { HybridPaymentHandler, usePaymentCheckout, } from "@gmisoftware/react-native-pay"; -import { callback } from "react-native-nitro-modules"; // Rehearses the release checklist: // https://gmi-software.github.io/react-native-pay/docs/guides/testing#release-checklist @@ -307,16 +306,14 @@ export default function TabOneScreen() { ) : ( - HybridPaymentHandler.openPaymentSetup(), - )} + onPress={() => HybridPaymentHandler.openPaymentSetup()} style={styles.payButton} /> ) @@ -329,7 +326,7 @@ export default function TabOneScreen() { supportedNetworks={paymentRequest.supportedNetworks} googlePayAllowedAuthMethods={paymentRequest.googlePayAllowedAuthMethods} merchantCapabilities={paymentRequest.merchantCapabilities} - onPress={callback(handlePayment)} + onPress={handlePayment} style={styles.payButton} /> )} diff --git a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt index 4e48a1a..51d11d9 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt @@ -4,6 +4,7 @@ import android.content.Context import com.google.android.gms.wallet.button.ButtonConstants import com.google.android.gms.wallet.button.ButtonOptions import com.google.android.gms.wallet.button.PayButton +import kotlin.math.roundToInt /** * Factory for creating and configuring Google Pay buttons @@ -30,7 +31,7 @@ object GooglePayButtonFactory { .apply { radius?.let { r -> if (r >= 0) { - setCornerRadius(r.toInt()) + setCornerRadius(cornerRadiusPx(r, context.resources.displayMetrics.density)) } } } @@ -45,6 +46,13 @@ object GooglePayButtonFactory { return button } + /** + * Converts the React Native radius (dp) to the px that [ButtonOptions] takes + */ + internal fun cornerRadiusPx(radiusDp: Double, density: Float): Int { + return (radiusDp * density).roundToInt() + } + /** * Maps GooglePayButtonType to ButtonConstants */ diff --git a/package/android/src/test/java/com/margelo/nitro/pay/GooglePayButtonFactoryTest.kt b/package/android/src/test/java/com/margelo/nitro/pay/GooglePayButtonFactoryTest.kt new file mode 100644 index 0000000..a772efc --- /dev/null +++ b/package/android/src/test/java/com/margelo/nitro/pay/GooglePayButtonFactoryTest.kt @@ -0,0 +1,20 @@ +package com.margelo.nitro.pay + +import org.junit.Assert.assertEquals +import org.junit.Test + +class GooglePayButtonFactoryTest { + + @Test + fun cornerRadiusPx_scalesDpByTheScreenDensity() { + assertEquals(8, GooglePayButtonFactory.cornerRadiusPx(8.0, 1f)) + assertEquals(24, GooglePayButtonFactory.cornerRadiusPx(8.0, 3f)) + assertEquals(0, GooglePayButtonFactory.cornerRadiusPx(0.0, 3f)) + } + + @Test + fun cornerRadiusPx_roundsToTheNearestPixel() { + assertEquals(11, GooglePayButtonFactory.cornerRadiusPx(4.0, 2.625f)) + assertEquals(10, GooglePayButtonFactory.cornerRadiusPx(3.5, 2.75f)) + } +} diff --git a/package/ios/HybridApplePayButton.swift b/package/ios/HybridApplePayButton.swift index d38b993..23cd7eb 100644 --- a/package/ios/HybridApplePayButton.swift +++ b/package/ios/HybridApplePayButton.swift @@ -16,6 +16,9 @@ class HybridApplePayButton: HybridApplePayButtonSpec { // Internal state private var paymentButton: PKPaymentButton? + /// The type and style `paymentButton` was built with: a change needs a new button + private var builtType: ApplePayButtonType? + private var builtStyle: ApplePayButtonStyle? override init() { super.init() @@ -23,6 +26,8 @@ class HybridApplePayButton: HybridApplePayButtonSpec { } func afterUpdate() { + // onPress is read at tap time, so only the type and style need a new button. + guard buttonType != builtType || buttonStyle != builtStyle else { return } setupButton() } @@ -41,6 +46,8 @@ class HybridApplePayButton: HybridApplePayButtonSpec { ) paymentButton = button + builtType = buttonType + builtStyle = buttonStyle // Add to view view.addSubview(button) diff --git a/package/ios/Tests/HybridApplePayButtonTests.swift b/package/ios/Tests/HybridApplePayButtonTests.swift new file mode 100644 index 0000000..5a416fc --- /dev/null +++ b/package/ios/Tests/HybridApplePayButtonTests.swift @@ -0,0 +1,64 @@ +import PassKit +import XCTest +@testable import NitroPay + +final class HybridApplePayButtonTests: XCTestCase { + + private func paymentButtons(in button: HybridApplePayButton) -> [PKPaymentButton] { + button.view.subviews.compactMap { $0 as? PKPaymentButton } + } + + func testKeepsTheButtonWhenOnlyOnPressChanges() { + let button = HybridApplePayButton() + button.afterUpdate() + let initial = paymentButtons(in: button) + + button.onPress = {} + button.afterUpdate() + button.onPress = {} + button.afterUpdate() + + XCTAssertEqual(initial.count, 1) + XCTAssertEqual(paymentButtons(in: button).count, 1) + XCTAssertTrue(paymentButtons(in: button).first === initial.first) + } + + func testRebuildsTheButtonWhenTheTypeOrStyleChanges() { + let button = HybridApplePayButton() + let initial = paymentButtons(in: button).first + + button.buttonType = .setup + button.afterUpdate() + let afterType = paymentButtons(in: button).first + + button.buttonStyle = .white + button.afterUpdate() + let afterStyle = paymentButtons(in: button).first + + XCTAssertFalse(afterType === initial) + XCTAssertFalse(afterStyle === afterType) + XCTAssertEqual(paymentButtons(in: button).count, 1) + } + + func testTapCallsTheLatestOnPress() throws { + let button = HybridApplePayButton() + var calls: [String] = [] + button.onPress = { calls.append("first") } + button.afterUpdate() + button.onPress = { calls.append("second") } + button.afterUpdate() + + // The test bundle has no host app, so no UIApplication delivers + // sendActions(for:). Perform the kept button's registered action instead. + let paymentButton = try XCTUnwrap(paymentButtons(in: button).first) + let actions = try XCTUnwrap( + paymentButton.actions(forTarget: button, forControlEvent: .touchUpInside) + ) + XCTAssertEqual(actions.count, 1) + for action in actions { + _ = (button as AnyObject).perform(NSSelectorFromString(action)) + } + + XCTAssertEqual(calls, ["second"]) + } +} diff --git a/package/jest.config.js b/package/jest.config.js index 4e5face..da278ca 100644 --- a/package/jest.config.js +++ b/package/jest.config.js @@ -2,7 +2,7 @@ module.exports = { preset: '@react-native/jest-preset', testEnvironment: 'node', roots: ['/src'], - testMatch: ['**/__tests__/**/*.test.ts'], + testMatch: ['**/__tests__/**/*.test.ts?(x)'], setupFilesAfterEnv: ['/jest.setup.js'], moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'], clearMocks: true, diff --git a/package/src/components/ApplePayButton.tsx b/package/src/components/ApplePayButton.tsx new file mode 100644 index 0000000..a0f9a51 --- /dev/null +++ b/package/src/components/ApplePayButton.tsx @@ -0,0 +1,42 @@ +import React from 'react' +import { Platform, type ViewProps } from 'react-native' +import { getHostComponent } from 'react-native-nitro-modules' +import type { + ApplePayButtonMethods, + ApplePayButtonProps as NativeApplePayButtonProps, +} from '../specs/ApplePayButton.nitro' +import ApplePayButtonConfig from '../../nitrogen/generated/shared/json/ApplePayButtonConfig.json' +import { + type PayButtonPressProps, + useDevWarning, + usePayButtonPress, +} from './usePayButtonPress' + +const NativeApplePayButton = getHostComponent< + NativeApplePayButtonProps, + ApplePayButtonMethods +>('ApplePayButton', () => ApplePayButtonConfig) + +export interface ApplePayButtonProps + extends Omit, + PayButtonPressProps, + ViewProps {} + +/** + * The native Apple Pay button (`PKPaymentButton`). iOS only: it renders + * nothing on Android. + */ +export function ApplePayButton({ + onPress, + disabled, + ...props +}: ApplePayButtonProps) { + const press = usePayButtonPress('ApplePayButton', onPress, disabled) + const isWrongPlatform = Platform.OS !== 'ios' + useDevWarning( + isWrongPlatform, + `ApplePayButton is iOS-only, so it renders nothing on ${Platform.OS}. Render GooglePayButton there.` + ) + if (isWrongPlatform) return null + return +} diff --git a/package/src/components/GooglePayButton.tsx b/package/src/components/GooglePayButton.tsx new file mode 100644 index 0000000..a5474fc --- /dev/null +++ b/package/src/components/GooglePayButton.tsx @@ -0,0 +1,42 @@ +import React from 'react' +import { Platform, type ViewProps } from 'react-native' +import { getHostComponent } from 'react-native-nitro-modules' +import type { + GooglePayButtonMethods, + GooglePayButtonProps as NativeGooglePayButtonProps, +} from '../specs/GooglePayButton.nitro' +import GooglePayButtonConfig from '../../nitrogen/generated/shared/json/GooglePayButtonConfig.json' +import { + type PayButtonPressProps, + useDevWarning, + usePayButtonPress, +} from './usePayButtonPress' + +const NativeGooglePayButton = getHostComponent< + NativeGooglePayButtonProps, + GooglePayButtonMethods +>('GooglePayButton', () => GooglePayButtonConfig) + +export interface GooglePayButtonProps + extends Omit, + PayButtonPressProps, + ViewProps {} + +/** + * The native Google Pay button (`PayButton`). Android only: it renders + * nothing on iOS. + */ +export function GooglePayButton({ + onPress, + disabled, + ...props +}: GooglePayButtonProps) { + const press = usePayButtonPress('GooglePayButton', onPress, disabled) + const isWrongPlatform = Platform.OS !== 'android' + useDevWarning( + isWrongPlatform, + `GooglePayButton is Android-only, so it renders nothing on ${Platform.OS}. Render ApplePayButton there.` + ) + if (isWrongPlatform) return null + return +} diff --git a/package/src/components/__tests__/PayButtons.test.tsx b/package/src/components/__tests__/PayButtons.test.tsx new file mode 100644 index 0000000..2195450 --- /dev/null +++ b/package/src/components/__tests__/PayButtons.test.tsx @@ -0,0 +1,240 @@ +import React from 'react' +import { Platform } from 'react-native' +import { render, screen } from '@testing-library/react-native' + +// The host components become plain host elements, so their props can be read. +jest.mock('react-native-nitro-modules', () => ({ + getHostComponent: (name: string) => name, + callback: (func: unknown) => ({ f: func }), +})) + +import { ApplePayButton } from '../ApplePayButton' +import { GooglePayButton } from '../GooglePayButton' + +/** Taps the native button the way Nitro does: through the wrapped `onPress`. */ +function tap(testID: string) { + screen.getByTestId(testID).props.onPress.f() +} + +describe('ApplePayButton', () => { + let warn: jest.SpyInstance + + beforeEach(() => { + jest.replaceProperty(Platform, 'OS', 'ios') + warn = jest.spyOn(console, 'warn').mockImplementation(() => {}) + }) + + afterEach(() => { + warn.mockRestore() + }) + + it('passes a plain onPress to the native button', () => { + const onPress = jest.fn() + render( + + ) + + const button = screen.getByTestId('pay') + expect(button.type).toBe('ApplePayButton') + expect(button.props).toMatchObject({ + buttonType: 'buy', + buttonStyle: 'black', + style: { height: 48 }, + }) + expect(button.props).not.toHaveProperty('disabled') + + tap('pay') + expect(onPress).toHaveBeenCalledTimes(1) + expect(warn).not.toHaveBeenCalled() + }) + + it('keeps the native onPress when only the handler changes', () => { + const first = jest.fn() + const second = jest.fn() + const { rerender } = render( + + ) + const nativeOnPress = screen.getByTestId('pay').props.onPress + + rerender( + + ) + + expect(screen.getByTestId('pay').props.onPress).toBe(nativeOnPress) + tap('pay') + expect(first).not.toHaveBeenCalled() + expect(second).toHaveBeenCalledTimes(1) + }) + + it('ignores taps while disabled', () => { + const onPress = jest.fn() + const { rerender } = render( + + ) + const nativeOnPress = screen.getByTestId('pay').props.onPress + + tap('pay') + expect(onPress).not.toHaveBeenCalled() + + rerender( + + ) + expect(screen.getByTestId('pay').props.onPress).toBe(nativeOnPress) + tap('pay') + expect(onPress).toHaveBeenCalledTimes(1) + }) + + it('does nothing on tap without onPress', () => { + render() + + expect(() => tap('pay')).not.toThrow() + }) + + it('still accepts onPress wrapped with callback(), with a warning', () => { + const onPress = jest.fn() + const wrapped = { f: onPress } as unknown as () => void + render( + + ) + + tap('pay') + expect(onPress).toHaveBeenCalledTimes(1) + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('no longer needs callback()') + }) + + it('renders nothing on Android, with a warning', () => { + jest.replaceProperty(Platform, 'OS', 'android') + + const { toJSON } = render( + + ) + + expect(toJSON()).toBeNull() + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('ApplePayButton is iOS-only') + }) +}) + +describe('GooglePayButton', () => { + let warn: jest.SpyInstance + + beforeEach(() => { + jest.replaceProperty(Platform, 'OS', 'android') + warn = jest.spyOn(console, 'warn').mockImplementation(() => {}) + }) + + afterEach(() => { + warn.mockRestore() + }) + + it('passes its props and a plain onPress to the native button', () => { + const onPress = jest.fn() + render( + + ) + + const button = screen.getByTestId('pay') + expect(button.type).toBe('GooglePayButton') + expect(button.props).toMatchObject({ + buttonType: 'pay', + theme: 'light', + radius: 8, + supportedNetworks: ['visa'], + googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + merchantCapabilities: ['Debit'], + }) + + tap('pay') + expect(onPress).toHaveBeenCalledTimes(1) + expect(warn).not.toHaveBeenCalled() + }) + + it('keeps the native onPress and ignores taps while disabled', () => { + const first = jest.fn() + const second = jest.fn() + const { rerender } = render( + + ) + const nativeOnPress = screen.getByTestId('pay').props.onPress + + tap('pay') + rerender( + + ) + tap('pay') + + expect(screen.getByTestId('pay').props.onPress).toBe(nativeOnPress) + expect(first).not.toHaveBeenCalled() + expect(second).toHaveBeenCalledTimes(1) + }) + + it('renders nothing on iOS, with a warning', () => { + jest.replaceProperty(Platform, 'OS', 'ios') + + const { toJSON } = render( + + ) + + expect(toJSON()).toBeNull() + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('GooglePayButton is Android-only') + }) +}) diff --git a/package/src/components/usePayButtonPress.ts b/package/src/components/usePayButtonPress.ts new file mode 100644 index 0000000..1c60d20 --- /dev/null +++ b/package/src/components/usePayButtonPress.ts @@ -0,0 +1,71 @@ +import { useEffect, useLayoutEffect, useRef, useState } from 'react' +import { callback } from 'react-native-nitro-modules' + +/** The props both pay buttons add to those of their native view. */ +export interface PayButtonPressProps { + /** Called when the user taps the button. */ + onPress?: () => void + /** + * Ignores taps while `true`, for example while a payment is in progress. + * The button looks the same: Apple's guidelines ask not to make the Apple + * Pay button appear unavailable, and Google's do not allow changing the + * Google Pay button's color. + */ + disabled?: boolean +} + +type PressHandler = () => void + +/** + * What `callback(fn)` from react-native-nitro-modules returns. Earlier + * versions of the buttons required it, so it still works. + */ +type WrappedPressHandler = { f: PressHandler } + +function isWrappedPressHandler(value: unknown): value is WrappedPressHandler { + return ( + typeof value === 'object' && + value !== null && + typeof (value as Partial).f === 'function' + ) +} + +/** Logs `message` in development builds when `condition` becomes true. */ +export function useDevWarning(condition: boolean, message: string) { + useEffect(() => { + if (__DEV__ && condition) console.warn(message) + }, [condition, message]) +} + +/** + * Returns the `onPress` a pay button host component receives, wrapped with + * `callback()` once for the button's lifetime. It reads the latest `onPress` + * and `disabled` at tap time, so a new handler on each render does not update + * the native view. + */ +export function usePayButtonPress( + component: string, + onPress: PressHandler | undefined, + disabled: boolean | undefined +) { + const latest = useRef({ onPress, disabled }) + useLayoutEffect(() => { + latest.current = { onPress, disabled } + }) + + const [press] = useState(() => + callback(() => { + const { onPress: handler, disabled: isDisabled } = latest.current + if (isDisabled) return + if (isWrappedPressHandler(handler)) handler.f() + else handler?.() + }) + ) + + useDevWarning( + isWrappedPressHandler(onPress), + `${component}: onPress no longer needs callback() from react-native-nitro-modules. Pass the function itself.` + ) + + return press +} diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index c02e747..7f76124 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -261,11 +261,10 @@ export interface UsePaymentCheckoutReturn { * {isProcessing ? ( * * ) : ( - * // onPress must be wrapped with callback() from react-native-nitro-modules * * )} * {error && Error: {error.message}} diff --git a/package/src/index.ts b/package/src/index.ts index 36c91b9..95559a8 100644 --- a/package/src/index.ts +++ b/package/src/index.ts @@ -1,30 +1,25 @@ -import { getHostComponent } from 'react-native-nitro-modules' -import type { - ApplePayButtonProps, - ApplePayButtonMethods, -} from './specs/ApplePayButton.nitro' -import type { - GooglePayButtonProps, - GooglePayButtonMethods, -} from './specs/GooglePayButton.nitro' import { getPaymentHandler } from './paymentHandler' export const HybridPaymentHandler = getPaymentHandler() export type { PaymentHandler } from './specs/PaymentHandler.nitro' -import ApplePayButtonConfig from '../nitrogen/generated/shared/json/ApplePayButtonConfig.json' -import GooglePayButtonConfig from '../nitrogen/generated/shared/json/GooglePayButtonConfig.json' - -export const ApplePayButton = getHostComponent< - ApplePayButtonProps, - ApplePayButtonMethods ->('ApplePayButton', () => ApplePayButtonConfig) - -export const GooglePayButton = getHostComponent< - GooglePayButtonProps, - GooglePayButtonMethods ->('GooglePayButton', () => GooglePayButtonConfig) +export { + ApplePayButton, + type ApplePayButtonProps, +} from './components/ApplePayButton' +export { + GooglePayButton, + type GooglePayButtonProps, +} from './components/GooglePayButton' +export type { + ApplePayButtonStyle, + ApplePayButtonType, +} from './specs/ApplePayButton.nitro' +export type { + GooglePayButtonTheme, + GooglePayButtonType, +} from './specs/GooglePayButton.nitro' export * from './types' export * from './utils' diff --git a/package/src/specs/GooglePayButton.nitro.ts b/package/src/specs/GooglePayButton.nitro.ts index 755ed70..732f4cb 100644 --- a/package/src/specs/GooglePayButton.nitro.ts +++ b/package/src/specs/GooglePayButton.nitro.ts @@ -19,6 +19,7 @@ export type GooglePayButtonTheme = 'dark' | 'light' export interface GooglePayButtonProps extends HybridViewProps { buttonType: GooglePayButtonType theme: GooglePayButtonTheme + /** Corner radius in dp, like other React Native sizes. */ radius?: number /** * As `PaymentRequest.supportedNetworks`. Pass the same values as the