import React, { FC, useCallback, useContext, useEffect, useRef, useState } from 'react' import { convertPrimitiveToString, wait, waitForElement } from '../../../../../../common/utils' import { OmniFilterContext } from '../../../../../OmniSearch' import { AutoSizeInput } from '../../../../auto-size-input/AutoSizeInput' import { FilterItemContext } from '../../../../filter-item/FilterItem' import { InputSegment } from '../../../../input-segment/InputSegment' import { typeGuardPrimitiveValue } from '../../../value-segment/ValueSegment' import { ValueSegmentProps, useFilterItemSegmentStyles } from '../../ValueSegments' export const SinglewithoutOptions: FC = ({ index, }) => { // hooks const styles = useFilterItemSegmentStyles() // refs const containerRef = useRef(null) const inputRef = useRef(null) // context const { focusMode, focusedSegmentIndex, focusedFilterIndex, } = useContext(OmniFilterContext) const { filter: { operator, value }, filterIndex, onChangeValue, } = useContext(FilterItemContext) // memoized values and constants const isSelected = (focusMode === 'segment' || focusMode === 'cursor') && (focusedFilterIndex === filterIndex) && (focusedSegmentIndex === index) const primitiveValue = typeGuardPrimitiveValue(operator, value) || '' // state const [displayValue, setDisplayValue] = useState(convertPrimitiveToString(primitiveValue)) const [renderChildren, setRenderChildren] = useState(false) // imperative logic const selectAll = useCallback(() => { if (!inputRef.current) return inputRef.current.setSelectionRange(0, inputRef.current.value.length) }, []) // side effects useEffect(() => { if (isSelected && !document.activeElement?.isSameNode(inputRef.current)) { inputRef.current?.focus() if (focusMode === 'segment') { selectAll() } } }, [focusMode, isSelected, selectAll]) useEffect(() => { onChangeValue(displayValue) }, [displayValue, onChangeValue]) useEffect(() => { const waitForContainer = async () => { while (!containerRef.current) { await wait(50) } setRenderChildren(true) } waitForContainer() }, []) // event handlers const handleInputChange = useCallback((event: React.ChangeEvent) => { setDisplayValue(event.target.value) }, []) const handleFocusInput = useCallback(() => { requestAnimationFrame(async () => { await waitForElement(inputRef.current) inputRef.current?.focus() }) }, []) return ( {renderChildren && ( )} ) }