import * as React from "react"; import { StyleProp, ViewStyle, StyleSheet, TextStyle, View, Platform, Pressable, } from "react-native"; import { isString } from "lodash"; import type { IconSlot } from "../../interfaces/Icon"; import { extractStyles } from "../../utilities"; import { usePrevious } from "../../hooks"; import Text from "../Text"; import Checkbox, { CheckboxProps } from "./Checkbox"; import { ReadTheme, withTheme } from "@draftbit/theme"; export enum Direction { Row = "row", RowReverse = "row-reverse", } export interface CheckboxRowProps extends CheckboxProps { label: string | React.ReactNode; labelStyle?: StyleProp; labelContainerStyle: StyleProp; checkboxStyle?: StyleProp; direction?: Direction; theme: ReadTheme; } const renderLabel = ( value: string | React.ReactNode, labelStyle: StyleProp, textStyle: StyleProp ) => { if (isString(value)) { return {value}; } else { return <>{value}; } }; const CheckboxRow: React.FC = ({ label = "Label", labelStyle, labelContainerStyle, checkboxStyle, direction = Direction.Row, Icon, status, disabled = false, onPress, onCheck, onUncheck, color, uncheckedColor, defaultValue, checkedIcon, uncheckedIcon, size, style, theme, ...rest }) => { const [internalValue, setInternalValue] = React.useState( status || defaultValue || false ); React.useEffect(() => { if (status != null) { setInternalValue(status); } }, [status]); // This special logic is to handle weird APIs like Airtable that return // true or undefined for a boolean const previousDefaultValue = usePrevious(defaultValue) as boolean | undefined; React.useEffect(() => { if (defaultValue !== previousDefaultValue) { setInternalValue(Boolean(defaultValue)); } }, [defaultValue, previousDefaultValue]); const handlePress = () => { const newValue = !internalValue; setInternalValue(newValue); onPress?.(newValue); if (newValue) { onCheck?.(); } if (!newValue) { onUncheck?.(); } }; const { textStyles, viewStyles } = extractStyles(style); return ( {renderLabel( label, labelStyle, StyleSheet.flatten([{ color: theme.colors.text.strong }, textStyles]) )} ); }; const styles = StyleSheet.create({ mainParent: { alignItems: "center", justifyContent: "space-around", paddingLeft: 20, paddingRight: 20, minHeight: 50, display: "flex", ...Platform.select({ web: { cursor: "pointer", userSelect: "none", }, }), }, label: { flex: 3, }, }); export default withTheme(CheckboxRow);