import type { ReactNode } from "react"; import React, { useEffect, useRef } from "react"; import type { ViewStyle } from "react-native"; import { View } from "react-native"; import uuid from "react-native-uuid"; import { useErrorMessageContext } from "./context"; import { useStyles } from "./ErrorMessageWrapper.style"; import { Icon } from "../Icon"; import { Text } from "../Text"; type WrapForTypes = "card" | "default"; interface ErrorMessageWrapperProps { /** * The message that shows up below the children */ readonly message?: string; /** * Changes how it gets laid out on the UI */ readonly wrapFor?: WrapForTypes; readonly children: ReactNode; } /** * Adds an error message below the children but ensure the message gets read * out first. * * This component is internal to Atlantis and shouldn't be used outside of it. */ export function ErrorMessageWrapper({ message, wrapFor = "default", children, }: ErrorMessageWrapperProps) { const errorMessageContext = useErrorMessageContext(); const register = errorMessageContext?.register; const unregister = errorMessageContext?.unregister; const a11yMessageRef = useRef(null); const { current: id } = useRef(uuid.v4()); const hasErrorMessage = Boolean(message); const styles = useStyles(); const wrapForStyle: Record = { card: styles.wrapForCard, default: undefined, }; useEffect(() => { if (register) { register({ id, ref: a11yMessageRef, hasErrorMessage }); } if (unregister) { return () => unregister(id); } }, [id, hasErrorMessage, register, unregister]); return ( {hasErrorMessage && ( )} {children} {hasErrorMessage && ( {message} )} ); }