/* @oracle/oraclejet-preact: undefined */
import { jsxs, jsx } from 'preact/jsx-runtime';
import { F as Flex } from './Flex-03129963.js';
import { H as HighlightText } from './HighlightText-0205faef.js';
import './Grid-9e4b4f19.js';
import './ListItemLayoutStyles.styles.css';
import { L as ListItemText } from './ListItemText-d001751c.js';
import { useCallback, useMemo, useRef, useState, useEffect } from 'preact/hooks';
import { e as error } from './logger-c92f309c.js';
import { dropdownStyles } from './PRIVATE_SelectCommon/themes/dropdownStyles.css.js';
import { L as List } from './List-4636ba9b.js';
import { u as usePress } from './usePress-051f5adb.js';
import { S as SvgCaretDown } from './CaretDown-4061aefc.js';
import { c as classNames } from './classNames-4e12b00d.js';
import { u as useComponentTheme } from './useComponentTheme-d2f9e47f.js';
import { ButtonLabelLayoutRedwoodTheme } from './UNSAFE_ButtonLabelLayout/themes/redwood/ButtonLabelLayoutTheme.js';
import { u as useTestId } from './useTestId-f24ac480.js';
import { BaseButtonRedwoodTheme } from './UNSAFE_BaseButton/themes/redwood/BaseButtonTheme.js';
import { C as CollectionInteractionContext } from './CollectionInteractionContext-7cf19abc.js';
import { T as Text } from './Text-834eb35e.js';
import { u as useTranslationBundle } from './useTranslationBundle-4822502f.js';
import { g as getClientHints } from './clientHints-a42b510c.js';
import { useMemo as useMemo$1 } from 'preact/compat';
import { K as KEYS, i as isControlOrFunctionKey } from './keyboardUtils-986fe923.js';
import { a as allTabbableElements } from './tabbableUtils-c8311ec6.js';

/**
 * @license
 * Copyright (c) %FIRST_YEAR% %CURRENT_YEAR%, Oracle and/or its affiliates.
 * The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */
function renderItemText(item, itemText, componentName) {
    // if item-text is a string and the data has the specified field, return it;
    // otherwise log an error
    if (typeof itemText === 'string') {
        // JET-78134: in 26C rc0 preflight, line type is not editable in PRC
        // Some JS applications incorrectly pass {} as valueItem/value-item instead of null
        // or leaving it unset for the empty state. Older releases already handled that misconfiguration
        // by logging this custom error; keep that behavior and avoid throwing when item.data is missing.
        const itemData = item.data;
        if (itemData != null && Object.prototype.hasOwnProperty.call(itemData, itemText)) {
            const retData = itemData[itemText];
            return String(retData);
        }
        error(`${componentName}: itemText specifies field that does not exist: ${itemText}`);
        // return undefined if the field doesn't exist
        return undefined;
    }
    // if item-text is a function, call it to create a display label
    return itemText(item);
}

