import * as _ from "lodash"; import * as React from "react"; // import { Button, ButtonType } from "../../components/Button"; import { Loading, LoadingType } from "../../components/Loading"; import { Modal, IModalProps } from "../../components/Modal"; import { Pin, PinType } from "../../components/Pin"; import { Reveal, RevealType } from "../../components/Reveal"; import { PaymentForm } from "../../components/PaymentForm"; // import { Image } from "../../components/Image"; import { Link } from "../../components/Link"; interface IPurchasePhotoProps { purchaseWithToken: (token: string, email: string) => Promise; purchaseWithSavedPayment: () => Promise; image: string; modal?: IModalProps; hasPayment: boolean; onClose?: () => void; onPurchased?: (error?: Error) => void; purchaseText: string; } interface IPurchasePhotoState { navigate: "payment" | "loading" | "failed" | "success"; } const defaultPurchasePhotoState: IPurchasePhotoState = { navigate: "payment", }; export class PurchasePhoto extends React.PureComponent { public state: IPurchasePhotoState = defaultPurchasePhotoState; constructor(props) { super(props); if (this.props.hasPayment) { this.state.navigate = "loading"; } } public componentDidMount() { // purchase immediately if we have payment if (this.props.hasPayment) { this.purchase(); } } public componentDidUpdate(prevProps: IPurchasePhotoProps) { // if opening if (!prevProps.modal.isOpen && this.props.modal.isOpen) { if (this.props.hasPayment) { this.purchase(); } else if (this.state.navigate !== "payment") { // reset to first screen this.setState({ navigate: "payment", }); } } } public render() { return ( (
{this.renderLoader(this.state.navigate === "loading")} {this.renderSuccess(this.state.navigate === "success")} {this.renderFailed(this.state.navigate === "failed")} {this.renderPayment(this.state.navigate === "payment")}
) ]}>
); } private renderPayment = (render: boolean) => { return (

Buy this photo?

You'll get a watermark-free photo sent to your email.

{ this.purchase(token, email); }} />
); } private renderLoader = (render: boolean) => { return ( ); } private renderSuccess = (active: boolean) => { return (
Success!
The photo will arrive in your email shortly.
); } private renderFailed = (active: boolean) => { return (
Something went wrong!
Please try again shortly.
); } private purchase = async (token?: string, email?: string) => { if (this.state.navigate !== "loading") { this.setState({ navigate: "loading", }); } try { if (this.props.hasPayment) { await this.props.purchaseWithSavedPayment(); } else { await this.props.purchaseWithToken(token, email); } this.props.onPurchased(); this.setState({ navigate: "success", }); } catch (e) { this.props.onPurchased(e); this.setState({ navigate: "failed", }); } } }