Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add storybook for CardField components #432

Merged
merged 20 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
ceec83f
docs: wip add storybook for form component
Apr 23, 2024
63e60a5
chore: add option to see source code
Apr 24, 2024
55cffa7
chore: remove broken link
Apr 24, 2024
913dd15
fix: wip relative imports not working
mchoun Apr 25, 2024
73676e6
fix: skeleton for individual stories
mchoun Apr 25, 2024
6c942c7
fix: add individual story and cardfieldsprovider
mchoun Apr 26, 2024
bf37f04
chore: add custom hook story
mchoun Apr 26, 2024
38ef629
chore: final updates and clean up
mchoun Apr 29, 2024
35d434d
chore: update src/stories/payPalCardFields/code.ts
sebastianfdz Apr 29, 2024
840a7e3
chore: update src/stories/payPalCardFields/code.ts
sebastianfdz Apr 29, 2024
f334054
chore: update src/stories/payPalCardFields/payPalCardFieldsForm.stori…
sebastianfdz Apr 29, 2024
d77745a
chore: update src/stories/payPalCardFields/payPalCardFieldsIndividual…
sebastianfdz Apr 29, 2024
c2cf470
chore: update src/stories/payPalCardFields/payPalCardFieldsIndividual…
sebastianfdz Apr 29, 2024
953a298
chore: update src/stories/payPalCardFields/code.ts
sebastianfdz Apr 29, 2024
e7830b4
chore: update src/stories/payPalCardFields/payPalCardFieldsForm.stori…
sebastianfdz Apr 29, 2024
8914e67
chore: update src/components/cardFields/PayPalCardFieldsProvider.tsx
sebastianfdz Apr 29, 2024
38cc22f
chore: remove cliet token references and fix lint issues
Apr 29, 2024
8fa2294
fix: prettier
Apr 29, 2024
1a5eeac
chore: reorder stories
Apr 29, 2024
bfc6f83
chore: remove decorator in favor of wrapping each componing in the pr…
Apr 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/components/cardFields/PayPalCardFieldsForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ import { PayPalCardField } from "./PayPalCardField";
import { FlexContainer } from "../ui/FlexContainer";
import { FullWidthContainer } from "../ui/FullWidthContainer";