const noOp = () => { };
function DefaultList({ 'aria-label': ariaLabel, componentName, currentItemVariant, currentKey, data, itemRenderer, itemText, onCurrentKeyChange, onItemAction, onLoadRange = noOp, onSelectionChange, searchText, selectedKeys, selectionMode }) {
    const listItemRenderer = useCallback((listItemContext) => {
        // specify the listItemContext props that we want to expose individually instead of
        // spreading the whole object so that we don't automatically include any new props that
        // may be added to it
        const itemRendererProps = {
            data: listItemContext.data,
            index: listItemContext.index,
            metadata: listItemContext.metadata,
            selector: listItemContext.selector,
            searchText,
            selectedKeys,
            onSelectionChange: ({ value }) => {
                onSelectionChange?.({ value });
            }
        };
        const itemContext = {
            data: listItemContext.data,
            key: listItemContext.metadata.key,
            metadata: listItemContext.metadata
        };
        return itemRenderer ? (itemRenderer(itemRendererProps)) : (jsxs(Flex, { align: "center", children: [listItemContext.selector && (jsx("div", { class: dropdownStyles.selectorWrapper, children: listItemContext.selector() })), jsx("div", { class: selectionMode === 'single'
                        ? dropdownStyles.singleSelectItem
                        : dropdownStyles.multiSelectItem, children: jsx(ListItemText, { variant: "primary", children: jsx(HighlightText, { matchText: searchText, children: renderItemText(itemContext, itemText, componentName) }) }) })] }));
    }, [
        componentName,
        itemRenderer,
        itemText,
        onSelectionChange,
        searchText,
        selectedKeys,
        selectionMode
    ]);
    const keys = useMemo(() => {
        return { all: false, keys: selectedKeys ?? new Set() };
    }, [selectedKeys]);
    const currentItemOverride = useMemo(() => (currentKey !== undefined ? { rowKey: currentKey } : undefined), [currentKey]);
    const handleItemAction = useCallback(({ context: { data, metadata } }) => {
        onItemAction?.({ context: { data, key: metadata.key, metadata } });
    }, [onItemAction]);
    const handleSelectionChange = useCallback(({ value }) => {
        onSelectionChange?.({ value: new Set(value.keys?.values()) });
    }, [onSelectionChange]);
    return (jsx(List, { "aria-label": ariaLabel, allowTabbableMode: false, currentItemVariant: currentItemVariant, currentItemOverride: currentItemOverride, data: data ?? null, onPersistCurrentItem: onCurrentKeyChange, onItemAction: handleItemAction, onLoadRange: onLoadRange, onSelectionChange: handleSelectionChange, role: "listbox", selectedKeys: keys, selectionMode: selectionMode, children: (context) => listItemRenderer(context) }));
}

const isSimpleClick = (event) => {
    return event.button === 0 && !event.ctrlKey;
};
const preventDefault = (event) => {
    event.preventDefault();
};
const preventDefaultForCurrentTarget = (event) => {
    if (event.currentTarget === event.target) {
        event.preventDefault();
    }
};

const noop = () => { };
function DropdownArrow({ isDisabled = false, onClick, testId }) {
    const { classes } = useComponentTheme(ButtonLabelLayoutRedwoodTheme, { size: 'sm' });
    const { baseTheme } = useComponentTheme(BaseButtonRedwoodTheme);
    const preventDefault = useCallback((event) => {
        event.preventDefault();
    }, []);
    const { pressProps } = usePress(onClick ?? noop, { isDisabled });
    // TODO: JET-67410 replace this with a icon button
    const styleClasses = classNames([
        classes,
        baseTheme,
        dropdownStyles.arrow.base,
        isDisabled ? dropdownStyles.arrow.disabled : dropdownStyles.arrow.enabled
    ]);
    const testIdProps = useTestId(testId);
    return (jsx("span", { "aria-hidden": "true", class: styleClasses, tabIndex: -1, onMouseDown: preventDefault, ...testIdProps, ...pressProps, children: jsx(SvgCaretDown, {}) }));
}

function DropdownList({ children, id, dropdownListRef, hasTopGap = true, hasBottomGap = true, isLoading = false, onKeyDown }) {
    const styleClasses = classNames([
        dropdownStyles.list.base,
        hasTopGap && dropdownStyles.list.topGap,
        hasBottomGap && dropdownStyles.list.bottomGap,
        isLoading && dropdownStyles.list.loading
    ]);
    return (jsx(CollectionInteractionContext.Provider, { value: 'embedded', children: jsx("div", { ref: dropdownListRef, class: styleClasses, id: id, onMouseDown: preventDefaultForCurrentTarget, onKeyDown: onKeyDown, children: children }) }));
}

function EmptyResults() {
    const translations = useTranslationBundle('@oracle/oraclejet-preact');
    // call preventDefault for mousedown on this div so that focus does not transfer from
    // the input
    return (jsx("div", { class: dropdownStyles.results.extraItem, onMouseDown: preventDefaultForCurrentTarget, children: jsx(Text, { variant: "primary", children: translations.select_noMatchesFound() }) }));
}

/**
 * @license
 * Copyright (c) %FIRST_YEAR% %CURRENT_YEAR%, Oracle and/or its affiliates.
 * The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */
/**
 * Helper function to determine whether the current device is a mobile device
 * @returns true if running on a mobile device, false otherwise
 */
