|
| 1 | +import Button from "@components/Button"; |
| 2 | +import { Input } from "@components/Input"; |
| 3 | +import { validator } from "@utils/helpers"; |
| 4 | +import { uniqueId } from "lodash"; |
| 5 | +import { GlobeIcon, MinusCircleIcon } from "lucide-react"; |
| 6 | +import * as React from "react"; |
| 7 | +import { useEffect, useMemo, useState } from "react"; |
| 8 | +import { Domain } from "@/interfaces/Domain"; |
| 9 | + |
| 10 | +type Props = { |
| 11 | + value: Domain; |
| 12 | + onChange: (d: Domain) => void; |
| 13 | + onRemove: () => void; |
| 14 | + onError?: (error: boolean) => void; |
| 15 | + error?: string; |
| 16 | +}; |
| 17 | +enum ActionType { |
| 18 | + ADD = "ADD", |
| 19 | + REMOVE = "REMOVE", |
| 20 | + UPDATE = "UPDATE", |
| 21 | +} |
| 22 | + |
| 23 | +export const domainReducer = (state: Domain[], action: any): Domain[] => { |
| 24 | + switch (action.type) { |
| 25 | + case ActionType.ADD: |
| 26 | + return [...state, { name: "", id: uniqueId("domain") }]; |
| 27 | + case ActionType.REMOVE: |
| 28 | + return state.filter((_, i) => i !== action.index); |
| 29 | + case ActionType.UPDATE: |
| 30 | + return state.map((n, i) => (i === action.index ? action.d : n)); |
| 31 | + default: |
| 32 | + return state; |
| 33 | + } |
| 34 | +}; |
| 35 | + |
| 36 | +export default function InputDomain({ |
| 37 | + value, |
| 38 | + onChange, |
| 39 | + onRemove, |
| 40 | + onError, |
| 41 | +}: Readonly<Props>) { |
| 42 | + const [name, setName] = useState(value?.name || ""); |
| 43 | + |
| 44 | + const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
| 45 | + setName(e.target.value); |
| 46 | + onChange({ ...value, name: e.target.value }); |
| 47 | + }; |
| 48 | + |
| 49 | + const domainError = useMemo(() => { |
| 50 | + if (name == "") { |
| 51 | + return ""; |
| 52 | + } |
| 53 | + const valid = validator.isValidDomain(name); |
| 54 | + if (!valid) { |
| 55 | + return "Please enter a valid domain, e.g. example.com or intra.example.com"; |
| 56 | + } |
| 57 | + }, [name]); |
| 58 | + |
| 59 | + useEffect(() => { |
| 60 | + const hasError = domainError !== "" && domainError !== undefined; |
| 61 | + onError?.(hasError); |
| 62 | + return () => onError?.(false); |
| 63 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 64 | + }, [domainError]); |
| 65 | + |
| 66 | + return ( |
| 67 | + <div className={"flex gap-2 w-full"}> |
| 68 | + <div className={"w-full"}> |
| 69 | + <Input |
| 70 | + customPrefix={<GlobeIcon size={15} />} |
| 71 | + placeholder={"e.g., example.com"} |
| 72 | + maxWidthClass={"w-full"} |
| 73 | + value={name} |
| 74 | + error={domainError} |
| 75 | + onChange={handleNameChange} |
| 76 | + /> |
| 77 | + </div> |
| 78 | + |
| 79 | + <Button |
| 80 | + className={"h-[42px]"} |
| 81 | + variant={"default-outline"} |
| 82 | + onClick={onRemove} |
| 83 | + > |
| 84 | + <MinusCircleIcon size={15} /> |
| 85 | + </Button> |
| 86 | + </div> |
| 87 | + ); |
| 88 | +} |
0 commit comments