@liberquack/utils
Version:
Quack utilities
59 lines • 2.26 kB
JavaScript
import { component } from "haunted";
import { useEffect, useRef } from "haunted/lib/core.js";
import { CreateCustomEvent } from "../../../ui-types.js";
import { useAwait } from "../../../util/hooks/use-await.js";
import { StripeContext } from "./stripe-context.js";
import { css } from "../../../util/css.js";
import "./stripe-context.js";
css `stripe-form { display: block }`;
//TODO: Rename it to StripeContextElelement
export const StripeForm = function ({ stripeClient, stripeClientSecret, stripePublicKey }) {
const stripeRef = useRef(null);
const useSubmit = useAwait(async () => {
if (stripeRef.current) {
const { stripeElements } = stripeRef.current;
const stripeCardElement = stripeElements.getElement("cardNumber") || stripeElements.getElement("card");
if (!stripeCardElement) {
throw "Input not found";
}
this.dispatchEvent(CreateCustomEvent("payment-method-token", {
detail: {
cardElement: stripeCardElement
}, bubbles: true
}));
}
}, (data) => {
if (this.value) {
this.value = { ...this.value, useSubmit: { ...data } };
}
});
const stripeCb = useAwait(async () => {
const loadStripeClient = async () => {
if (stripePublicKey) {
const stripeLib = await import('@stripe/stripe-js');
return stripeLib.loadStripe(stripePublicKey);
}
};
const stripe = stripeClient ?? await loadStripeClient();
if (!stripe)
throw "Could not load stripe";
const stripeElements = stripe.elements({ clientSecret: stripeClientSecret });
stripeRef.current = {
stripeClient: stripe,
stripeElements: stripeElements,
useSubmit: useSubmit
};
this.value = stripeRef.current;
});
useEffect(() => {
if (!stripeRef.current) {
stripeCb.run();
}
}, []);
};
customElements.define("stripe-form", component(StripeForm, {
useShadowDOM: false,
baseElement: StripeContext.Provider,
observedAttributes: ["stripe-public-key"]
}));
//# sourceMappingURL=stripe-form.js.map