import * as Yup from "yup"; import { forwardRef, useImperativeHandle, useState } from "react"; import PropTypes from "prop-types"; import { Formik, Form, FieldArray } from "formik"; import { parseSkylink } from "skynet-js"; import cn from "classnames"; import accountsService from "../../services/accountsService"; import { Alert } from "../Alert"; import { Button } from "../Button"; import { CopyButton } from "../CopyButton"; import { TextField } from "../Form/TextField"; import { PlusIcon, TrashIcon } from "../Icons"; const skylinkValidator = (optional) => (value) => { if (!value) { return optional; } try { return parseSkylink(value) !== null; } catch { return false; } }; const newSponsorKeySchema = Yup.object().shape({ name: Yup.string(), skylinks: Yup.array().of(Yup.string().test("skylink", "Provide a valid Skylink", skylinkValidator(false))), nextSkylink: Yup.string().when("skylinks", { is: (skylinks) => skylinks.length === 0, then: (schema) => schema.test("skylink", "Provide a valid Skylink", skylinkValidator(true)), otherwise: (schema) => schema.test("skylink", "Provide a valid Skylink", skylinkValidator(true)), }), }); const State = { Pure: "PURE", Success: "SUCCESS", Failure: "FAILURE", }; export const AddSponsorKeyForm = forwardRef(({ onSuccess }, ref) => { const [state, setState] = useState(State.Pure); const [generatedKey, setGeneratedKey] = useState(null); useImperativeHandle(ref, () => ({ reset: () => setState(State.Pure), })); return (
{state === State.Success && ( Success!

Please copy your new API key below. We'll never show it again!

{generatedKey}
)} {state === State.Failure && ( We were not able to generate a new key. Please try again later. )} { try { const { key } = await accountsService .post("user/apikeys", { json: { name, public: "true", skylinks: [...skylinks, nextSkylink].filter(Boolean).map((skylink) => parseSkylink(skylink)), }, }) .json(); resetForm(); setGeneratedKey(key); setState(State.Success); onSuccess(); } catch { setState(State.Failure); } }} > {({ errors, touched, isSubmitting, values, isValid, setFieldValue, setFieldTouched }) => (
Skylinks sponsored by the new key
{ const { skylinks = [] } = values; const { skylinks: skylinksErrors = [] } = errors; const { skylinks: skylinksTouched = [] } = touched; const appendSkylink = (skylink) => { push(skylink); setFieldValue("nextSkylink", "", false); setFieldTouched("nextSkylink", false); }; const isNextSkylinkInvalid = Boolean( errors.nextSkylink || !touched.nextSkylink || !values.nextSkylink ); return (
{skylinks.map((_, index) => (
))}
{ if (event.key === "Enter" && isValid) { event.preventDefault(); appendSkylink(values.nextSkylink); } }} />
); }} />
)}
); }); AddSponsorKeyForm.displayName = "AddSponsorKeyForm"; AddSponsorKeyForm.propTypes = { onSuccess: PropTypes.func.isRequired, };