/**
This `<PayPalCardFieldsForm />` component renders the 4 individual fields for [Card Fields](https://developer.paypal.com/docs/business/checkout/advanced-card-payments/integrate#3-add-javascript-sdk-and-card-form) integrations.
This setup relies on the `<PayPalCardFieldsProvider />` parent component, which manages the state related to loading the JS SDK script and performs certain validations before rendering the fields.



Note: If you want to have more granular control over the layout of how the fields are rendered, you can alternatively use our Individual Fields.
*/
export const PayPalCardFieldsForm: React.FC<PayPalCardFieldsFormOptions> = ({
className,
...options
Expand Down
11 changes: 11 additions & 0 deletions src/components/cardFields/PayPalCardFieldsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ type CardFieldsProviderProps = PayPalCardFieldsComponentOptions & {
children: ReactNode;
};

/**
The `<PayPalCardFieldsProvider />` is a context provider that is designed to support the rendering and state management of PayPal CardFields in your application.

The context provider will initialize the `CardFields` instance from the JS SDK and determine eligibility to render the CardField components. Once the `CardFields` are initialized, the context provider will manage the state of the `CardFields` instance as well as the reference to each individiual card field.
sebastianfdz marked this conversation as resolved.
Show resolved Hide resolved

Passing the `inputEvents` and `style` props to the context provider will apply them to each of the individual field components.

The state managed by the provider is accessible through our custom hook `usePayPalCardFields`.

*/

export const PayPalCardFieldsProvider = ({
children,
...props
Expand Down
240 changes: 240 additions & 0 deletions src/stories/payPalCardFields/code.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
import { CREATE_ORDER_URL, CAPTURE_ORDER_URL } from "../utils";

import type { Args } from "@storybook/addons/dist/ts3.9/types";

Check warning on line 3 in src/stories/payPalCardFields/code.ts

View workflow job for this annotation

GitHub Actions / main

'Args' is defined but never used
sebastianfdz marked this conversation as resolved.
Show resolved Hide resolved

export const getFormCode = (): string => {
return `
import React, { useState } from "react";
import type { CardFieldsOnApproveData } from "@paypal/paypal-js";

import {
PayPalScriptProvider,
usePayPalCardFields,
PayPalCardFieldsProvider,
PayPalCardFieldsForm,
} from "@paypal/react-paypal-js";

export default function App(): JSX.Element {
const [isPaying, setIsPaying] = useState(false);
async function createOrder() {
return fetch("${CREATE_ORDER_URL}", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
cart: [
{
sku: "1blwyeo8",
quantity: 2,
},
],
}),
})
.then((response) => response.json())
.then((order) => {
return order.id;
})
.catch((err) => {
console.error(err);
});
}

function onApprove(data: CardFieldsOnApproveData) {
fetch("${CAPTURE_ORDER_URL}", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ orderID: data.orderID }),
})
.then((response) => response.json())
.then((data) => {
setIsPaying(false);
})
.catch((err) => {
console.error(err);
});
}
return (
<PayPalScriptProvider
options={{
clientId:
"AduyjUJ0A7urUcWtGCTjanhRBSzOSn9_GKUzxWDnf51YaV1eZNA0ZAFhebIV_Eq-daemeI7dH05KjLWm",
components: "card-fields",
}}
>
<PayPalCardFieldsProvider
createOrder={createOrder}
onApprove={onApprove}
onError={(err) => {
console.log(err);
}}
>
<PayPalCardFieldsForm />
{/* Custom client component to handle card fields submit */}
<SubmitPayment isPaying={isPaying} setIsPaying={setIsPaying} />
</PayPalCardFieldsProvider>
</PayPalScriptProvider>
);
}

const SubmitPayment: React.FC<{
setIsPaying: React.Dispatch<React.SetStateAction<boolean>>;
isPaying: boolean;
}> = ({ isPaying, setIsPaying }) => {
const { cardFieldsForm, fields } = usePayPalCardFields();

const handleClick = async () => {
if (!cardFieldsForm) {
const childErrorMessage =
"Unable to find any child components in the <PayPalHostedFieldsProvider />";
sebastianfdz marked this conversation as resolved.
Show resolved Hide resolved

throw new Error(childErrorMessage);
}
const formState = await cardFieldsForm.getState();

if (!formState.isFormValid) {
return alert("The payment form is invalid");
}
setIsPaying(true);

cardFieldsForm.submit().catch((err) => {
setIsPaying(false);
});
};

return (
<button
className={isPaying ? "btn" : "btn btn-primary"}
style={{ float: "right" }}
onClick={handleClick}
>
{isPaying ? <div className="spinner tiny" /> : "Pay"}
</button>
);
};

`;
};

export const getIndividualFieldCode = (): string => {
return `
import React, { useState } from "react";
import type { CardFieldsOnApproveData } from "@paypal/paypal-js";

import {
PayPalScriptProvider,
usePayPalCardFields,
PayPalCardFieldsProvider,
PayPalCVVField,
PayPalExpiryField,
PayPalNameField,
PayPalNumberField,
} from "@paypal/react-paypal-js";

export default function App(): JSX.Element {
const [isPaying, setIsPaying] = useState(false);
async function createOrder() {
return fetch("${CREATE_ORDER_URL}", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
cart: [
{
sku: "1blwyeo8",
quantity: 2,
},
],
}),
})
.then((response) => response.json())
.then((order) => {
return order.id;
})
.catch((err) => {
console.error(err);
});
}

function onApprove(data: CardFieldsOnApproveData) {
fetch("${CAPTURE_ORDER_URL}", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ orderID: data.orderID }),
})
.then((response) => response.json())
.then((data) => {
setIsPaying(false);
})
.catch((err) => {
console.error(err);
});
}
return (
<PayPalScriptProvider
options={{
clientId:
"AduyjUJ0A7urUcWtGCTjanhRBSzOSn9_GKUzxWDnf51YaV1eZNA0ZAFhebIV_Eq-daemeI7dH05KjLWm",
components: "card-fields",
}}
>
<PayPalCardFieldsProvider
createOrder={createOrder}
onApprove={onApprove}
onError={(err) => {
console.log(err);
}}
>
<PayPalNameField />
<PayPalNumberField />
<PayPalExpiryField />
<PayPalCVVField />
<SubmitPayment isPaying={isPaying} setIsPaying={setIsPaying} />
</PayPalCardFieldsProvider>
</PayPalScriptProvider>
);
}

const SubmitPayment: React.FC<{
setIsPaying: React.Dispatch<React.SetStateAction<boolean>>;
isPaying: boolean;
}> = ({ isPaying, setIsPaying }) => {
const { cardFieldsForm } = usePayPalCardFields();

const handleClick = async () => {
if (!cardFieldsForm) {
const childErrorMessage =
"Unable to find any child components in the <PayPalHostedFieldsProvider />";
sebastianfdz marked this conversation as resolved.
Show resolved Hide resolved

throw new Error(childErrorMessage);
}
const formState = await cardFieldsForm.getState();

if (!formState.isFormValid) {
return alert("The payment form is invalid");
}
setIsPaying(true);

cardFieldsForm.submit().catch((err) => {
setIsPaying(false);
});
};

return (
<button
className={isPaying ? "btn" : "btn btn-primary"}
style={{ float: "right" }}
onClick={handleClick}
>
{isPaying ? <div className="spinner tiny" /> : "Pay"}
</button>
);
};

`;
};
Loading
Loading