|
| 1 | +import React, { cloneElement, isValidElement, memo, type ReactElement, type ReactNode } from 'react' |
| 2 | + |
| 3 | +interface ButtonProps { |
| 4 | + onClick?: (e?: unknown) => void | Promise<unknown> |
| 5 | + onMouseOver?: () => void |
| 6 | + onMouseOut?: () => void |
| 7 | + style?: Record<string, unknown> |
| 8 | + children?: ReactNode |
| 9 | + // pass-through for box host props |
| 10 | + [key: string]: unknown |
| 11 | +} |
| 12 | + |
| 13 | +function makeTextUnselectable(node: ReactNode): ReactNode { |
| 14 | + if (node === null || node === undefined || typeof node === 'boolean') return node |
| 15 | + if (typeof node === 'string' || typeof node === 'number') return node |
| 16 | + |
| 17 | + if (Array.isArray(node)) { |
| 18 | + return node.map((child, idx) => <React.Fragment key={idx}>{makeTextUnselectable(child)}</React.Fragment>) |
| 19 | + } |
| 20 | + |
| 21 | + if (!isValidElement(node)) return node |
| 22 | + |
| 23 | + const el = node as ReactElement |
| 24 | + const type = el.type |
| 25 | + |
| 26 | + // Ensure text nodes are not selectable |
| 27 | + if (typeof type === 'string' && type === 'text') { |
| 28 | + const nextProps = { ...el.props, selectable: false } |
| 29 | + const nextChildren = el.props?.children ? makeTextUnselectable(el.props.children) : el.props?.children |
| 30 | + return cloneElement(el, nextProps, nextChildren) |
| 31 | + } |
| 32 | + |
| 33 | + // Recurse into other host elements and components' children |
| 34 | + const nextChildren = el.props?.children ? makeTextUnselectable(el.props.children) : el.props?.children |
| 35 | + return cloneElement(el, el.props, nextChildren) |
| 36 | +} |
| 37 | + |
| 38 | +export const Button = memo(({ onClick, onMouseOver, onMouseOut, style, children, ...rest }: ButtonProps) => { |
| 39 | + const processedChildren = makeTextUnselectable(children) |
| 40 | + return ( |
| 41 | + <box |
| 42 | + {...rest} |
| 43 | + style={style} |
| 44 | + onMouseDown={onClick} |
| 45 | + onMouseOver={onMouseOver} |
| 46 | + onMouseOut={onMouseOut} |
| 47 | + > |
| 48 | + {processedChildren} |
| 49 | + </box> |
| 50 | + ) |
| 51 | +}) |
0 commit comments