first commit

This commit is contained in:
2026-06-24 09:48:54 +02:00
commit 41e62ddcad
33739 changed files with 4266226 additions and 0 deletions
@@ -0,0 +1,633 @@
import React, {StrictMode} from 'react';
import {render, act, waitFor} from '@testing-library/react';
import {renderHook} from '@testing-library/react-hooks';
import {CheckoutProvider, useCheckout} from './CheckoutProvider';
import {Elements} from './Elements';
import {useStripe} from './useStripe';
import * as mocks from '../../test/mocks';
describe('CheckoutProvider', () => {
let mockStripe: any;
let mockStripePromise: any;
let mockCheckoutSdk: any;
let mockSession: any;
let consoleError: any;
let consoleWarn: any;
let mockCheckout: any;
beforeEach(() => {
mockStripe = mocks.mockStripe();
mockStripePromise = Promise.resolve(mockStripe);
mockCheckoutSdk = mocks.mockCheckoutSdk();
mockStripe.initCheckout.mockResolvedValue(mockCheckoutSdk);
mockSession = mocks.mockCheckoutSession();
mockCheckoutSdk.session.mockReturnValue(mockSession);
const {on: _on, session: _session, ...actions} = mockCheckoutSdk;
mockCheckout = {...actions, ...mockSession};
jest.spyOn(console, 'error');
jest.spyOn(console, 'warn');
consoleError = console.error;
consoleWarn = console.warn;
});
afterEach(() => {
jest.restoreAllMocks();
});
test('injects CheckoutProvider with the useCheckout hook', async () => {
const wrapper = ({children}: any) => (
<CheckoutProvider
stripe={mockStripe}
options={{fetchClientSecret: async () => 'cs_123'}}
>
{children}
</CheckoutProvider>
);
const {result, waitForNextUpdate} = renderHook(() => useCheckout(), {
wrapper,
});
// observe intermediate states
await waitForNextUpdate();
// wait for all (potentially multiple) updates to finish
await waitFor(() => expect(result.current).toEqual(mockCheckout));
});
test('injects CheckoutProvider with the useStripe hook', async () => {
const wrapper = ({children}: any) => (
<CheckoutProvider
stripe={mockStripe}
options={{fetchClientSecret: async () => 'cs_123'}}
>
{children}
</CheckoutProvider>
);
const {result, waitForNextUpdate} = renderHook(() => useStripe(), {
wrapper,
});
// observe intermediate states
await waitForNextUpdate();
// wait for all (potentially multiple) updates to finish
await waitFor(() => expect(result.current).toBe(mockStripe));
});
test('allows a transition from null to a valid Stripe object', async () => {
let stripeProp: any = null;
const wrapper = ({children}: any) => (
<CheckoutProvider
stripe={stripeProp}
options={{fetchClientSecret: async () => 'cs_123'}}
>
{children}
</CheckoutProvider>
);
const {result, rerender} = renderHook(() => useCheckout(), {wrapper});
expect(result.current).toBe(undefined);
stripeProp = mockStripe;
act(() => rerender());
await waitFor(() => expect(result.current).toEqual(mockCheckout));
});
test('works with a Promise resolving to a valid Stripe object', async () => {
const wrapper = ({children}: any) => (
<CheckoutProvider
stripe={mockStripePromise}
options={{fetchClientSecret: async () => 'cs_123'}}
>
{children}
</CheckoutProvider>
);
const {result, waitForNextUpdate} = renderHook(() => useCheckout(), {
wrapper,
});
expect(result.current).toBe(undefined);
await waitForNextUpdate();
await waitFor(() => expect(result.current).toEqual(mockCheckout));
});
test('allows a transition from null to a valid Promise', async () => {
let stripeProp: any = null;
const wrapper = ({children}: any) => (
<CheckoutProvider
stripe={stripeProp}
options={{fetchClientSecret: async () => 'cs_123'}}
>
{children}
</CheckoutProvider>
);
const {result, rerender, waitForNextUpdate} = renderHook(
() => useCheckout(),
{wrapper}
);
expect(result.current).toBe(undefined);
stripeProp = mockStripePromise;
act(() => rerender());
expect(result.current).toBe(undefined);
await waitForNextUpdate();
await waitFor(() => expect(result.current).toEqual(mockCheckout));
});
test('does not set context if Promise resolves after CheckoutProvider is unmounted', async () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
let result: any;
act(() => {
result = render(
<CheckoutProvider
stripe={mockStripePromise}
options={{fetchClientSecret: async () => 'cs_123'}}
>
{null}
</CheckoutProvider>
);
});
result.unmount();
await act(() => mockStripePromise);
expect(consoleError).not.toHaveBeenCalled();
});
test('works with a Promise resolving to null for SSR safety', async () => {
const nullPromise = Promise.resolve(null);
const TestComponent = () => {
const customCheckout = useCheckout();
return customCheckout ? <div>not empty</div> : null;
};
let result: any;
act(() => {
result = render(
<CheckoutProvider
stripe={nullPromise}
options={{fetchClientSecret: async () => 'cs_123'}}
>
<TestComponent />
</CheckoutProvider>
);
});
expect(result.container).toBeEmptyDOMElement();
await act(() => nullPromise.then(() => undefined));
expect(result.container).toBeEmptyDOMElement();
});
describe.each([
['undefined', undefined],
['false', false],
['string', 'foo'],
['random object', {foo: 'bar'}],
])('invalid stripe prop', (name, stripeProp) => {
test(`errors when props.stripe is ${name}`, () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
expect(() =>
render(
<CheckoutProvider
stripe={stripeProp as any}
options={{fetchClientSecret: async () => 'cs_123'}}
>
<div />
</CheckoutProvider>
)
).toThrow('Invalid prop `stripe` supplied to `CheckoutProvider`.');
});
});
test('does not allow changes to an already set Stripe object', async () => {
// Silence console output so test output is less noisy
consoleWarn.mockImplementation(() => {});
let result: any;
act(() => {
result = render(
<CheckoutProvider
stripe={mockStripe}
options={{fetchClientSecret: async () => 'cs_123'}}
/>
);
});
const mockStripe2: any = mocks.mockStripe();
act(() => {
result.rerender(
<CheckoutProvider
stripe={mockStripe2}
options={{fetchClientSecret: async () => 'cs_123'}}
/>
);
});
await waitFor(() => {
expect(mockStripe.initCheckout).toHaveBeenCalledTimes(1);
expect(mockStripe2.initCheckout).toHaveBeenCalledTimes(0);
expect(consoleWarn).toHaveBeenCalledWith(
'Unsupported prop change on CheckoutProvider: You cannot change the `stripe` prop after setting it.'
);
});
});
test('initCheckout only called once and allows changes to elementsOptions appearance after setting the Stripe object', async () => {
let result: any;
const fetchClientSecret = async () => 'cs_123';
act(() => {
result = render(
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret,
elementsOptions: {
appearance: {theme: 'stripe'},
},
}}
/>
);
});
await waitFor(() =>
expect(mockStripe.initCheckout).toHaveBeenCalledWith({
fetchClientSecret,
elementsOptions: {
appearance: {theme: 'stripe'},
},
})
);
act(() => {
result.rerender(
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret: async () => 'cs_123',
elementsOptions: {appearance: {theme: 'night'}},
}}
/>
);
});
await waitFor(() => {
expect(mockStripe.initCheckout).toHaveBeenCalledTimes(1);
expect(mockCheckoutSdk.changeAppearance).toHaveBeenCalledTimes(1);
expect(mockCheckoutSdk.changeAppearance).toHaveBeenCalledWith({
theme: 'night',
});
});
});
test('it does not call loadFonts a 2nd time if they do not change', async () => {
let result: any;
const fetchClientSecret = async () => 'cs_123';
act(() => {
result = render(
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret,
elementsOptions: {
fonts: [
{
cssSrc: 'https://example.com/font.css',
},
],
},
}}
/>
);
});
await waitFor(() =>
expect(mockStripe.initCheckout).toHaveBeenCalledWith({
fetchClientSecret,
elementsOptions: {
fonts: [
{
cssSrc: 'https://example.com/font.css',
},
],
},
})
);
act(() => {
result.rerender(
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret: async () => 'cs_123',
elementsOptions: {
fonts: [
{
cssSrc: 'https://example.com/font.css',
},
],
},
}}
/>
);
});
act(() => {
result.rerender(
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret: async () => 'cs_123',
elementsOptions: {
fonts: [
{
cssSrc: 'https://example.com/font.css',
},
],
},
}}
/>
);
});
await waitFor(() => {
expect(mockStripe.initCheckout).toHaveBeenCalledTimes(1);
// This is called once, due to the sdk having loaded.
expect(mockCheckoutSdk.loadFonts).toHaveBeenCalledTimes(1);
});
});
test('allows changes to elementsOptions fonts', async () => {
let result: any;
const fetchClientSecret = async () => 'cs_123';
act(() => {
result = render(
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret,
elementsOptions: {},
}}
/>
);
});
await waitFor(() =>
expect(mockStripe.initCheckout).toHaveBeenCalledWith({
fetchClientSecret,
elementsOptions: {},
})
);
act(() => {
result.rerender(
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret: async () => 'cs_123',
elementsOptions: {
fonts: [
{
cssSrc: 'https://example.com/font.css',
},
],
},
}}
/>
);
});
await waitFor(() => {
expect(mockStripe.initCheckout).toHaveBeenCalledTimes(1);
expect(mockCheckoutSdk.loadFonts).toHaveBeenCalledTimes(1);
expect(mockCheckoutSdk.loadFonts).toHaveBeenCalledWith([
{
cssSrc: 'https://example.com/font.css',
},
]);
});
});
test('allows options changes before setting the Stripe object', async () => {
let result: any;
const fetchClientSecret = async () => 'cs_123';
act(() => {
result = render(
<CheckoutProvider
stripe={null}
options={{
fetchClientSecret,
elementsOptions: {
appearance: {theme: 'stripe'},
},
}}
/>
);
});
await waitFor(() =>
expect(mockStripe.initCheckout).toHaveBeenCalledTimes(0)
);
act(() => {
result.rerender(
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret,
elementsOptions: {appearance: {theme: 'stripe'}},
}}
/>
);
});
await waitFor(() => {
expect(console.warn).not.toHaveBeenCalled();
expect(mockStripe.initCheckout).toHaveBeenCalledTimes(1);
expect(mockStripe.initCheckout).toHaveBeenCalledWith({
fetchClientSecret,
elementsOptions: {
appearance: {theme: 'stripe'},
},
});
});
});
test('throws when trying to call useCheckout outside of CheckoutProvider context', () => {
const {result} = renderHook(() => useCheckout());
expect(result.error && result.error.message).toBe(
'Could not find CheckoutProvider context; You need to wrap the part of your app that calls useCheckout() in an <CheckoutProvider> provider.'
);
});
test('throws when trying to call useStripe outside of CheckoutProvider context', () => {
const {result} = renderHook(() => useStripe());
expect(result.error && result.error.message).toBe(
'Could not find Elements context; You need to wrap the part of your app that calls useStripe() in an <Elements> provider.'
);
});
test('throws when trying to call useStripe in Elements -> CheckoutProvider nested context', async () => {
const wrapper = ({children}: any) => (
<Elements stripe={mockStripe}>
<CheckoutProvider
stripe={mockStripe}
options={{fetchClientSecret: async () => 'cs_123'}}
>
{children}
</CheckoutProvider>
</Elements>
);
const {result, waitForNextUpdate} = renderHook(() => useStripe(), {
wrapper,
});
await waitForNextUpdate();
expect(result.error && result.error.message).toBe(
'You cannot wrap the part of your app that calls useStripe() in both <CheckoutProvider> and <Elements> providers.'
);
});
test('throws when trying to call useStripe in CheckoutProvider -> Elements nested context', async () => {
const wrapper = ({children}: any) => (
<CheckoutProvider
stripe={mockStripe}
options={{fetchClientSecret: async () => 'cs_123'}}
>
<Elements stripe={mockStripe}>{children}</Elements>
</CheckoutProvider>
);
const {result, waitForNextUpdate} = renderHook(() => useStripe(), {
wrapper,
});
await waitForNextUpdate();
expect(result.error && result.error.message).toBe(
'You cannot wrap the part of your app that calls useStripe() in both <CheckoutProvider> and <Elements> providers.'
);
});
describe('React.StrictMode', () => {
test('initCheckout once in StrictMode', async () => {
const TestComponent = () => {
const _ = useCheckout();
return <div />;
};
act(() => {
render(
<StrictMode>
<CheckoutProvider
stripe={mockStripe}
options={{fetchClientSecret: async () => 'cs_123'}}
>
<TestComponent />
</CheckoutProvider>
</StrictMode>
);
});
await waitFor(() =>
expect(mockStripe.initCheckout).toHaveBeenCalledTimes(1)
);
});
test('initCheckout once with stripePromise in StrictMode', async () => {
const TestComponent = () => {
const _ = useCheckout();
return <div />;
};
act(() => {
render(
<StrictMode>
<CheckoutProvider
stripe={mockStripePromise}
options={{fetchClientSecret: async () => 'cs_123'}}
>
<TestComponent />
</CheckoutProvider>
</StrictMode>
);
});
await waitFor(() =>
expect(mockStripe.initCheckout).toHaveBeenCalledTimes(1)
);
});
test('allows changes to options via (mockCheckoutSdk.changeAppearance after setting the Stripe object in StrictMode', async () => {
let result: any;
const fetchClientSecret = async () => 'cs_123';
act(() => {
result = render(
<StrictMode>
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret,
elementsOptions: {
appearance: {theme: 'stripe'},
},
}}
/>
</StrictMode>
);
});
await waitFor(() => {
expect(mockStripe.initCheckout).toHaveBeenCalledTimes(1);
expect(mockStripe.initCheckout).toHaveBeenCalledWith({
fetchClientSecret,
elementsOptions: {
appearance: {theme: 'stripe'},
},
});
});
act(() => {
result.rerender(
<StrictMode>
<CheckoutProvider
stripe={mockStripe}
options={{
fetchClientSecret: async () => 'cs_123',
elementsOptions: {appearance: {theme: 'night'}},
}}
/>
</StrictMode>
);
});
await waitFor(() => {
expect(mockCheckoutSdk.changeAppearance).toHaveBeenCalledTimes(1);
expect(mockCheckoutSdk.changeAppearance).toHaveBeenCalledWith({
theme: 'night',
});
});
});
});
});
@@ -0,0 +1,272 @@
import {FunctionComponent, PropsWithChildren, ReactNode} from 'react';
import * as stripeJs from '@stripe/stripe-js';
import React from 'react';
import PropTypes from 'prop-types';
import {parseStripeProp} from '../utils/parseStripeProp';
import {usePrevious} from '../utils/usePrevious';
import {isEqual} from '../utils/isEqual';
import {
ElementsContext,
ElementsContextValue,
parseElementsContext,
} from './Elements';
import {registerWithStripeJs} from '../utils/registerWithStripeJs';
interface CheckoutSdkContextValue {
checkoutSdk: stripeJs.StripeCheckout | null;
stripe: stripeJs.Stripe | null;
}
const CheckoutSdkContext = React.createContext<CheckoutSdkContextValue | null>(
null
);
CheckoutSdkContext.displayName = 'CheckoutSdkContext';
export const parseCheckoutSdkContext = (
ctx: CheckoutSdkContextValue | null,
useCase: string
): CheckoutSdkContextValue => {
if (!ctx) {
throw new Error(
`Could not find CheckoutProvider context; You need to wrap the part of your app that ${useCase} in an <CheckoutProvider> provider.`
);
}
return ctx;
};
type StripeCheckoutActions = Omit<
Omit<stripeJs.StripeCheckout, 'session'>,
'on'
>;
export interface CheckoutContextValue
extends StripeCheckoutActions,
stripeJs.StripeCheckoutSession {}
const CheckoutContext = React.createContext<CheckoutContextValue | null>(null);
CheckoutContext.displayName = 'CheckoutContext';
export const extractCheckoutContextValue = (
checkoutSdk: stripeJs.StripeCheckout | null,
sessionState: stripeJs.StripeCheckoutSession | null
): CheckoutContextValue | null => {
if (!checkoutSdk) {
return null;
}
const {on: _on, session: _session, ...actions} = checkoutSdk;
if (!sessionState) {
return Object.assign(checkoutSdk.session(), actions);
}
return Object.assign(sessionState, actions);
};
interface CheckoutProviderProps {
/**
* A [Stripe object](https://stripe.com/docs/js/initializing) or a `Promise` resolving to a `Stripe` object.
* The easiest way to initialize a `Stripe` object is with the the [Stripe.js wrapper module](https://github.com/stripe/stripe-js/blob/master/README.md#readme).
* Once this prop has been set, it can not be changed.
*
* You can also pass in `null` or a `Promise` resolving to `null` if you are performing an initial server-side render or when generating a static site.
*/
stripe: PromiseLike<stripeJs.Stripe | null> | stripeJs.Stripe | null;
options: stripeJs.StripeCheckoutOptions;
}
interface PrivateCheckoutProviderProps {
stripe: unknown;
options: stripeJs.StripeCheckoutOptions;
children?: ReactNode;
}
const INVALID_STRIPE_ERROR =
'Invalid prop `stripe` supplied to `CheckoutProvider`. We recommend using the `loadStripe` utility from `@stripe/stripe-js`. See https://stripe.com/docs/stripe-js/react#elements-props-stripe for details.';
export const CheckoutProvider: FunctionComponent<PropsWithChildren<
CheckoutProviderProps
>> = (({
stripe: rawStripeProp,
options,
children,
}: PrivateCheckoutProviderProps) => {
const parsed = React.useMemo(
() => parseStripeProp(rawStripeProp, INVALID_STRIPE_ERROR),
[rawStripeProp]
);
// State used to trigger a re-render when sdk.session is updated
const [
session,
setSession,
] = React.useState<stripeJs.StripeCheckoutSession | null>(null);
const [ctx, setContext] = React.useState<CheckoutSdkContextValue>(() => ({
stripe: parsed.tag === 'sync' ? parsed.stripe : null,
checkoutSdk: null,
}));
const safeSetContext = (
stripe: stripeJs.Stripe,
checkoutSdk: stripeJs.StripeCheckout
) => {
setContext((ctx) => {
if (ctx.stripe && ctx.checkoutSdk) {
return ctx;
}
return {stripe, checkoutSdk};
});
};
// Ref used to avoid calling initCheckout multiple times when options changes
const initCheckoutCalledRef = React.useRef(false);
React.useEffect(() => {
let isMounted = true;
if (parsed.tag === 'async' && !ctx.stripe) {
parsed.stripePromise.then((stripe) => {
if (stripe && isMounted && !initCheckoutCalledRef.current) {
// Only update context if the component is still mounted
// and stripe is not null. We allow stripe to be null to make
// handling SSR easier.
initCheckoutCalledRef.current = true;
stripe.initCheckout(options).then((checkoutSdk) => {
if (checkoutSdk) {
safeSetContext(stripe, checkoutSdk);
checkoutSdk.on('change', setSession);
}
});
}
});
} else if (
parsed.tag === 'sync' &&
parsed.stripe &&
!initCheckoutCalledRef.current
) {
initCheckoutCalledRef.current = true;
parsed.stripe.initCheckout(options).then((checkoutSdk) => {
if (checkoutSdk) {
safeSetContext(parsed.stripe, checkoutSdk);
checkoutSdk.on('change', setSession);
}
});
}
return () => {
isMounted = false;
};
}, [parsed, ctx, options, setSession]);
// Warn on changes to stripe prop
const prevStripe = usePrevious(rawStripeProp);
React.useEffect(() => {
if (prevStripe !== null && prevStripe !== rawStripeProp) {
console.warn(
'Unsupported prop change on CheckoutProvider: You cannot change the `stripe` prop after setting it.'
);
}
}, [prevStripe, rawStripeProp]);
// Apply updates to elements when options prop has relevant changes
const prevOptions = usePrevious(options);
const prevCheckoutSdk = usePrevious(ctx.checkoutSdk);
React.useEffect(() => {
// Ignore changes while checkout sdk is not initialized.
if (!ctx.checkoutSdk) {
return;
}
const hasSdkLoaded = Boolean(!prevCheckoutSdk && ctx.checkoutSdk);
// Handle appearance changes
const previousAppearance = prevOptions?.elementsOptions?.appearance;
const currentAppearance = options?.elementsOptions?.appearance;
const hasAppearanceChanged = !isEqual(
currentAppearance,
previousAppearance
);
if (currentAppearance && (hasAppearanceChanged || hasSdkLoaded)) {
ctx.checkoutSdk.changeAppearance(currentAppearance);
}
// Handle fonts changes
const previousFonts = prevOptions?.elementsOptions?.fonts;
const currentFonts = options?.elementsOptions?.fonts;
const hasFontsChanged = !isEqual(previousFonts, currentFonts);
if (currentFonts && (hasFontsChanged || hasSdkLoaded)) {
ctx.checkoutSdk.loadFonts(currentFonts);
}
}, [options, prevOptions, ctx.checkoutSdk, prevCheckoutSdk]);
// Attach react-stripe-js version to stripe.js instance
React.useEffect(() => {
registerWithStripeJs(ctx.stripe);
}, [ctx.stripe]);
const checkoutContextValue = React.useMemo(
() => extractCheckoutContextValue(ctx.checkoutSdk, session),
[ctx.checkoutSdk, session]
);
if (!ctx.checkoutSdk) {
return null;
}
return (
<CheckoutSdkContext.Provider value={ctx}>
<CheckoutContext.Provider value={checkoutContextValue}>
{children}
</CheckoutContext.Provider>
</CheckoutSdkContext.Provider>
);
}) as FunctionComponent<PropsWithChildren<CheckoutProviderProps>>;
CheckoutProvider.propTypes = {
stripe: PropTypes.any,
options: PropTypes.shape({
fetchClientSecret: PropTypes.func.isRequired,
elementsOptions: PropTypes.object as any,
}).isRequired,
};
export const useCheckoutSdkContextWithUseCase = (
useCaseString: string
): CheckoutSdkContextValue => {
const ctx = React.useContext(CheckoutSdkContext);
return parseCheckoutSdkContext(ctx, useCaseString);
};
export const useElementsOrCheckoutSdkContextWithUseCase = (
useCaseString: string
): CheckoutSdkContextValue | ElementsContextValue => {
const checkoutSdkContext = React.useContext(CheckoutSdkContext);
const elementsContext = React.useContext(ElementsContext);
if (checkoutSdkContext && elementsContext) {
throw new Error(
`You cannot wrap the part of your app that ${useCaseString} in both <CheckoutProvider> and <Elements> providers.`
);
}
if (checkoutSdkContext) {
return parseCheckoutSdkContext(checkoutSdkContext, useCaseString);
}
return parseElementsContext(elementsContext, useCaseString);
};
export const useCheckout = (): CheckoutContextValue => {
// ensure it's in CheckoutProvider
useCheckoutSdkContextWithUseCase('calls useCheckout()');
const ctx = React.useContext(CheckoutContext);
if (!ctx) {
throw new Error(
'Could not find Checkout Context; You need to wrap the part of your app that calls useCheckout() in an <CheckoutProvider> provider.'
);
}
return ctx;
};
+436
View File
@@ -0,0 +1,436 @@
import React, {StrictMode} from 'react';
import {render, act} from '@testing-library/react';
import {renderHook} from '@testing-library/react-hooks';
import {Elements, useElements, ElementsConsumer} from './Elements';
import * as mocks from '../../test/mocks';
import {useStripe} from './useStripe';
describe('Elements', () => {
let mockStripe: any;
let mockStripePromise: any;
let mockElements: any;
let consoleError: any;
let consoleWarn: any;
beforeEach(() => {
mockStripe = mocks.mockStripe();
mockStripePromise = Promise.resolve(mockStripe);
mockElements = mocks.mockElements();
mockStripe.elements.mockReturnValue(mockElements);
jest.spyOn(console, 'error');
jest.spyOn(console, 'warn');
consoleError = console.error;
consoleWarn = console.warn;
});
afterEach(() => {
jest.restoreAllMocks();
});
test('injects elements with the useElements hook', () => {
const wrapper = ({children}: any) => (
<Elements stripe={mockStripe}>{children}</Elements>
);
const {result} = renderHook(() => useElements(), {wrapper});
expect(result.current).toBe(mockElements);
});
test('only creates elements once', () => {
const TestComponent = () => {
const _ = useElements();
return <div />;
};
render(
<Elements stripe={mockStripe}>
<TestComponent />
</Elements>
);
expect(mockStripe.elements).toHaveBeenCalledTimes(1);
});
test('injects stripe with the useStripe hook', () => {
const wrapper = ({children}: any) => (
<Elements stripe={mockStripe}>{children}</Elements>
);
const {result} = renderHook(() => useStripe(), {wrapper});
expect(result.current).toBe(mockStripe);
});
test('provides elements and stripe with the ElementsConsumer component', () => {
expect.assertions(2);
render(
<Elements stripe={mockStripe}>
<ElementsConsumer>
{(ctx) => {
expect(ctx.elements).toBe(mockElements);
expect(ctx.stripe).toBe(mockStripe);
return null;
}}
</ElementsConsumer>
</Elements>
);
});
test('provides given stripe instance on mount', () => {
const TestComponent = () => {
const stripe = useStripe();
if (!stripe) {
throw new Error('Stripe instance is null');
}
return null;
};
expect(() => {
render(
<Elements stripe={mockStripe}>
<TestComponent />
</Elements>
);
}).not.toThrow('Stripe instance is null');
});
test('allows a transition from null to a valid Stripe object', () => {
let stripeProp: any = null;
const wrapper = ({children}: any) => (
<Elements stripe={stripeProp}>{children}</Elements>
);
const {result, rerender} = renderHook(() => useElements(), {wrapper});
expect(result.current).toBe(null);
stripeProp = mockStripe;
rerender();
expect(result.current).toBe(mockElements);
});
test('works with a Promise resolving to a valid Stripe object', async () => {
const wrapper = ({children}: any) => (
<Elements stripe={mockStripePromise}>{children}</Elements>
);
const {result, waitForNextUpdate} = renderHook(() => useElements(), {
wrapper,
});
expect(result.current).toBe(null);
await waitForNextUpdate();
expect(result.current).toBe(mockElements);
});
test('allows a transition from null to a valid Promise', async () => {
let stripeProp: any = null;
const wrapper = ({children}: any) => (
<Elements stripe={stripeProp}>{children}</Elements>
);
const {result, rerender, waitForNextUpdate} = renderHook(
() => useElements(),
{wrapper}
);
expect(result.current).toBe(null);
stripeProp = mockStripePromise;
rerender();
expect(result.current).toBe(null);
await waitForNextUpdate();
expect(result.current).toBe(mockElements);
});
test('does not set context if Promise resolves after Elements is unmounted', async () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
const {unmount} = render(
<Elements stripe={mockStripePromise}>{null}</Elements>
);
unmount();
await act(() => mockStripePromise);
expect(consoleError).not.toHaveBeenCalled();
});
test('works with a Promise resolving to null for SSR safety', async () => {
const nullPromise = Promise.resolve(null);
const TestComponent = () => {
const elements = useElements();
return elements ? <div>not empty</div> : null;
};
const {container} = render(
<Elements stripe={nullPromise}>
<TestComponent />
</Elements>
);
expect(container).toBeEmptyDOMElement();
await act(() => nullPromise.then(() => undefined));
expect(container).toBeEmptyDOMElement();
});
test('errors when props.stripe is `undefined`', () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
expect(() => render(<Elements stripe={undefined as any} />)).toThrow(
'Invalid prop `stripe` supplied to `Elements`.'
);
});
test('errors when props.stripe is `false`', () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
expect(() => render(<Elements stripe={false as any} />)).toThrow(
'Invalid prop `stripe` supplied to `Elements`.'
);
});
test('errors when props.stripe is a string', () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
expect(() => render(<Elements stripe={'wat' as any} />)).toThrow(
'Invalid prop `stripe` supplied to `Elements`.'
);
});
test('errors when props.stripe is a some other object', () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
expect(() => render(<Elements stripe={{wat: 2} as any} />)).toThrow(
'Invalid prop `stripe` supplied to `Elements`.'
);
});
test('does not allow changes to a set Stripe object', () => {
// Silence console output so test output is less noisy
consoleWarn.mockImplementation(() => {});
const {rerender} = render(<Elements stripe={mockStripe} />);
const mockStripe2: any = mocks.mockStripe();
rerender(<Elements stripe={mockStripe2} />);
expect(mockStripe.elements.mock.calls).toHaveLength(1);
expect(mockStripe2.elements.mock.calls).toHaveLength(0);
expect(consoleWarn).toHaveBeenCalledWith(
'Unsupported prop change on Elements: You cannot change the `stripe` prop after setting it.'
);
});
test('allows changes to options via elements.update after setting the Stripe object', () => {
const {rerender} = render(
<Elements stripe={mockStripe} options={{foo: 'foo'} as any} />
);
rerender(<Elements stripe={mockStripe} options={{bar: 'bar'} as any} />);
expect(mockStripe.elements).toHaveBeenCalledWith({foo: 'foo'});
expect(mockStripe.elements).toHaveBeenCalledTimes(1);
expect(mockElements.update).toHaveBeenCalledWith({bar: 'bar'});
expect(mockStripe.elements).toHaveBeenCalledTimes(1);
});
test('allows options changes before setting the Stripe object', () => {
const {rerender} = render(
<Elements stripe={null} options={{foo: 'foo'} as any} />
);
rerender(<Elements stripe={mockStripe} options={{bar: 'bar'} as any} />);
expect(console.warn).not.toHaveBeenCalled();
rerender(<Elements stripe={mockStripe} options={{bar: 'bar'} as any} />);
expect(mockStripe.elements).toHaveBeenCalledWith({bar: 'bar'});
});
test('throws when trying to call useElements outside of Elements context', () => {
const {result} = renderHook(() => useElements());
expect(result.error && result.error.message).toBe(
'Could not find Elements context; You need to wrap the part of your app that calls useElements() in an <Elements> provider.'
);
});
test('throws when trying to call useStripe outside of Elements context', () => {
const {result} = renderHook(() => useStripe());
expect(result.error && result.error.message).toBe(
'Could not find Elements context; You need to wrap the part of your app that calls useStripe() in an <Elements> provider.'
);
});
test('throws when trying to mount an <ElementsConsumer> outside of Elements context', () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
const TestComponent = () => {
return <ElementsConsumer>{() => null}</ElementsConsumer>;
};
expect(() => render(<TestComponent />)).toThrow(
'Could not find Elements context; You need to wrap the part of your app that mounts <ElementsConsumer> in an <Elements> provider.'
);
});
describe('React.StrictMode', () => {
test('creates elements twice in StrictMode', () => {
const TestComponent = () => {
const _ = useElements();
return <div />;
};
render(
<StrictMode>
<Elements stripe={mockStripe}>
<TestComponent />
</Elements>
</StrictMode>
);
expect(mockStripe.elements).toHaveBeenCalledTimes(2);
});
test('allows changes to options via elements.update after setting the Stripe object in StrictMode', () => {
const TestComponent = () => {
const [options, setOptions] = React.useState({foo: 'foo'} as any);
React.useEffect(() => {
setOptions({bar: 'bar'} as any);
}, []);
return (
<StrictMode>
<Elements stripe={mockStripe} options={options as any} />
</StrictMode>
);
};
render(<TestComponent />);
expect(mockStripe.elements).toHaveBeenCalledWith({foo: 'foo'});
expect(mockStripe.elements).toHaveBeenCalledTimes(2);
expect(mockElements.update).toHaveBeenCalledWith({bar: 'bar'});
expect(mockStripe.elements).toHaveBeenCalledTimes(2);
});
test('creates only one elements instance when updated while resolving Stripe promise', async () => {
let updateResolver: any = () => {};
const updateResult = new Promise<void>((resolve) => {
updateResolver = resolve;
});
let stripePromiseResolve: any = () => {};
const stripePromise = new Promise<any>((resolve) => {
stripePromiseResolve = resolve;
});
// Only resolve stripe once the options have been updated
updateResult.then(() => {
stripePromiseResolve(mockStripePromise);
});
const TestComponent = () => {
const [_, forceRerender] = React.useState(0);
React.useEffect(() => {
setTimeout(() => {
forceRerender((val) => val + 1);
setTimeout(() => {
updateResolver();
});
});
}, []);
return (
<Elements
stripe={stripePromise}
options={{appearance: {theme: 'flat'}}}
/>
);
};
render(<TestComponent />);
await act(async () => await updateResult);
await act(async () => await stripePromise);
expect(mockStripe.elements).toHaveBeenCalledWith({
appearance: {theme: 'flat'},
});
expect(mockStripe.elements).toHaveBeenCalledTimes(1);
});
test('creates only one elements instance when updated while resolving Stripe promise in StrictMode', async () => {
let updateResolver: any = () => {};
const updateResult = new Promise<void>((resolve) => {
updateResolver = resolve;
});
let stripePromiseResolve: any = () => {};
const stripePromise = new Promise<any>((resolve) => {
stripePromiseResolve = resolve;
});
// Only resolve stripe once the options have been updated
updateResult.then(() => {
stripePromiseResolve(mockStripePromise);
});
const TestComponent = () => {
const [_, forceRerender] = React.useState(0);
React.useEffect(() => {
setTimeout(() => {
forceRerender((val) => val + 1);
setTimeout(() => {
updateResolver();
});
});
}, []);
return (
<StrictMode>
<Elements
stripe={stripePromise}
options={{appearance: {theme: 'flat'}}}
/>
</StrictMode>
);
};
render(<TestComponent />);
await act(async () => await updateResult);
await act(async () => await stripePromise);
expect(mockStripe.elements).toHaveBeenCalledWith({
appearance: {theme: 'flat'},
});
expect(mockStripe.elements).toHaveBeenCalledTimes(1);
});
});
});
+201
View File
@@ -0,0 +1,201 @@
// Must use `import *` or named imports for React's types
import {
FunctionComponent,
PropsWithChildren,
ReactElement,
ReactNode,
} from 'react';
import * as stripeJs from '@stripe/stripe-js';
import React from 'react';
import PropTypes from 'prop-types';
import {usePrevious} from '../utils/usePrevious';
import {
extractAllowedOptionsUpdates,
UnknownOptions,
} from '../utils/extractAllowedOptionsUpdates';
import {parseStripeProp} from '../utils/parseStripeProp';
import {registerWithStripeJs} from '../utils/registerWithStripeJs';
export interface ElementsContextValue {
elements: stripeJs.StripeElements | null;
stripe: stripeJs.Stripe | null;
}
export const ElementsContext = React.createContext<ElementsContextValue | null>(
null
);
ElementsContext.displayName = 'ElementsContext';
export const parseElementsContext = (
ctx: ElementsContextValue | null,
useCase: string
): ElementsContextValue => {
if (!ctx) {
throw new Error(
`Could not find Elements context; You need to wrap the part of your app that ${useCase} in an <Elements> provider.`
);
}
return ctx;
};
interface ElementsProps {
/**
* A [Stripe object](https://stripe.com/docs/js/initializing) or a `Promise` resolving to a `Stripe` object.
* The easiest way to initialize a `Stripe` object is with the the [Stripe.js wrapper module](https://github.com/stripe/stripe-js/blob/master/README.md#readme).
* Once this prop has been set, it can not be changed.
*
* You can also pass in `null` or a `Promise` resolving to `null` if you are performing an initial server-side render or when generating a static site.
*/
stripe: PromiseLike<stripeJs.Stripe | null> | stripeJs.Stripe | null;
/**
* Optional [Elements configuration options](https://stripe.com/docs/js/elements_object/create).
* Once the stripe prop has been set, these options cannot be changed.
*/
options?: stripeJs.StripeElementsOptions;
}
interface PrivateElementsProps {
stripe: unknown;
options?: UnknownOptions;
children?: ReactNode;
}
/**
* The `Elements` provider allows you to use [Element components](https://stripe.com/docs/stripe-js/react#element-components) and access the [Stripe object](https://stripe.com/docs/js/initializing) in any nested component.
* Render an `Elements` provider at the root of your React app so that it is available everywhere you need it.
*
* To use the `Elements` provider, call `loadStripe` from `@stripe/stripe-js` with your publishable key.
* The `loadStripe` function will asynchronously load the Stripe.js script and initialize a `Stripe` object.
* Pass the returned `Promise` to `Elements`.
*
* @docs https://docs.stripe.com/sdks/stripejs-react?ui=elements#elements-provider
*/
export const Elements: FunctionComponent<PropsWithChildren<ElementsProps>> = (({
stripe: rawStripeProp,
options,
children,
}: PrivateElementsProps) => {
const parsed = React.useMemo(() => parseStripeProp(rawStripeProp), [
rawStripeProp,
]);
// For a sync stripe instance, initialize into context
const [ctx, setContext] = React.useState<ElementsContextValue>(() => ({
stripe: parsed.tag === 'sync' ? parsed.stripe : null,
elements: parsed.tag === 'sync' ? parsed.stripe.elements(options) : null,
}));
React.useEffect(() => {
let isMounted = true;
const safeSetContext = (stripe: stripeJs.Stripe) => {
setContext((ctx) => {
// no-op if we already have a stripe instance (https://github.com/stripe/react-stripe-js/issues/296)
if (ctx.stripe) return ctx;
return {
stripe,
elements: stripe.elements(options),
};
});
};
// For an async stripePromise, store it in context once resolved
if (parsed.tag === 'async' && !ctx.stripe) {
parsed.stripePromise.then((stripe) => {
if (stripe && isMounted) {
// Only update Elements context if the component is still mounted
// and stripe is not null. We allow stripe to be null to make
// handling SSR easier.
safeSetContext(stripe);
}
});
} else if (parsed.tag === 'sync' && !ctx.stripe) {
// Or, handle a sync stripe instance going from null -> populated
safeSetContext(parsed.stripe);
}
return () => {
isMounted = false;
};
}, [parsed, ctx, options]);
// Warn on changes to stripe prop
const prevStripe = usePrevious(rawStripeProp);
React.useEffect(() => {
if (prevStripe !== null && prevStripe !== rawStripeProp) {
console.warn(
'Unsupported prop change on Elements: You cannot change the `stripe` prop after setting it.'
);
}
}, [prevStripe, rawStripeProp]);
// Apply updates to elements when options prop has relevant changes
const prevOptions = usePrevious(options);
React.useEffect(() => {
if (!ctx.elements) {
return;
}
const updates = extractAllowedOptionsUpdates(options, prevOptions, [
'clientSecret',
'fonts',
]);
if (updates) {
ctx.elements.update(updates);
}
}, [options, prevOptions, ctx.elements]);
// Attach react-stripe-js version to stripe.js instance
React.useEffect(() => {
registerWithStripeJs(ctx.stripe);
}, [ctx.stripe]);
return (
<ElementsContext.Provider value={ctx}>{children}</ElementsContext.Provider>
);
}) as FunctionComponent<PropsWithChildren<ElementsProps>>;
Elements.propTypes = {
stripe: PropTypes.any,
options: PropTypes.object as any,
};
export const useElementsContextWithUseCase = (
useCaseMessage: string
): ElementsContextValue => {
const ctx = React.useContext(ElementsContext);
return parseElementsContext(ctx, useCaseMessage);
};
/**
* @docs https://stripe.com/docs/stripe-js/react#useelements-hook
*/
export const useElements = (): stripeJs.StripeElements | null => {
const {elements} = useElementsContextWithUseCase('calls useElements()');
return elements;
};
interface ElementsConsumerProps {
children: (props: ElementsContextValue) => ReactNode;
}
/**
* @docs https://stripe.com/docs/stripe-js/react#elements-consumer
*/
export const ElementsConsumer: FunctionComponent<ElementsConsumerProps> = ({
children,
}) => {
const ctx = useElementsContextWithUseCase('mounts <ElementsConsumer>');
// Assert to satisfy the busted React.FC return type (it should be ReactNode)
return children(ctx) as ReactElement | null;
};
ElementsConsumer.propTypes = {
children: PropTypes.func.isRequired,
};
@@ -0,0 +1,176 @@
import React from 'react';
import {render, act} from '@testing-library/react';
import * as EmbeddedCheckoutProviderModule from './EmbeddedCheckoutProvider';
import {EmbeddedCheckout} from './EmbeddedCheckout';
import * as mocks from '../../test/mocks';
const {EmbeddedCheckoutProvider} = EmbeddedCheckoutProviderModule;
describe('EmbeddedCheckout on the client', () => {
let mockStripe: any;
let mockStripePromise: any;
let mockEmbeddedCheckout: any;
let mockEmbeddedCheckoutPromise: any;
const fakeClientSecret = 'cs_123_secret_abc';
const fetchClientSecret = () => Promise.resolve(fakeClientSecret);
const fakeOptions = {fetchClientSecret};
beforeEach(() => {
mockStripe = mocks.mockStripe();
mockStripePromise = Promise.resolve(mockStripe);
mockEmbeddedCheckout = mocks.mockEmbeddedCheckout();
mockEmbeddedCheckoutPromise = Promise.resolve(mockEmbeddedCheckout);
mockStripe.initEmbeddedCheckout.mockReturnValue(
mockEmbeddedCheckoutPromise
);
jest.spyOn(React, 'useLayoutEffect');
});
afterEach(() => {
jest.restoreAllMocks();
});
it('passes id to the wrapping DOM element', async () => {
const {container} = render(
<EmbeddedCheckoutProvider
stripe={mockStripePromise}
options={fakeOptions}
>
<EmbeddedCheckout id="foo" />
</EmbeddedCheckoutProvider>
);
await act(async () => await mockStripePromise);
const embeddedCheckoutDiv = container.firstChild as Element;
expect(embeddedCheckoutDiv.id).toBe('foo');
});
it('passes className to the wrapping DOM element', async () => {
const {container} = render(
<EmbeddedCheckoutProvider
stripe={mockStripePromise}
options={fakeOptions}
>
<EmbeddedCheckout className="bar" />
</EmbeddedCheckoutProvider>
);
await act(async () => await mockStripePromise);
const embeddedCheckoutDiv = container.firstChild as Element;
expect(embeddedCheckoutDiv).toHaveClass('bar');
});
it('mounts Embedded Checkout', async () => {
const {container} = render(
<EmbeddedCheckoutProvider stripe={mockStripe} options={fakeOptions}>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
expect(mockEmbeddedCheckout.mount).toBeCalledWith(container.firstChild);
});
it('does not mount until Embedded Checkout has been initialized', async () => {
// Render with no stripe instance and client secret
const {container, rerender} = render(
<EmbeddedCheckoutProvider
stripe={null}
options={{fetchClientSecret: null}}
>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);
expect(mockEmbeddedCheckout.mount).not.toBeCalled();
// Set stripe prop
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={{fetchClientSecret: null}}
>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);
expect(mockEmbeddedCheckout.mount).not.toBeCalled();
// Set fetchClientSecret
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={{fetchClientSecret}}
>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);
expect(mockEmbeddedCheckout.mount).not.toBeCalled();
// Resolve initialization promise
await act(() => mockEmbeddedCheckoutPromise);
expect(mockEmbeddedCheckout.mount).toBeCalledWith(container.firstChild);
});
it('unmounts Embedded Checkout when the component unmounts', async () => {
const {container, rerender} = render(
<EmbeddedCheckoutProvider stripe={mockStripe} options={fakeOptions}>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
expect(mockEmbeddedCheckout.mount).toBeCalledWith(container.firstChild);
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={fakeOptions}
></EmbeddedCheckoutProvider>
);
expect(mockEmbeddedCheckout.unmount).toBeCalled();
});
it('does not throw when the Embedded Checkout instance is already destroyed when unmounting', async () => {
const {container, rerender} = render(
<EmbeddedCheckoutProvider stripe={mockStripe} options={fakeOptions}>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
expect(mockEmbeddedCheckout.mount).toBeCalledWith(container.firstChild);
mockEmbeddedCheckout.unmount.mockImplementation(() => {
throw new Error('instance has been destroyed');
});
expect(() => {
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={fakeOptions}
></EmbeddedCheckoutProvider>
);
}).not.toThrow();
});
it('still works with clientSecret param (deprecated)', async () => {
const {container} = render(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={{clientSecret: 'cs_123_456'}}
>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
expect(mockEmbeddedCheckout.mount).toBeCalledWith(container.firstChild);
});
});
@@ -0,0 +1,60 @@
/**
* @jest-environment node
*/
import React from 'react';
import {renderToString} from 'react-dom/server';
import * as EmbeddedCheckoutProviderModule from './EmbeddedCheckoutProvider';
import {EmbeddedCheckout} from './EmbeddedCheckout';
const {EmbeddedCheckoutProvider} = EmbeddedCheckoutProviderModule;
describe('EmbeddedCheckout on the server (without stripe and clientSecret props)', () => {
beforeEach(() => {
jest.spyOn(React, 'useLayoutEffect');
});
afterEach(() => {
jest.restoreAllMocks();
});
it('passes id to the wrapping DOM element', () => {
const result = renderToString(
<EmbeddedCheckoutProvider stripe={null} options={{clientSecret: null}}>
<EmbeddedCheckout id="foo" />
</EmbeddedCheckoutProvider>
);
expect(result).toBe('<div id="foo"></div>');
});
it('passes className to the wrapping DOM element', () => {
const result = renderToString(
<EmbeddedCheckoutProvider stripe={null} options={{clientSecret: null}}>
<EmbeddedCheckout className="bar" />
</EmbeddedCheckoutProvider>
);
expect(result).toEqual('<div class="bar"></div>');
});
it('throws when Embedded Checkout is mounted outside of EmbeddedCheckoutProvider context', () => {
// Prevent the console.errors to keep the test output clean
jest.spyOn(console, 'error');
(console.error as any).mockImplementation(() => {});
expect(() => renderToString(<EmbeddedCheckout />)).toThrow(
'<EmbeddedCheckout> must be used within <EmbeddedCheckoutProvider>'
);
});
it('does not call useLayoutEffect', () => {
renderToString(
<EmbeddedCheckoutProvider stripe={null} options={{clientSecret: null}}>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);
expect(React.useLayoutEffect).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,67 @@
import React, {FunctionComponent} from 'react';
import {useEmbeddedCheckoutContext} from './EmbeddedCheckoutProvider';
import {isServer} from '../utils/isServer';
interface EmbeddedCheckoutProps {
/**
* Passes through to the Embedded Checkout container.
*/
id?: string;
/**
* Passes through to the Embedded Checkout container.
*/
className?: string;
}
const EmbeddedCheckoutClientElement = ({
id,
className,
}: EmbeddedCheckoutProps) => {
const {embeddedCheckout} = useEmbeddedCheckoutContext();
const isMounted = React.useRef<boolean>(false);
const domNode = React.useRef<HTMLDivElement | null>(null);
React.useLayoutEffect(() => {
if (!isMounted.current && embeddedCheckout && domNode.current !== null) {
embeddedCheckout.mount(domNode.current);
isMounted.current = true;
}
// Clean up on unmount
return () => {
if (isMounted.current && embeddedCheckout) {
try {
embeddedCheckout.unmount();
isMounted.current = false;
} catch (e) {
// Do nothing.
// Parent effects are destroyed before child effects, so
// in cases where both the EmbeddedCheckoutProvider and
// the EmbeddedCheckout component are removed at the same
// time, the embeddedCheckout instance will be destroyed,
// which causes an error when calling unmount.
}
}
};
}, [embeddedCheckout]);
return <div ref={domNode} id={id} className={className} />;
};
// Only render the wrapper in a server environment.
const EmbeddedCheckoutServerElement = ({
id,
className,
}: EmbeddedCheckoutProps) => {
// Validate that we are in the right context by calling useEmbeddedCheckoutContext.
useEmbeddedCheckoutContext();
return <div id={id} className={className} />;
};
type EmbeddedCheckoutComponent = FunctionComponent<EmbeddedCheckoutProps>;
export const EmbeddedCheckout: EmbeddedCheckoutComponent = isServer
? EmbeddedCheckoutServerElement
: EmbeddedCheckoutClientElement;
@@ -0,0 +1,463 @@
import React from 'react';
import {render, act} from '@testing-library/react';
import {renderHook} from '@testing-library/react-hooks';
import {
EmbeddedCheckoutProvider,
useEmbeddedCheckoutContext,
} from './EmbeddedCheckoutProvider';
import * as mocks from '../../test/mocks';
describe('EmbeddedCheckoutProvider', () => {
let mockStripe: any;
let mockStripePromise: any;
let mockEmbeddedCheckout: any;
let mockEmbeddedCheckoutPromise: any;
const fakeClientSecret = 'cs_123_secret_abc';
const fetchClientSecret = () => Promise.resolve(fakeClientSecret);
const fakeOptions = {fetchClientSecret};
let consoleWarn: any;
let consoleError: any;
beforeEach(() => {
mockStripe = mocks.mockStripe();
mockStripePromise = Promise.resolve(mockStripe);
mockEmbeddedCheckout = mocks.mockEmbeddedCheckout();
mockEmbeddedCheckoutPromise = Promise.resolve(mockEmbeddedCheckout);
mockStripe.initEmbeddedCheckout.mockReturnValue(
mockEmbeddedCheckoutPromise
);
jest.spyOn(console, 'error');
jest.spyOn(console, 'warn');
consoleError = console.error;
consoleWarn = console.warn;
});
afterEach(() => {
jest.restoreAllMocks();
});
it('provides the Embedded Checkout instance via context', async () => {
const wrapper = ({children}: {children?: React.ReactNode}) => (
<EmbeddedCheckoutProvider stripe={mockStripe} options={fakeOptions}>
{children}
</EmbeddedCheckoutProvider>
);
const {result} = renderHook(() => useEmbeddedCheckoutContext(), {wrapper});
await act(() => mockEmbeddedCheckoutPromise);
expect(result.current.embeddedCheckout).toBe(mockEmbeddedCheckout);
});
it('only creates elements once', async () => {
const TestConsumerComponent = () => {
const _ = useEmbeddedCheckoutContext();
return <div />;
};
render(
<EmbeddedCheckoutProvider stripe={mockStripe} options={fakeOptions}>
<TestConsumerComponent />
</EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
expect(mockStripe.initEmbeddedCheckout).toHaveBeenCalledTimes(1);
});
it('allows a transition from null to a valid Stripe object', async () => {
let stripeProp: any = null;
const wrapper = ({children}: {children?: React.ReactNode}) => (
<EmbeddedCheckoutProvider stripe={stripeProp} options={fakeOptions}>
{children}
</EmbeddedCheckoutProvider>
);
const {result, rerender} = renderHook(() => useEmbeddedCheckoutContext(), {
wrapper,
});
expect(result.current.embeddedCheckout).toBe(null);
stripeProp = mockStripe;
rerender();
await act(() => mockEmbeddedCheckoutPromise);
expect(result.current.embeddedCheckout).toBe(mockEmbeddedCheckout);
});
it('works with a Promise resolving to a valid Stripe object', async () => {
const wrapper = ({children}: {children?: React.ReactNode}) => (
<EmbeddedCheckoutProvider
stripe={mockStripePromise}
options={fakeOptions}
>
{children}
</EmbeddedCheckoutProvider>
);
const {result} = renderHook(() => useEmbeddedCheckoutContext(), {wrapper});
expect(result.current.embeddedCheckout).toBe(null);
await act(() => mockStripePromise);
await act(() => mockEmbeddedCheckoutPromise);
expect(result.current.embeddedCheckout).toBe(mockEmbeddedCheckout);
});
it('allows a transition from null to a valid Promise', async () => {
let stripeProp: any = null;
const wrapper = ({children}: {children?: React.ReactNode}) => (
<EmbeddedCheckoutProvider stripe={stripeProp} options={fakeOptions}>
{children}
</EmbeddedCheckoutProvider>
);
const {result, rerender} = renderHook(() => useEmbeddedCheckoutContext(), {
wrapper,
});
expect(result.current.embeddedCheckout).toBe(null);
stripeProp = mockStripePromise;
rerender();
expect(result.current.embeddedCheckout).toBe(null);
await act(() => mockStripePromise);
expect(result.current.embeddedCheckout).toBe(mockEmbeddedCheckout);
});
it('works with a Promise resolving to null for SSR safety', async () => {
const nullPromise = Promise.resolve(null);
const TestConsumerComponent = () => {
const {embeddedCheckout} = useEmbeddedCheckoutContext();
return embeddedCheckout ? <div>not empty</div> : null;
};
const {container} = render(
<EmbeddedCheckoutProvider stripe={nullPromise} options={fakeOptions}>
<TestConsumerComponent />
</EmbeddedCheckoutProvider>
);
expect(container).toBeEmptyDOMElement();
await act(() => nullPromise.then(() => undefined));
expect(container).toBeEmptyDOMElement();
});
it('errors when props.stripe is `undefined`', () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
expect(() =>
render(
<EmbeddedCheckoutProvider
stripe={undefined as any}
options={fakeOptions}
/>
)
).toThrow('Invalid prop `stripe` supplied to `EmbeddedCheckoutProvider`.');
});
it('errors when props.stripe is `false`', () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
expect(() =>
render(
<EmbeddedCheckoutProvider stripe={false as any} options={fakeOptions} />
)
).toThrow('Invalid prop `stripe` supplied to `EmbeddedCheckoutProvider`.');
});
it('errors when props.stripe is a string', () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
expect(() =>
render(
<EmbeddedCheckoutProvider stripe={'foo' as any} options={fakeOptions} />
)
).toThrow('Invalid prop `stripe` supplied to `EmbeddedCheckoutProvider`.');
});
it('errors when props.stripe is a some other object', () => {
// Silence console output so test output is less noisy
consoleError.mockImplementation(() => {});
expect(() =>
render(
<EmbeddedCheckoutProvider
stripe={{wat: 2} as any}
options={fakeOptions}
/>
)
).toThrow('Invalid prop `stripe` supplied to `EmbeddedCheckoutProvider`.');
});
it('does not allow changes to a set Stripe object', async () => {
// Silence console output so test output is less noisy
consoleWarn.mockImplementation(() => {});
const {rerender} = render(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={fakeOptions}
></EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
const mockStripe2: any = mocks.mockStripe();
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe2}
options={fakeOptions}
></EmbeddedCheckoutProvider>
);
expect(mockStripe.initEmbeddedCheckout.mock.calls).toHaveLength(1);
expect(mockStripe2.initEmbeddedCheckout.mock.calls).toHaveLength(0);
expect(consoleWarn).toHaveBeenCalledWith(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the `stripe` prop after setting it.'
);
});
describe('clientSecret param (deprecated)', () => {
it('allows a transition from null to a valid client secret', async () => {
let optionsProp: any = {clientSecret: null};
const wrapper = ({children}: {children?: React.ReactNode}) => (
<EmbeddedCheckoutProvider stripe={mockStripe} options={optionsProp}>
{children}
</EmbeddedCheckoutProvider>
);
const {result, rerender} = renderHook(
() => useEmbeddedCheckoutContext(),
{
wrapper,
}
);
expect(result.current.embeddedCheckout).toBe(null);
optionsProp = {clientSecret: fakeClientSecret};
rerender();
await act(() => mockEmbeddedCheckoutPromise);
expect(result.current.embeddedCheckout).toBe(mockEmbeddedCheckout);
});
it('does not allow changes to clientSecret option', async () => {
const optionsProp1 = {clientSecret: 'cs_123_secret_abc'};
const optionsProp2 = {clientSecret: 'cs_abc_secret_123'};
// Silence console output so test output is less noisy
consoleWarn.mockImplementation(() => {});
const {rerender} = render(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp1}
></EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp2}
></EmbeddedCheckoutProvider>
);
expect(consoleWarn).toHaveBeenCalledWith(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the client secret after setting it. Unmount and create a new instance of EmbeddedCheckoutProvider instead.'
);
});
});
describe('fetchClientSecret param', () => {
it('allows a transition from null to a valid fetchClientSecret', async () => {
let optionsProp: any = {fetchClientSecret: null};
const wrapper = ({children}: {children?: React.ReactNode}) => (
<EmbeddedCheckoutProvider stripe={mockStripe} options={optionsProp}>
{children}
</EmbeddedCheckoutProvider>
);
const {result, rerender} = renderHook(
() => useEmbeddedCheckoutContext(),
{
wrapper,
}
);
expect(result.current.embeddedCheckout).toBe(null);
optionsProp = {fetchClientSecret};
rerender();
await act(() => mockEmbeddedCheckoutPromise);
expect(result.current.embeddedCheckout).toBe(mockEmbeddedCheckout);
});
it('does not allow changes to fetchClientSecret option', async () => {
const optionsProp1 = {fetchClientSecret};
const optionsProp2 = {
fetchClientSecret: () => Promise.resolve('cs_abc_secret_123'),
};
// Silence console output so test output is less noisy
consoleWarn.mockImplementation(() => {});
const {rerender} = render(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp1}
></EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp2}
></EmbeddedCheckoutProvider>
);
expect(consoleWarn).toHaveBeenCalledWith(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change fetchClientSecret after setting it. Unmount and create a new instance of EmbeddedCheckoutProvider instead.'
);
});
});
it('errors if both clientSecret and fetchClientSecret are undefined', async () => {
// Silence console output so test output is less noisy
consoleWarn.mockImplementation(() => {});
render(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={{}}
></EmbeddedCheckoutProvider>
);
expect(consoleWarn).toHaveBeenCalledWith(
'Invalid props passed to EmbeddedCheckoutProvider: You must provide one of either `options.fetchClientSecret` or `options.clientSecret`.'
);
});
it('does not allow changes to onComplete option', async () => {
const optionsProp1 = {
fetchClientSecret,
onComplete: () => 'foo',
};
const optionsProp2 = {
fetchClientSecret,
onComplete: () => 'bar',
};
// Silence console output so test output is less noisy
consoleWarn.mockImplementation(() => {});
const {rerender} = render(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp1}
></EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp2}
></EmbeddedCheckoutProvider>
);
expect(consoleWarn).toHaveBeenCalledWith(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the onComplete option after setting it.'
);
});
it('does not allow changes to onShippingDetailsChange option', async () => {
const optionsProp1 = {
fetchClientSecret,
onShippingDetailsChange: () => Promise.resolve({type: 'accept' as const}),
};
const optionsProp2 = {
fetchClientSecret,
onShippingDetailsChange: () => Promise.resolve({type: 'reject' as const}),
};
// Silence console output so test output is less noisy
consoleWarn.mockImplementation(() => {});
const {rerender} = render(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp1}
></EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp2}
></EmbeddedCheckoutProvider>
);
expect(consoleWarn).toHaveBeenCalledWith(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the onShippingDetailsChange option after setting it.'
);
});
it('does not allow changes to onLineItemsChange option', async () => {
const optionsProp1 = {
fetchClientSecret,
onLineItemsChange: () => Promise.resolve({type: 'accept' as const}),
};
const optionsProp2 = {
fetchClientSecret,
onLineItemsChange: () => Promise.resolve({type: 'reject' as const}),
};
// Silence console output so test output is less noisy
consoleWarn.mockImplementation(() => {});
const {rerender} = render(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp1}
></EmbeddedCheckoutProvider>
);
await act(() => mockEmbeddedCheckoutPromise);
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={optionsProp2}
></EmbeddedCheckoutProvider>
);
expect(consoleWarn).toHaveBeenCalledWith(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the onLineItemsChange option after setting it.'
);
});
it('destroys Embedded Checkout when the component unmounts', async () => {
const {rerender} = render(
<div>
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={fakeOptions}
></EmbeddedCheckoutProvider>
</div>
);
await act(() => mockEmbeddedCheckoutPromise);
rerender(<div></div>);
expect(mockEmbeddedCheckout.destroy).toBeCalled();
});
});
@@ -0,0 +1,242 @@
import {FunctionComponent, PropsWithChildren, ReactNode} from 'react';
import React from 'react';
import {usePrevious} from '../utils/usePrevious';
import {UnknownOptions} from '../utils/extractAllowedOptionsUpdates';
import {parseStripeProp} from '../utils/parseStripeProp';
import {registerWithStripeJs} from '../utils/registerWithStripeJs';
import * as stripeJs from '@stripe/stripe-js';
type EmbeddedCheckoutPublicInterface = {
mount(location: string | HTMLElement): void;
unmount(): void;
destroy(): void;
};
export type EmbeddedCheckoutContextValue = {
embeddedCheckout: EmbeddedCheckoutPublicInterface | null;
};
const EmbeddedCheckoutContext = React.createContext<EmbeddedCheckoutContextValue | null>(
null
);
EmbeddedCheckoutContext.displayName = 'EmbeddedCheckoutProviderContext';
export const useEmbeddedCheckoutContext = (): EmbeddedCheckoutContextValue => {
const ctx = React.useContext(EmbeddedCheckoutContext);
if (!ctx) {
throw new Error(
'<EmbeddedCheckout> must be used within <EmbeddedCheckoutProvider>'
);
}
return ctx;
};
interface EmbeddedCheckoutProviderProps {
/**
* A [Stripe object](https://stripe.com/docs/js/initializing) or a `Promise`
* resolving to a `Stripe` object.
* The easiest way to initialize a `Stripe` object is with the the
* [Stripe.js wrapper module](https://github.com/stripe/stripe-js/blob/master/README.md#readme).
* Once this prop has been set, it can not be changed.
*
* You can also pass in `null` or a `Promise` resolving to `null` if you are
* performing an initial server-side render or when generating a static site.
*/
stripe: PromiseLike<stripeJs.Stripe | null> | stripeJs.Stripe | null;
/**
* Embedded Checkout configuration options.
* You can initially pass in `null` to `options.clientSecret` or
* `options.fetchClientSecret` if you are performing an initial server-side
* render or when generating a static site.
*/
options: {
clientSecret?: string | null;
fetchClientSecret?: (() => Promise<string>) | null;
onComplete?: () => void;
onShippingDetailsChange?: (
event: stripeJs.StripeEmbeddedCheckoutShippingDetailsChangeEvent
) => Promise<stripeJs.ResultAction>;
onLineItemsChange?: (
event: stripeJs.StripeEmbeddedCheckoutLineItemsChangeEvent
) => Promise<stripeJs.ResultAction>;
};
}
interface PrivateEmbeddedCheckoutProviderProps {
stripe: unknown;
options: UnknownOptions;
children?: ReactNode;
}
const INVALID_STRIPE_ERROR =
'Invalid prop `stripe` supplied to `EmbeddedCheckoutProvider`. We recommend using the `loadStripe` utility from `@stripe/stripe-js`. See https://stripe.com/docs/stripe-js/react#elements-props-stripe for details.';
export const EmbeddedCheckoutProvider: FunctionComponent<PropsWithChildren<
EmbeddedCheckoutProviderProps
>> = ({
stripe: rawStripeProp,
options,
children,
}: PrivateEmbeddedCheckoutProviderProps) => {
const parsed = React.useMemo(() => {
return parseStripeProp(rawStripeProp, INVALID_STRIPE_ERROR);
}, [rawStripeProp]);
const embeddedCheckoutPromise = React.useRef<Promise<void> | null>(null);
const loadedStripe = React.useRef<stripeJs.Stripe | null>(null);
const [ctx, setContext] = React.useState<EmbeddedCheckoutContextValue>({
embeddedCheckout: null,
});
React.useEffect(() => {
// Don't support any ctx updates once embeddedCheckout or stripe is set.
if (loadedStripe.current || embeddedCheckoutPromise.current) {
return;
}
const setStripeAndInitEmbeddedCheckout = (stripe: stripeJs.Stripe) => {
if (loadedStripe.current || embeddedCheckoutPromise.current) return;
loadedStripe.current = stripe;
embeddedCheckoutPromise.current = loadedStripe.current
.initEmbeddedCheckout(options as any)
.then((embeddedCheckout) => {
setContext({embeddedCheckout});
});
};
// For an async stripePromise, store it once resolved
if (
parsed.tag === 'async' &&
!loadedStripe.current &&
(options.clientSecret || options.fetchClientSecret)
) {
parsed.stripePromise.then((stripe) => {
if (stripe) {
setStripeAndInitEmbeddedCheckout(stripe);
}
});
} else if (
parsed.tag === 'sync' &&
!loadedStripe.current &&
(options.clientSecret || options.fetchClientSecret)
) {
// Or, handle a sync stripe instance going from null -> populated
setStripeAndInitEmbeddedCheckout(parsed.stripe);
}
}, [parsed, options, ctx, loadedStripe]);
React.useEffect(() => {
// cleanup on unmount
return () => {
// If embedded checkout is fully initialized, destroy it.
if (ctx.embeddedCheckout) {
embeddedCheckoutPromise.current = null;
ctx.embeddedCheckout.destroy();
} else if (embeddedCheckoutPromise.current) {
// If embedded checkout is still initializing, destroy it once
// it's done. This could be caused by unmounting very quickly
// after mounting.
embeddedCheckoutPromise.current.then(() => {
embeddedCheckoutPromise.current = null;
if (ctx.embeddedCheckout) {
ctx.embeddedCheckout.destroy();
}
});
}
};
}, [ctx.embeddedCheckout]);
// Attach react-stripe-js version to stripe.js instance
React.useEffect(() => {
registerWithStripeJs(loadedStripe);
}, [loadedStripe]);
// Warn on changes to stripe prop.
// The stripe prop value can only go from null to non-null once and
// can't be changed after that.
const prevStripe = usePrevious(rawStripeProp);
React.useEffect(() => {
if (prevStripe !== null && prevStripe !== rawStripeProp) {
console.warn(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the `stripe` prop after setting it.'
);
}
}, [prevStripe, rawStripeProp]);
// Warn on changes to options.
const prevOptions = usePrevious(options);
React.useEffect(() => {
if (prevOptions == null) {
return;
}
if (options == null) {
console.warn(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot unset options after setting them.'
);
return;
}
if (
options.clientSecret === undefined &&
options.fetchClientSecret === undefined
) {
console.warn(
'Invalid props passed to EmbeddedCheckoutProvider: You must provide one of either `options.fetchClientSecret` or `options.clientSecret`.'
);
}
if (
prevOptions.clientSecret != null &&
options.clientSecret !== prevOptions.clientSecret
) {
console.warn(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the client secret after setting it. Unmount and create a new instance of EmbeddedCheckoutProvider instead.'
);
}
if (
prevOptions.fetchClientSecret != null &&
options.fetchClientSecret !== prevOptions.fetchClientSecret
) {
console.warn(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change fetchClientSecret after setting it. Unmount and create a new instance of EmbeddedCheckoutProvider instead.'
);
}
if (
prevOptions.onComplete != null &&
options.onComplete !== prevOptions.onComplete
) {
console.warn(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the onComplete option after setting it.'
);
}
if (
prevOptions.onShippingDetailsChange != null &&
options.onShippingDetailsChange !== prevOptions.onShippingDetailsChange
) {
console.warn(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the onShippingDetailsChange option after setting it.'
);
}
if (
prevOptions.onLineItemsChange != null &&
options.onLineItemsChange !== prevOptions.onLineItemsChange
) {
console.warn(
'Unsupported prop change on EmbeddedCheckoutProvider: You cannot change the onLineItemsChange option after setting it.'
);
}
}, [prevOptions, options]);
return (
<EmbeddedCheckoutContext.Provider value={ctx}>
{children}
</EmbeddedCheckoutContext.Provider>
);
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,256 @@
// Must use `import *` or named imports for React's types
import {FunctionComponent} from 'react';
import * as stripeJs from '@stripe/stripe-js';
import React from 'react';
import PropTypes from 'prop-types';
import {useAttachEvent} from '../utils/useAttachEvent';
import {ElementProps} from '../types';
import {usePrevious} from '../utils/usePrevious';
import {
extractAllowedOptionsUpdates,
UnknownOptions,
} from '../utils/extractAllowedOptionsUpdates';
import {useElementsOrCheckoutSdkContextWithUseCase} from './CheckoutProvider';
type UnknownCallback = (...args: unknown[]) => any;
interface PrivateElementProps {
id?: string;
className?: string;
onChange?: UnknownCallback;
onBlur?: UnknownCallback;
onFocus?: UnknownCallback;
onEscape?: UnknownCallback;
onReady?: UnknownCallback;
onClick?: UnknownCallback;
onLoadError?: UnknownCallback;
onLoaderStart?: UnknownCallback;
onNetworksChange?: UnknownCallback;
onConfirm?: UnknownCallback;
onCancel?: UnknownCallback;
onShippingAddressChange?: UnknownCallback;
onShippingRateChange?: UnknownCallback;
onSavedPaymentMethodRemove?: UnknownCallback;
onSavedPaymentMethodUpdate?: UnknownCallback;
options?: UnknownOptions;
}
const capitalized = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
const createElementComponent = (
type: stripeJs.StripeElementType,
isServer: boolean
): FunctionComponent<ElementProps> => {
const displayName = `${capitalized(type)}Element`;
const ClientElement: FunctionComponent<PrivateElementProps> = ({
id,
className,
options = {},
onBlur,
onFocus,
onReady,
onChange,
onEscape,
onClick,
onLoadError,
onLoaderStart,
onNetworksChange,
onConfirm,
onCancel,
onShippingAddressChange,
onShippingRateChange,
onSavedPaymentMethodRemove,
onSavedPaymentMethodUpdate,
}) => {
const ctx = useElementsOrCheckoutSdkContextWithUseCase(
`mounts <${displayName}>`
);
const elements = 'elements' in ctx ? ctx.elements : null;
const checkoutSdk = 'checkoutSdk' in ctx ? ctx.checkoutSdk : null;
const [element, setElement] = React.useState<stripeJs.StripeElement | null>(
null
);
const elementRef = React.useRef<stripeJs.StripeElement | null>(null);
const domNode = React.useRef<HTMLDivElement | null>(null);
// For every event where the merchant provides a callback, call element.on
// with that callback. If the merchant ever changes the callback, removes
// the old callback with element.off and then call element.on with the new one.
useAttachEvent(element, 'blur', onBlur);
useAttachEvent(element, 'focus', onFocus);
useAttachEvent(element, 'escape', onEscape);
useAttachEvent(element, 'click', onClick);
useAttachEvent(element, 'loaderror', onLoadError);
useAttachEvent(element, 'loaderstart', onLoaderStart);
useAttachEvent(element, 'networkschange', onNetworksChange);
useAttachEvent(element, 'confirm', onConfirm);
useAttachEvent(element, 'cancel', onCancel);
useAttachEvent(element, 'shippingaddresschange', onShippingAddressChange);
useAttachEvent(element, 'shippingratechange', onShippingRateChange);
useAttachEvent(
element,
'savedpaymentmethodremove',
onSavedPaymentMethodRemove
);
useAttachEvent(
element,
'savedpaymentmethodupdate',
onSavedPaymentMethodUpdate
);
useAttachEvent(element, 'change', onChange);
let readyCallback: UnknownCallback | undefined;
if (onReady) {
if (type === 'expressCheckout') {
// Passes through the event, which includes visible PM types
readyCallback = onReady;
} else {
// For other Elements, pass through the Element itself.
readyCallback = () => {
onReady(element);
};
}
}
useAttachEvent(element, 'ready', readyCallback);
React.useLayoutEffect(() => {
if (
elementRef.current === null &&
domNode.current !== null &&
(elements || checkoutSdk)
) {
let newElement: stripeJs.StripeElement | null = null;
if (checkoutSdk) {
switch (type) {
case 'payment':
newElement = checkoutSdk.createPaymentElement(options);
break;
case 'address':
if ('mode' in options) {
const {mode, ...restOptions} = options;
if (mode === 'shipping') {
newElement = checkoutSdk.createShippingAddressElement(
restOptions
);
} else if (mode === 'billing') {
newElement = checkoutSdk.createBillingAddressElement(
restOptions
);
} else {
throw new Error(
"Invalid options.mode. mode must be 'billing' or 'shipping'."
);
}
} else {
throw new Error(
"You must supply options.mode. mode must be 'billing' or 'shipping'."
);
}
break;
case 'expressCheckout':
newElement = checkoutSdk.createExpressCheckoutElement(
options as any
) as stripeJs.StripeExpressCheckoutElement;
break;
case 'currencySelector':
newElement = checkoutSdk.createCurrencySelectorElement();
break;
case 'taxId':
newElement = checkoutSdk.createTaxIdElement(options);
break;
default:
throw new Error(
`Invalid Element type ${displayName}. You must use either the <PaymentElement />, <AddressElement options={{mode: 'shipping'}} />, <AddressElement options={{mode: 'billing'}} />, or <ExpressCheckoutElement />.`
);
}
} else if (elements) {
newElement = elements.create(type as any, options);
}
// Store element in a ref to ensure it's _immediately_ available in cleanup hooks in StrictMode
elementRef.current = newElement;
// Store element in state to facilitate event listener attachment
setElement(newElement);
if (newElement) {
newElement.mount(domNode.current);
}
}
}, [elements, checkoutSdk, options]);
const prevOptions = usePrevious(options);
React.useEffect(() => {
if (!elementRef.current) {
return;
}
const updates = extractAllowedOptionsUpdates(options, prevOptions, [
'paymentRequest',
]);
if (updates && 'update' in elementRef.current) {
elementRef.current.update(updates);
}
}, [options, prevOptions]);
React.useLayoutEffect(() => {
return () => {
if (
elementRef.current &&
typeof elementRef.current.destroy === 'function'
) {
try {
elementRef.current.destroy();
elementRef.current = null;
} catch (error) {
// Do nothing
}
}
};
}, []);
return <div id={id} className={className} ref={domNode} />;
};
// Only render the Element wrapper in a server environment.
const ServerElement: FunctionComponent<PrivateElementProps> = (props) => {
useElementsOrCheckoutSdkContextWithUseCase(`mounts <${displayName}>`);
const {id, className} = props;
return <div id={id} className={className} />;
};
const Element = isServer ? ServerElement : ClientElement;
Element.propTypes = {
id: PropTypes.string,
className: PropTypes.string,
onChange: PropTypes.func,
onBlur: PropTypes.func,
onFocus: PropTypes.func,
onReady: PropTypes.func,
onEscape: PropTypes.func,
onClick: PropTypes.func,
onLoadError: PropTypes.func,
onLoaderStart: PropTypes.func,
onNetworksChange: PropTypes.func,
onConfirm: PropTypes.func,
onCancel: PropTypes.func,
onShippingAddressChange: PropTypes.func,
onShippingRateChange: PropTypes.func,
onSavedPaymentMethodRemove: PropTypes.func,
onSavedPaymentMethodUpdate: PropTypes.func,
options: PropTypes.object as any,
};
Element.displayName = displayName;
(Element as any).__elementType = type;
return Element as FunctionComponent<ElementProps>;
};
export default createElementComponent;
+12
View File
@@ -0,0 +1,12 @@
import * as stripeJs from '@stripe/stripe-js';
import {useElementsOrCheckoutSdkContextWithUseCase} from './CheckoutProvider';
/**
* @docs https://stripe.com/docs/stripe-js/react#usestripe-hook
*/
export const useStripe = (): stripeJs.Stripe | null => {
const {stripe} = useElementsOrCheckoutSdkContextWithUseCase(
'calls useStripe()'
);
return stripe;
};
+4
View File
@@ -0,0 +1,4 @@
// A magic global reflecting the current package version defined in
// `package.json`. This will be rewritten at build time as a string literal
// when rollup is run (via `@plugin/rollup-replace`).
declare const _VERSION: string;
+211
View File
@@ -0,0 +1,211 @@
import createElementComponent from './components/createElementComponent';
import {
AuBankAccountElementComponent,
CardElementComponent,
CardNumberElementComponent,
CardExpiryElementComponent,
CardCvcElementComponent,
ExpressCheckoutElementComponent,
FpxBankElementComponent,
IbanElementComponent,
IdealBankElementComponent,
P24BankElementComponent,
EpsBankElementComponent,
LinkAuthenticationElementComponent,
PaymentElementComponent,
PaymentRequestButtonElementComponent,
ShippingAddressElementComponent,
AddressElementComponent,
AffirmMessageElementComponent,
AfterpayClearpayMessageElementComponent,
PaymentMethodMessagingElementComponent,
CurrencySelectorElementComponent,
TaxIdElementComponent,
} from './types';
import {isServer} from './utils/isServer';
export * from './types';
export {useElements, Elements, ElementsConsumer} from './components/Elements';
export {
useCheckout,
CheckoutProvider,
CheckoutContextValue,
} from './components/CheckoutProvider';
export {EmbeddedCheckout} from './components/EmbeddedCheckout';
export {EmbeddedCheckoutProvider} from './components/EmbeddedCheckoutProvider';
export {useStripe} from './components/useStripe';
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const AuBankAccountElement: AuBankAccountElementComponent = createElementComponent(
'auBankAccount',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const CardElement: CardElementComponent = createElementComponent(
'card',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const CardNumberElement: CardNumberElementComponent = createElementComponent(
'cardNumber',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const CardExpiryElement: CardExpiryElementComponent = createElementComponent(
'cardExpiry',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const CardCvcElement: CardCvcElementComponent = createElementComponent(
'cardCvc',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const FpxBankElement: FpxBankElementComponent = createElementComponent(
'fpxBank',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const IbanElement: IbanElementComponent = createElementComponent(
'iban',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const IdealBankElement: IdealBankElementComponent = createElementComponent(
'idealBank',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const P24BankElement: P24BankElementComponent = createElementComponent(
'p24Bank',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const EpsBankElement: EpsBankElementComponent = createElementComponent(
'epsBank',
isServer
);
export const PaymentElement: PaymentElementComponent = createElementComponent(
'payment',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const ExpressCheckoutElement: ExpressCheckoutElementComponent = createElementComponent(
'expressCheckout',
isServer
);
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*/
export const CurrencySelectorElement: CurrencySelectorElementComponent = createElementComponent(
'currencySelector',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const PaymentRequestButtonElement: PaymentRequestButtonElementComponent = createElementComponent(
'paymentRequestButton',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const LinkAuthenticationElement: LinkAuthenticationElementComponent = createElementComponent(
'linkAuthentication',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const AddressElement: AddressElementComponent = createElementComponent(
'address',
isServer
);
/**
* @deprecated
* Use `AddressElement` instead.
*
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const ShippingAddressElement: ShippingAddressElementComponent = createElementComponent(
'shippingAddress',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const PaymentMethodMessagingElement: PaymentMethodMessagingElementComponent = createElementComponent(
'paymentMethodMessaging',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const AffirmMessageElement: AffirmMessageElementComponent = createElementComponent(
'affirmMessage',
isServer
);
/**
* @docs https://stripe.com/docs/stripe-js/react#element-components
*/
export const AfterpayClearpayMessageElement: AfterpayClearpayMessageElementComponent = createElementComponent(
'afterpayClearpayMessage',
isServer
);
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*/
export const TaxIdElement: TaxIdElementComponent = createElementComponent(
'taxId',
isServer
);
+883
View File
@@ -0,0 +1,883 @@
import {FunctionComponent} from 'react';
import * as stripeJs from '@stripe/stripe-js';
import {StripeError} from '@stripe/stripe-js';
export interface ElementProps {
/**
* Passes through to the [Element’s container](https://stripe.com/docs/js/element/the_element_container).
*/
id?: string;
/**
* Passes through to the [Element’s container](https://stripe.com/docs/js/element/the_element_container).
*/
className?: string;
/**
* Triggered when the Element loses focus.
*/
onBlur?: (event: {elementType: stripeJs.StripeElementType}) => any;
/**
* Triggered when the Element receives focus.
*/
onFocus?: (event: {elementType: stripeJs.StripeElementType}) => any;
}
export interface AuBankAccountElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=auBankAccount).
*/
options?: stripeJs.StripeAuBankAccountElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=auBankAccountElement).
*/
onChange?: (event: stripeJs.StripeAuBankAccountElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeAuBankAccountElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
}
export type AuBankAccountElementComponent = FunctionComponent<
AuBankAccountElementProps
>;
export interface CardElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=card).
*/
options?: stripeJs.StripeCardElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=cardElement).
*/
onChange?: (event: stripeJs.StripeCardElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeCardElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
/**
* Triggered when there is a change to the available networks the provided card can run on.
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_networkschange?type=cardElement).
*/
onNetworksChange?: (event: {elementType: 'card'}) => any;
/**
* Triggered when the Element fails to load.
*/
onLoadError?: (event: {elementType: 'card'; error: StripeError}) => any;
}
export type CardElementComponent = FunctionComponent<CardElementProps>;
export interface CardNumberElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=cardNumber).
*/
options?: stripeJs.StripeCardNumberElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=cardNumberElement).
*/
onChange?: (event: stripeJs.StripeCardNumberElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeCardNumberElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
/**
* Triggered when there is a change to the available networks the provided card can run on.
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_networkschange?type=cardNumberElement).
*/
onNetworksChange?: (event: {elementType: 'cardNumber'}) => any;
/**
* Triggered when the Element fails to load.
*/
onLoadError?: (event: {elementType: 'cardNumber'; error: StripeError}) => any;
}
export type CardNumberElementComponent = FunctionComponent<
CardNumberElementProps
>;
export interface CardExpiryElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=cardExpiry).
*/
options?: stripeJs.StripeCardExpiryElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=cardExpiryElement).
*/
onChange?: (event: stripeJs.StripeCardExpiryElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeCardExpiryElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
}
export type CardExpiryElementComponent = FunctionComponent<
CardExpiryElementProps
>;
export interface CardCvcElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=cardCvc).
*/
options?: stripeJs.StripeCardCvcElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=cardCvcElement).
*/
onChange?: (event: stripeJs.StripeCardCvcElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeCardCvcElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
}
export type CardCvcElementComponent = FunctionComponent<CardCvcElementProps>;
export interface FpxBankElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=fpxBank).
*/
options?: stripeJs.StripeFpxBankElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=fpxBankElement).
*/
onChange?: (event: stripeJs.StripeFpxBankElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeFpxBankElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
}
export type FpxBankElementComponent = FunctionComponent<FpxBankElementProps>;
export interface IbanElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=iban).
*/
options?: stripeJs.StripeIbanElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=ibanElement).
*/
onChange?: (event: stripeJs.StripeIbanElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeIbanElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
}
export type IbanElementComponent = FunctionComponent<IbanElementProps>;
export interface IdealBankElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=idealBank).
*/
options?: stripeJs.StripeIdealBankElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=idealBankElement).
*/
onChange?: (event: stripeJs.StripeIdealBankElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeIdealBankElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
}
export type IdealBankElementComponent = FunctionComponent<
IdealBankElementProps
>;
export interface P24BankElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=p24Bank).
*/
options?: stripeJs.StripeP24BankElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=p24BankElement).
*/
onChange?: (event: stripeJs.StripeP24BankElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeP24BankElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
}
export interface LinkAuthenticationElementProps extends ElementProps {
/**
* An object containing Element configuration options.
*/
options?: stripeJs.StripeLinkAuthenticationElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=auBankAccountElement).
*/
onChange?: (
event: stripeJs.StripeLinkAuthenticationElementChangeEvent
) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeLinkAuthenticationElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
/**
* Triggered when the Element fails to load.
*/
onLoadError?: (event: {
elementType: 'linkAuthentication';
error: StripeError;
}) => any;
/**
* Triggered when the [loader](https://stripe.com/docs/js/elements_object/create#stripe_elements-options-loader) UI is mounted to the DOM and ready to be displayed.
*/
onLoaderStart?: (event: {elementType: 'linkAuthentication'}) => any;
}
export type LinkAuthenticationElementComponent = FunctionComponent<
LinkAuthenticationElementProps
>;
export type P24BankElementComponent = FunctionComponent<P24BankElementProps>;
export interface EpsBankElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=epsBank).
*/
options?: stripeJs.StripeEpsBankElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=epsBankElement).
*/
onChange?: (event: stripeJs.StripeEpsBankElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeEpsBankElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
}
export type EpsBankElementComponent = FunctionComponent<EpsBankElementProps>;
export interface PaymentElementProps extends ElementProps {
/**
* An object containing Element configuration options.
*/
options?: stripeJs.StripePaymentElementOptions;
/**
* Triggered when data exposed by this Element is changed.
*/
onChange?: (event: stripeJs.StripePaymentElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripePaymentElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
/**
* Triggered when the Element fails to load.
*/
onLoadError?: (event: {elementType: 'payment'; error: StripeError}) => any;
/**
* Triggered when the [loader](https://stripe.com/docs/js/elements_object/create#stripe_elements-options-loader) UI is mounted to the DOM and ready to be displayed.
*/
onLoaderStart?: (event: {elementType: 'payment'}) => any;
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*
* Triggered when the user removes a saved payment method from the Payment Element.
*/
onSavedPaymentMethodRemove?: (event: {
elementType: 'payment';
success: boolean;
error?: string;
payment_method: stripeJs.StripePaymentElementChangeEvent['value']['payment_method'];
}) => any;
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*
* Triggered when the user updates a saved payment method from the Payment Element.
*/
onSavedPaymentMethodUpdate?: (event: {
elementType: 'payment';
success: boolean;
error?: string;
payment_method: stripeJs.StripePaymentElementChangeEvent['value']['payment_method'];
}) => any;
}
export type PaymentElementComponent = FunctionComponent<PaymentElementProps>;
export interface ExpressCheckoutElementProps extends ElementProps {
/**
* An object containing Element configuration options.
*/
options?: stripeJs.StripeExpressCheckoutElementOptions;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* The list of payment methods that could possibly show in the element, or undefined if no payment methods can show.
*/
onReady?: (event: stripeJs.StripeExpressCheckoutElementReadyEvent) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
/**
* Triggered when the Element fails to load.
*/
onLoadError?: (event: {
elementType: 'expressCheckout';
error: StripeError;
}) => any;
/**
* Triggered when a button on the Element is clicked.
*/
onClick?: (event: stripeJs.StripeExpressCheckoutElementClickEvent) => any;
/**
* Triggered when a buyer authorizes a payment within a supported payment method.
*/
onConfirm: (event: stripeJs.StripeExpressCheckoutElementConfirmEvent) => any;
/**
* Triggered when a payment interface is dismissed (e.g., a buyer closes the payment interface)
*/
onCancel?: (event: {elementType: 'expressCheckout'}) => any;
/**
* Triggered when a buyer selects a different shipping address.
*/
onShippingAddressChange?: (
event: stripeJs.StripeExpressCheckoutElementShippingAddressChangeEvent
) => any;
/**
* Triggered when a buyer selects a different shipping rate.
*/
onShippingRateChange?: (
event: stripeJs.StripeExpressCheckoutElementShippingRateChangeEvent
) => any;
}
export type ExpressCheckoutElementComponent = FunctionComponent<
ExpressCheckoutElementProps
>;
export interface PaymentRequestButtonElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=paymentRequestButton).
*/
options?: stripeJs.StripePaymentRequestButtonElementOptions;
/**
* Triggered when the Element is clicked.
*/
onClick?: (
event: stripeJs.StripePaymentRequestButtonElementClickEvent
) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripePaymentRequestButtonElement) => any;
}
export type PaymentRequestButtonElementComponent = FunctionComponent<
PaymentRequestButtonElementProps
>;
export interface CurrencySelectorElementProps extends ElementProps {
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeCurrencySelectorElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
/**
* Triggered when the Element fails to load.
*/
onLoadError?: (event: {
elementType: 'currencySelector';
error: StripeError;
}) => any;
/**
* Triggered when the [loader](https://stripe.com/docs/js/elements_object/create#stripe_elements-options-loader) UI is mounted to the DOM and ready to be displayed.
*/
onLoaderStart?: (event: {elementType: 'currencySelector'}) => any;
}
export type CurrencySelectorElementComponent = FunctionComponent<
CurrencySelectorElementProps
>;
export interface AddressElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_address_element#address_element_create-options).
*/
options: stripeJs.StripeAddressElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=addressElement).
*/
onChange?: (event: stripeJs.StripeAddressElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeAddressElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
/**
* Triggered when the Element fails to load.
*/
onLoadError?: (event: {elementType: 'address'; error: StripeError}) => any;
/**
* Triggered when the [loader](https://stripe.com/docs/js/elements_object/create#stripe_elements-options-loader) UI is mounted to the DOM and ready to be displayed.
*/
onLoaderStart?: (event: {elementType: 'address'}) => any;
}
export type AddressElementComponent = FunctionComponent<AddressElementProps>;
export interface ShippingAddressElementProps extends ElementProps {
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/deprecated/create_shipping_address_element#shipping_address_element_create-options).
*/
options?: stripeJs.StripeShippingAddressElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
* For more information, refer to the [Stripe.js reference](https://stripe.com/docs/js/element/events/on_change?type=shippingAddressElement).
*/
onChange?: (event: stripeJs.StripeShippingAddressElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeShippingAddressElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
/**
* Triggered when the Element fails to load.
*/
onLoadError?: (event: {
elementType: 'shippingAddress';
error: StripeError;
}) => any;
/**
* Triggered when the [loader](https://stripe.com/docs/js/elements_object/create#stripe_elements-options-loader) UI is mounted to the DOM and ready to be displayed.
*/
onLoaderStart?: (event: {elementType: 'shippingAddress'}) => any;
}
export type ShippingAddressElementComponent = FunctionComponent<
ShippingAddressElementProps
>;
export interface PaymentMethodMessagingElementProps {
/**
* Passes through to the [Element’s container](https://stripe.com/docs/js/element/the_element_container).
*/
id?: string;
/**
* Passes through to the [Element’s container](https://stripe.com/docs/js/element/the_element_container).
*/
className?: string;
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=afterpayClearpayMessage).
*/
options?: stripeJs.StripePaymentMethodMessagingElementOptions;
/**
* Triggered when the Element has been fully loaded, after initial method calls have been fired.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripePaymentMethodMessagingElement) => any;
}
export type PaymentMethodMessagingElementComponent = FunctionComponent<
PaymentMethodMessagingElementProps
>;
export interface AffirmMessageElementProps {
/**
* Passes through to the [Element’s container](https://stripe.com/docs/js/element/the_element_container).
*/
id?: string;
/**
* Passes through to the [Element’s container](https://stripe.com/docs/js/element/the_element_container).
*/
className?: string;
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=afterpayClearpayMessage).
*/
options?: stripeJs.StripeAffirmMessageElementOptions;
/**
* Triggered when the Element has been fully loaded, after initial method calls have been fired.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeAffirmMessageElement) => any;
}
export type AffirmMessageElementComponent = FunctionComponent<
AffirmMessageElementProps
>;
export interface AfterpayClearpayMessageElementProps {
/**
* Passes through to the [Element’s container](https://stripe.com/docs/js/element/the_element_container).
*/
id?: string;
/**
* Passes through to the [Element’s container](https://stripe.com/docs/js/element/the_element_container).
*/
className?: string;
/**
* An object containing [Element configuration options](https://stripe.com/docs/js/elements_object/create_element?type=afterpayClearpayMessage).
*/
options?: stripeJs.StripeAfterpayClearpayMessageElementOptions;
/**
* Triggered when the Element has been fully loaded, after initial method calls have been fired.
* Called with a reference to the underlying [Element instance](https://stripe.com/docs/js/element).
*/
onReady?: (element: stripeJs.StripeAfterpayClearpayMessageElement) => any;
}
export type AfterpayClearpayMessageElementComponent = FunctionComponent<
AfterpayClearpayMessageElementProps
>;
declare module '@stripe/stripe-js' {
interface StripeElements {
/**
* Requires beta access:
* Contact [Stripe support](https://support.stripe.com/) for more information.
*
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=auBankAccount) for the `AuBankAccountElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `AuBankAccountElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: AuBankAccountElementComponent
): stripeJs.StripeAuBankAccountElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=card) for the `CardElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `CardElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: CardElementComponent
): stripeJs.StripeCardElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=cardNumber) for the `CardNumberElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `CardNumberElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: CardNumberElementComponent
): stripeJs.StripeCardNumberElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=cardCvc) for the `CardCvcElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `CardCvcElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: CardCvcElementComponent
): stripeJs.StripeCardCvcElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=cardExpiry) for the `CardExpiryElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `CardExpiryElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: CardExpiryElementComponent
): stripeJs.StripeCardExpiryElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=fpxBank) for the `FpxBankElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `FpxBankElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: FpxBankElementComponent
): stripeJs.StripeFpxBankElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=iban) for the `IbanElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `IbanElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: IbanElementComponent
): stripeJs.StripeIbanElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=idealBank) for the `IdealBankElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `IdealBankElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: IdealBankElementComponent
): stripeJs.StripeIdealBankElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=p24Bank) for the `P24BankElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `P24BankElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: P24BankElementComponent
): stripeJs.StripeP24BankElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=epsBank) for the `EpsBankElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `EpsBankElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: EpsBankElementComponent
): stripeJs.StripeEpsBankElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_link_authentication_element) for the `LinkAuthenticationElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `LinkAuthenticationElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: LinkAuthenticationElementComponent
): stripeJs.StripeLinkAuthenticationElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_payment_element) for the `PaymentElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `PaymentElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: PaymentElementComponent
): stripeJs.StripeElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_express_checkout_element) for the `ExpressCheckoutElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `ExpressCheckoutElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: ExpressCheckoutElementComponent
): stripeJs.StripeElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=paymentRequestButton) for the `PaymentRequestButtonElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `PaymentRequestButtonElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: PaymentRequestButtonElementComponent
): stripeJs.StripePaymentRequestButtonElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_address_element) for the `AddressElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `AddressElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: AddressElementComponent
): stripeJs.StripeAddressElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/deprecated/create_shipping_address_element) for the `ShippingAddressElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `ShippingAddressElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: ShippingAddressElementComponent
): stripeJs.StripeShippingAddressElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=paymentMethodMessaging) for the `PaymentMethodMessagingElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `PaymentMethodMessagingElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: PaymentMethodMessagingElementComponent
): stripeJs.StripePaymentMethodMessagingElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=affirmMessage) for the `AffirmMessageElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `AffirmMessageElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: AffirmMessageElementComponent
): stripeJs.StripeAffirmMessageElement | null;
/**
* Returns the underlying [element instance](https://stripe.com/docs/js/elements_object/create_element?type=afterpayClearpayMessage) for the `AfterpayClearpayMessageElement` component in the current [Elements](https://stripe.com/docs/stripe-js/react#elements-provider) provider tree.
* Returns `null` if no `AfterpayClearpayMessageElement` is rendered in the current `Elements` provider tree.
*/
getElement(
component: AfterpayClearpayMessageElementComponent
): stripeJs.StripeAfterpayClearpayMessageElement | null;
}
}
export interface TaxIdElementProps extends ElementProps {
/**
* An object containing Element configuration options.
*/
options: stripeJs.StripeTaxIdElementOptions;
/**
* Triggered when data exposed by this Element is changed (e.g., when there is an error).
*/
onChange?: (event: stripeJs.StripeTaxIdElementChangeEvent) => any;
/**
* Triggered when the Element is fully rendered and can accept imperative `element.focus()` calls.
*/
onReady?: (element: stripeJs.StripeTaxIdElement) => any;
/**
* Triggered when the escape key is pressed within the Element.
*/
onEscape?: () => any;
/**
* Triggered when the Element fails to load.
*/
onLoadError?: (event: {elementType: 'taxId'; error: StripeError}) => any;
/**
* Triggered when the [loader](https://stripe.com/docs/js/elements_object/create#stripe_elements-options-loader) UI is mounted to the DOM and ready to be displayed.
*/
onLoaderStart?: (event: {elementType: 'taxId'}) => any;
}
export type TaxIdElementComponent = FunctionComponent<TaxIdElementProps>;
@@ -0,0 +1,67 @@
import {extractAllowedOptionsUpdates} from './extractAllowedOptionsUpdates';
describe('extractAllowedOptionsUpdates', () => {
it('drops unchanged keys', () => {
expect(
extractAllowedOptionsUpdates(
{foo: 'foo2', bar: {buz: 'buz'}},
{foo: 'foo1', bar: {buz: 'buz'}},
[]
)
).toEqual({foo: 'foo2'});
});
it('works with a null previous value', () => {
expect(extractAllowedOptionsUpdates({foo: 'foo2'}, null, [])).toEqual({
foo: 'foo2',
});
});
it('warns about and drops updates to immutable keys', () => {
const consoleSpy = jest.spyOn(window.console, 'warn');
// Silence console output so test output is less noisy
consoleSpy.mockImplementation(() => {});
expect(
extractAllowedOptionsUpdates(
{foo: 'foo2', bar: 'bar'},
{foo: 'foo1', bar: 'bar'},
['bar', 'foo']
)
).toEqual(null);
expect(consoleSpy).toHaveBeenCalledWith(
'Unsupported prop change: options.foo is not a mutable property.'
);
expect(consoleSpy).toHaveBeenCalledTimes(1);
consoleSpy.mockRestore();
});
it('does not warn on properties that do not change', () => {
const consoleSpy = jest.spyOn(window.console, 'warn');
// Silence console output so test output is less noisy
consoleSpy.mockImplementation(() => {});
const obj = {
num: 0,
obj: {
num: 0,
},
emptyObj: {},
regex: /foo/,
func: () => {},
null: null,
undefined: undefined,
array: [1, 2, 3],
};
expect(extractAllowedOptionsUpdates(obj, obj, Object.keys(obj))).toEqual(
null
);
expect(consoleSpy).not.toHaveBeenCalled();
consoleSpy.mockRestore();
});
});
@@ -0,0 +1,39 @@
import {isUnknownObject} from './guards';
import {isEqual} from './isEqual';
export type UnknownOptions = {[k: string]: unknown};
export const extractAllowedOptionsUpdates = (
options: unknown | void,
prevOptions: unknown | void,
immutableKeys: string[]
): UnknownOptions | null => {
if (!isUnknownObject(options)) {
return null;
}
return Object.keys(options).reduce(
(newOptions: null | UnknownOptions, key) => {
const isUpdated =
!isUnknownObject(prevOptions) ||
!isEqual(options[key], prevOptions[key]);
if (immutableKeys.includes(key)) {
if (isUpdated) {
console.warn(
`Unsupported prop change: options.${key} is not a mutable property.`
);
}
return newOptions;
}
if (!isUpdated) {
return newOptions;
}
return {...(newOptions || {}), [key]: options[key]};
},
null
);
};
+24
View File
@@ -0,0 +1,24 @@
import {Stripe} from '@stripe/stripe-js';
export const isUnknownObject = (
raw: unknown
): raw is {[key in PropertyKey]: unknown} => {
return raw !== null && typeof raw === 'object';
};
export const isPromise = (raw: unknown): raw is PromiseLike<unknown> => {
return isUnknownObject(raw) && typeof raw.then === 'function';
};
// We are using types to enforce the `stripe` prop in this lib,
// but in an untyped integration `stripe` could be anything, so we need
// to do some sanity validation to prevent type errors.
export const isStripe = (raw: unknown): raw is Stripe => {
return (
isUnknownObject(raw) &&
typeof raw.elements === 'function' &&
typeof raw.createToken === 'function' &&
typeof raw.createPaymentMethod === 'function' &&
typeof raw.confirmCardPayment === 'function'
);
};
+65
View File
@@ -0,0 +1,65 @@
import {isEqual} from './isEqual';
describe('isEqual', () => {
[
['a', 'a'],
[100, 100],
[false, false],
[undefined, undefined],
[null, null],
[{}, {}],
[{a: 10}, {a: 10}],
[{a: null}, {a: null}],
[{a: undefined}, {a: undefined}],
[[], []],
[
['a', 'b', 'c'],
['a', 'b', 'c'],
],
[
['a', {inner: [12]}, 'c'],
['a', {inner: [12]}, 'c'],
],
[{a: {nested: {more: [1, 2, 3]}}}, {a: {nested: {more: [1, 2, 3]}}}],
].forEach(([left, right]) => {
it(`should should return true for isEqual(${JSON.stringify(
left
)}, ${JSON.stringify(right)})`, () => {
expect(isEqual(left, right)).toBe(true);
expect(isEqual(right, left)).toBe(true);
});
});
[
['a', 'b'],
['0', 0],
[new Date(1), {}],
[false, ''],
[false, true],
[null, undefined],
[{}, []],
[/foo/, /foo/],
[new Date(1), new Date(1)],
[{a: 10}, {a: 11}],
[
['a', 'b', 'c'],
['a', 'b', 'c', 'd'],
],
[
['a', 'b', 'c', 'd'],
['a', 'b', 'c'],
],
[
['a', {inner: [12]}, 'c'],
['a', {inner: [null]}, 'c'],
],
[{a: {nested: {more: [1, 2, 3]}}}, {b: {nested: {more: [1, 2, 3]}}}],
].forEach(([left, right]) => {
it(`should should return false for isEqual(${JSON.stringify(
left
)}, ${JSON.stringify(right)})`, () => {
expect(isEqual(left, right)).toBe(false);
expect(isEqual(right, left)).toBe(false);
});
});
});
+50
View File
@@ -0,0 +1,50 @@
import {isUnknownObject} from './guards';
const PLAIN_OBJECT_STR = '[object Object]';
export const isEqual = (left: unknown, right: unknown): boolean => {
if (!isUnknownObject(left) || !isUnknownObject(right)) {
return left === right;
}
const leftArray = Array.isArray(left);
const rightArray = Array.isArray(right);
if (leftArray !== rightArray) return false;
const leftPlainObject =
Object.prototype.toString.call(left) === PLAIN_OBJECT_STR;
const rightPlainObject =
Object.prototype.toString.call(right) === PLAIN_OBJECT_STR;
if (leftPlainObject !== rightPlainObject) return false;
// not sure what sort of special object this is (regexp is one option), so
// fallback to reference check.
if (!leftPlainObject && !leftArray) return left === right;
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
if (leftKeys.length !== rightKeys.length) return false;
const keySet: {[key: string]: boolean} = {};
for (let i = 0; i < leftKeys.length; i += 1) {
keySet[leftKeys[i]] = true;
}
for (let i = 0; i < rightKeys.length; i += 1) {
keySet[rightKeys[i]] = true;
}
const allKeys = Object.keys(keySet);
if (allKeys.length !== leftKeys.length) {
return false;
}
const l = left;
const r = right;
const pred = (key: string): boolean => {
return isEqual(l[key], r[key]);
};
return allKeys.every(pred);
};
+1
View File
@@ -0,0 +1 @@
export const isServer = typeof window === 'undefined';
+46
View File
@@ -0,0 +1,46 @@
import * as stripeJs from '@stripe/stripe-js';
import {isStripe, isPromise} from '../utils/guards';
const INVALID_STRIPE_ERROR =
'Invalid prop `stripe` supplied to `Elements`. We recommend using the `loadStripe` utility from `@stripe/stripe-js`. See https://stripe.com/docs/stripe-js/react#elements-props-stripe for details.';
// We are using types to enforce the `stripe` prop in this lib, but in a real
// integration `stripe` could be anything, so we need to do some sanity
// validation to prevent type errors.
const validateStripe = (
maybeStripe: unknown,
errorMsg = INVALID_STRIPE_ERROR
): null | stripeJs.Stripe => {
if (maybeStripe === null || isStripe(maybeStripe)) {
return maybeStripe;
}
throw new Error(errorMsg);
};
type ParsedStripeProp =
| {tag: 'empty'}
| {tag: 'sync'; stripe: stripeJs.Stripe}
| {tag: 'async'; stripePromise: Promise<stripeJs.Stripe | null>};
export const parseStripeProp = (
raw: unknown,
errorMsg = INVALID_STRIPE_ERROR
): ParsedStripeProp => {
if (isPromise(raw)) {
return {
tag: 'async',
stripePromise: Promise.resolve(raw).then((result) =>
validateStripe(result, errorMsg)
),
};
}
const stripe = validateStripe(raw, errorMsg);
if (stripe === null) {
return {tag: 'empty'};
}
return {tag: 'sync', stripe};
};
+13
View File
@@ -0,0 +1,13 @@
export const registerWithStripeJs = (stripe: any) => {
if (!stripe || !stripe._registerWrapper || !stripe.registerAppInfo) {
return;
}
stripe._registerWrapper({name: 'react-stripe-js', version: _VERSION});
stripe.registerAppInfo({
name: 'react-stripe-js',
version: _VERSION,
url: 'https://stripe.com/docs/stripe-js/react',
});
};
+35
View File
@@ -0,0 +1,35 @@
import React from 'react';
import * as stripeJs from '@stripe/stripe-js';
export const useAttachEvent = <A extends unknown[]>(
element: stripeJs.StripeElement | null,
event: string,
cb?: (...args: A) => any
) => {
const cbDefined = !!cb;
const cbRef = React.useRef(cb);
// In many integrations the callback prop changes on each render.
// Using a ref saves us from calling element.on/.off every render.
React.useEffect(() => {
cbRef.current = cb;
}, [cb]);
React.useEffect(() => {
if (!cbDefined || !element) {
return () => {};
}
const decoratedCb = (...args: A): void => {
if (cbRef.current) {
cbRef.current(...args);
}
};
(element as any).on(event, decoratedCb);
return () => {
(element as any).off(event, decoratedCb);
};
}, [cbDefined, event, element, cbRef]);
};
+30
View File
@@ -0,0 +1,30 @@
import {renderHook} from '@testing-library/react-hooks';
import {usePrevious} from './usePrevious';
describe('usePrevious', () => {
it('returns the initial value if it has not yet been changed', () => {
const {result} = renderHook(() => usePrevious('foo'));
expect(result.current).toEqual('foo');
});
it('returns the previous value after the it has been changed', () => {
let val = 'foo';
const {result, rerender} = renderHook(() => usePrevious(val));
expect(result.current).toEqual('foo');
val = 'bar';
rerender();
expect(result.current).toEqual('foo');
val = 'baz';
rerender();
expect(result.current).toEqual('bar');
val = 'buz';
rerender();
expect(result.current).toEqual('baz');
});
});
+11
View File
@@ -0,0 +1,11 @@
import React from 'react';
export const usePrevious = <T>(value: T): T => {
const ref = React.useRef(value);
React.useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};