function isMobile() {
    const deviceType = getClientHints().deviceType;
    return deviceType === 'phone' || deviceType === 'tablet';
}
/**
 * Helper function to determine whether the current device is a phone
 * @returns true if running on a phone, false otherwise
 */
function isPhone() {
    return getClientHints().deviceType === 'phone';
}
/**
 * Helper function to determine whether the current device is a tablet
 * @returns true if running on a tablet, false otherwise
 */
function isTablet() {
    return getClientHints().deviceType === 'tablet';
}
function isBeforeDataFetch(data) {
    return data.sizePrecision === 'atLeast' && data.totalSize === 0;
}
function isSearchTextEmptyOrUndefined(searchText) {
    return searchText === undefined || searchText.length === 0;
}
function isSearchClearedFirstTime(prevSearchText, searchText) {
    return prevSearchText === undefined && searchText === '';
}
/**
 * Extract keys from a value items array.
 *
 * @param valueItems The value items from which the keys are to be extracted
 * @returns The set of keys
 */
function createKeysFromValueItems(valueItems) {
    const keys = valueItems?.reduce((accumKeys, currentItem) => {
        accumKeys.add(currentItem.key);
        return accumKeys;
    }, new Set());
    return keys;
}

/**
 * A custom hook that constructs the context for SelectSingle/SelectMultiple's collectionRenderer.
 * @param param0 Parameters for constructing the collection renderer context
 * @returns the CollectionRendererContext object
 */
function useCollectionRenderer({ currentKey, onCurrentKeyChange, onItemAction, onSelectedKeysChange, searchText, selectedKeys, selectedOnlyData }) {
    return useMemo$1(() => {
        const common = {
            searchText,
            currentRowKeyOverride: currentKey,
            onPersistCurrentRowKey: onCurrentKeyChange,
            selected: selectedKeys
        };
        // If onItemAction is present, then we are constructing context for SelectSingle. So,
        // return the context satisfying SelectSingleCollectionRendererContext type.
        if (onItemAction !== undefined)
            return {
                ...common,
                onRowAction: onItemAction
            };
        // If onItemAction is not present, then we are constructing context for SelectMultiple. So,
        // return the context satisfying SelectMultipleCollectionRendererContext type.
        return {
            ...common,
            onSelectedChange: onSelectedKeysChange,
            selectedOnlyData
        };
    }, [
        currentKey,
        onCurrentKeyChange,
        onItemAction,
        onSelectedKeysChange,
        searchText,
        selectedKeys,
        selectedOnlyData
    ]);
}

/**
 * @license
 * Copyright (c) %FIRST_YEAR% %CURRENT_YEAR%, Oracle and/or its affiliates.
 * The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */
/**
 * Hook that manages state and behavior for a Select* component.  This hook creates state
 * variables and event listeners, returning properties to apply to components internally
 * rendered by a Select* component, as well as state information.
 *
 * @param data Specifies data for the dropdown list.
 * @param inputRef Ref to the input element.
 * @param isFocused Specifies whether the component has focus.
 * @param onFilter Callback function to trigger loading data for the dropdown list,
 * which may or may not be filtered by user entered text.
 *
 * @returns Component state and event listeners.
 */
