import {useMemo, useRef, useState} from 'react'; import renderHtmlAttributes from "../../utils/renderHtmlAttributes"; import useFormSubmitSuccess from "../../hooks/useFormSubmitSuccess"; import type {FreemiusProps} from "../../types/freemius"; import UpgradeOverlay from "../../components/UpgradeOverlay"; type FieldProps = { itemId: string formId: string attrs: Record style: 'material' | 'ios' | 'carbon' layout: 'default' | 'inline' onValue: string offValue: string onValueLabel: string offValueLabel: string defaultState: boolean labelsVisibility: 'hide' | 'show-both-labels' | 'show-active-label' handleIcon: string } & FreemiusProps const Field = (props: FieldProps) => { const inputRef = useRef(null); const attrs = useMemo(() => renderHtmlAttributes(props.attrs), [props.attrs]); const initialValue = useMemo(() => { return props.defaultState ? props.onValue : props.offValue; }, [props.defaultState, props.offValue, props.onValue]); const [value, setValue] = useState(initialValue); // Reset after form submit useFormSubmitSuccess(inputRef, () => { setValue(initialValue); }, [initialValue]); const id = useMemo(() => { return `form-field-${props.formId}-${props.itemId}`; }, [props.formId, props.itemId]); const isShowBothLabels = useMemo(() => { return props.labelsVisibility === 'show-both-labels'; }, [props.labelsVisibility]); const isShowActiveLabel = useMemo(() => { return props.labelsVisibility === 'show-active-label'; }, [props.labelsVisibility]); const showActiveLabel = useMemo(() => { if (value === props.onValue) { return props.onValueLabel; } else if (value === props.offValue) { return props.offValueLabel; } return value; }, [props.offValue, props.offValueLabel, props.onValue, props.onValueLabel, value]); const showActiveValue = useMemo(() => { if (value === props.onValue) { return props.onValue; } else if (value === props.offValue) { return props.offValue; } return value; }, [props.offValue, props.onValue, value]); const showActiveLabelId = useMemo(() => { if (value === props.onValue) { return 'off'; } else if (value === props.offValue) { return 'on'; } return 'on'; }, [props.offValue, props.onValue, value]); const handleIcon = useMemo(() => { try { return decodeURIComponent(props.handleIcon); } catch { return props.handleIcon; } }, [props.handleIcon]); return ( <> {!props.freemius.can_use_premium_code && }
{ if (!props.freemius.can_use_premium_code) { return; } setValue(event.target.value) }} /> { if (!props.freemius.can_use_premium_code) { return; } setValue(event.target.value) }} /> {isShowBothLabels && ( )}
{(isShowBothLabels || isShowActiveLabel) && ( )}
); }; export default Field;