import { Children, isValidElement } from 'react';
/**
 * Trims leading and trailing whitespace from a `ReactNode`.
 *
 * Recursively processes the node to remove whitespace-only strings from the start and end:
 *
 * - Strings: Returns the trimmed string.
 * - Numbers/booleans/null/undefined: Returns as-is.
 * - Arrays: Removes leading/trailing whitespace-only elements, trims edge strings.
 * - React elements (including fragments): Returns a new element with trimmed children.
 *
 * @example
 *
 * ```tsx
 * trimReactNode('  hello  ') // 'hello'
 * trimReactNode(
 *   <>
 *     {' '}
 *     <span>test</span>{' '}
 *   </>,
 * ) // <><span>test</span></>
 * trimReactNode([' ', <div>content</div>, ' ']) // [<div>content</div>]
 * ```
 *
 * @param node - The `ReactNode` to trim.
 * @returns A new `ReactNode` with leading and trailing whitespace removed.
 */
export function trimReactNode(reactNode) {
    // Handle primitives
    if (typeof reactNode === 'string') {
        return reactNode.trim();
    }
    if (typeof reactNode === 'number' ||
        typeof reactNode === 'boolean' ||
        reactNode === null ||
        reactNode === undefined) {
        return reactNode;
    }
    // Handle arrays
    if (Array.isArray(reactNode)) {
        const children = [...reactNode];
        // Trim leading and trailing whitespace
        for (const trimStart of [true, false]) {
            while (children.length > 0) {
                const index = trimStart ? 0 : children.length - 1;
                const child = children[index];
                if (typeof child === 'string') {
                    const trimmed = trimStart ? child.trimStart() : child.trimEnd();
                    if (trimmed === '') {
                        if (trimStart) {
                            children.shift();
                        }
                        else {
                            children.pop();
                        }
                    }
                    else {
                        children[index] = trimmed;
                        break;
                    }
                }
                else {
                    children[index] = trimReactNode(child);
                    break;
                }
            }
        }
        return children;
    }
    // Handle React elements (including fragments)
    if (isValidElement(reactNode)) {
        const element = reactNode;
        if (element.props.children !== undefined) {
            const childrenArray = Children.toArray(element.props.children);
            const trimmedChildren = trimReactNode(childrenArray);
            return { ...element, props: { ...element.props, children: trimmedChildren } };
        }
    }
    return reactNode;
}
//# sourceMappingURL=trimReactNode.js.map