function useSelectCommon({ data, inputRef, isFocused, onFilter }) {
    const mainFieldRef = useRef(null);
    const dropdownRef = useRef(null);
    const [isDropdownOpen, setDropdownOpen] = useState(false);
    const [isDropdownAbove, setDropdownAbove] = useState(false);
    // We only need to push currentRow when we need to override the
    // current row, like when the dropdown is opened and we want to set the initial
    // focused row or when filtering and we want to focus the first row.
    const [currentRowOverride, _setCurrentRowOverride] = useState({
        rowKey: undefined
    });
    // We still need information on what the current row actually is, but we do not need
    // to react to it until certain scenarios like pressing Tab from the dropdown. So, we
    // just store this in a ref.
    const currentRowKeyRef = useRef();
    // When we want to update the currentRowOverride, we also want to keep the currentRowKeyRef
    // in sync as the collection will not call onChanged for this change.
    const setCurrentRowOverride = useCallback((currentRow) => {
        currentRowKeyRef.current = currentRow.rowKey;
        _setCurrentRowOverride(currentRow);
    }, []);
    const [isUserFiltering, setUserFiltering] = useState(false);
    const [userInput, setUserInput] = useState();
    const [searchText, setSearchText] = useState();
    const [prevIsDropdownOpen, setPrevIsDropdownOpen] = useState(isDropdownOpen);
    const [prevIsFocused, setPrevIsFocused] = useState(isFocused);
    const [prevIsUserFiltering, setPrevIsUserFiltering] = useState(isUserFiltering);
    const onMouseDown = useCallback((event) => {
        // const target = event.target as HTMLElement;
        if (event.defaultPrevented || !isSimpleClick(event)) {
            return;
        }
        if (!isDropdownOpen) {
            setDropdownOpen(true);
        }
        // this is needed to focus the input when clicking on the inside label when there is no
        // value;  otherwise the component looks focused but doesn't actually have physical focus
        setTimeout(function () {
            inputRef.current?.focus();
        }, 0);
    }, [inputRef, isDropdownOpen]);
    const handleDropdownArrowClick = useCallback(() => {
        setDropdownOpen(!isDropdownOpen);
        // focus the input so that if the user Tabs afterwards, it loses focus and the dropdown closes
        inputRef.current?.focus();
    }, [inputRef, isDropdownOpen]);
    const handleDropdownAutoDismiss = useCallback((event) => {
        if (isDropdownOpen) {
            setDropdownOpen(false);
            switch (event?.type) {
                case 'keydown': {
                    const keyboardEvent = event;
                    switch (keyboardEvent.code) {
                        case KEYS.ESC:
                            // focus the input when the user cancels out of the dropdown
                            inputRef.current?.focus();
                            break;
                    }
                    break;
                }
                case 'mousedown':
                    // if focus is in the dropdown, focus the input before the dropdown is hidden so that
                    // focus will transfer correctly when the target is not focusable;
                    // otherwise the text cursor appears in the input again
                    if (dropdownRef.current?.contains(document.activeElement)) {
                        inputRef.current?.focus();
                    }
                    break;
            }
        }
    }, [inputRef, isDropdownOpen]);
    const handleDropdownPosition = useCallback((data) => {
        setDropdownAbove(data.placement.startsWith('top'));
    }, []);
    const getDropdownTabbableElems = useCallback(() => {
        return isDropdownOpen && dropdownRef.current
            ? allTabbableElements(dropdownRef.current)
            : undefined;
    }, [isDropdownOpen]);
    const handleUpDownArrowKeys = useCallback((event) => {
        if (!isDropdownOpen) {
            setDropdownOpen(true);
        }
        else {
            // JET-64909 - focus / 'current' dropped when arrow keying during loading
            // Transfer physical focus into the dropdown only if the data is present and the dropdown
            // has rendered the data. Otherwise, keep the focus in the field.
            if (data != null) {
                const tabbableElems = getDropdownTabbableElems();
                tabbableElems?.[0]?.focus();
                // if there is no current item set, make the first item current
                if (currentRowOverride.rowKey === undefined) {
                    setCurrentRowOverride({ rowKey: data.data[0]?.metadata?.key });
                }
            }
        }
        // prevent the page from scrolling
        event.preventDefault();
    }, [currentRowOverride, data, getDropdownTabbableElems, isDropdownOpen, setCurrentRowOverride]);
    const handleMainFieldKeyDown = useCallback((event) => {
        // const target = event.target as HTMLElement;
        // ignore control key and function key
        if (isControlOrFunctionKey(event)) {
            return;
        }
        switch (event.code) {
            case KEYS.PAGE_UP:
            case KEYS.PAGE_DOWN:
                // prevent the page from scrolling
                event.preventDefault();
                return;
            case KEYS.UP:
            case KEYS.DOWN:
                // prevent the page from scrolling
                event.preventDefault();
                break;
            case KEYS.ESC:
                if (isDropdownOpen) {
                    setDropdownOpen(false);
                    event.preventDefault();
                    // JET-53183 - core pack compat: stop propagation of handled events
                    // we don't want a parent collection component to stop editing the row when we close
                    // the dropdown
                    event.stopPropagation();
                }
                break;
        }
    }, [isDropdownOpen]);
    const handleMainFieldKeyUp = useCallback((event) => {
        // ignore control key and function key
        if (isControlOrFunctionKey(event)) {
            return;
        }
        switch (event.code) {
            case KEYS.UP:
            case KEYS.DOWN:
                handleUpDownArrowKeys(event);
                break;
        }
    }, [handleUpDownArrowKeys]);
    const handleInput = useCallback((detail) => {
        if (!isDropdownOpen) {
            setDropdownOpen(true);
        }
        setUserFiltering(true);
        setUserInput(detail.value);
        const str = detail.value;
        setSearchText(str);
        onFilter?.({ searchText: str });
    }, [isDropdownOpen, onFilter]);
    const onCurrentKeyChange = useCallback((detail) => {
        // when the collection changes the current key, we only want to store the information
        // and not do anything.
        currentRowKeyRef.current = detail.value;
    }, []);
    const stopFiltering = useCallback(() => {
        setUserFiltering(false);
        setUserInput('');
        // Set this to `undefined` as this represents the initial state.
        // We need to do this for select-single as we need to highlight different
        // rows based on whether it is the initial dropdown navigation or empty filter navigation.
        setSearchText(undefined);
    }, []);
    const updateFiltering = useCallback((value) => {
        setUserFiltering(true);
        setUserInput(value);
        setSearchText(value);
    }, []);
    // the user is not actively filtering if the dropdown is closed and the component doesn't
    // have focus
    if (prevIsDropdownOpen !== isDropdownOpen ||
        prevIsFocused !== isFocused ||
        prevIsUserFiltering !== isUserFiltering) {
        if (!isDropdownOpen && !isFocused && isUserFiltering) {
            stopFiltering();
        }
    }
    // need to call onFilter with undefined searchText when the dropdown opens and the
    // user is NOT filtering
    useEffect(() => {
        if (isDropdownOpen && !isUserFiltering) {
            onFilter?.({ searchText: undefined });
        }
    }, [isDropdownOpen, isUserFiltering, onFilter]);
    // when the dropdown closes, reset the isDropdownAbove flag
    if (prevIsDropdownOpen !== isDropdownOpen) {
        if (!isDropdownOpen) {
            setDropdownAbove(false);
        }
        setPrevIsDropdownOpen(isDropdownOpen);
    }
    if (prevIsFocused !== isFocused) {
        setPrevIsFocused(isFocused);
    }
    if (prevIsUserFiltering !== isUserFiltering) {
        setPrevIsUserFiltering(isUserFiltering);
    }
    return {
        currentRowKeyRef,
        currentRowOverride,
        dropdownRef,
        getDropdownTabbableElems,
        handleDropdownArrowClick,
        handleDropdownAutoDismiss,
        handleDropdownPosition,
        handleInput,
        handleMainFieldKeyDown,
        handleMainFieldKeyUp,
        handleUpDownArrowKeys,
        isDropdownAbove,
        isDropdownOpen,
        // the field should remain to look focused while the dropdown is open,
        // in case physical focus is in the dropdown
        isFocused: isFocused || isDropdownOpen,
        isUserFiltering,
        mainFieldRef,
        onCurrentKeyChange,
        onMouseDown,
        searchText,
        setCurrentRowOverride,
        setDropdownOpen,
        setUserInput,
        stopFiltering,
        updateFiltering,
        userInput
    };
}

export { DefaultList as D, EmptyResults as E, DropdownArrow as a, DropdownList as b, preventDefaultForCurrentTarget as c, useSelectCommon as d, isMobile as e, isPhone as f, isTablet as g, isBeforeDataFetch as h, isSimpleClick as i, isSearchTextEmptyOrUndefined as j, isSearchClearedFirstTime as k, createKeysFromValueItems as l, preventDefault as p, renderItemText as r, useCollectionRenderer as u };
//# sourceMappingURL=useSelectCommon-a3c69d60.js.map
