import { FormEventHandler, ForwardedRef, KeyboardEventHandler, forwardRef, useDeferredValue, useEffect, useRef, } from 'react' import { observer } from 'mobx-react-lite' import { classNames } from '@standardnotes/utils' import { LinkingController } from '@/Controllers/LinkingController' import { ElementIds } from '@/Constants/ElementIDs' import { getLinkingSearchResults } from '@/Utils/Items/Search/getSearchResults' import { useApplication } from '../ApplicationProvider' import { DecryptedItem, SNNote } from '@standardnotes/snjs' import { Combobox, ComboboxItem, ComboboxPopover, useComboboxStore, VisuallyHidden } from '@ariakit/react' import LinkedItemMeta from './LinkedItemMeta' import { LinkedItemSearchResultsAddTagOption } from './LinkedItemSearchResultsAddTagOption' import { Slot } from '@radix-ui/react-slot' import Icon from '../Icon/Icon' import { PremiumFeatureIconName } from '../Icon/PremiumFeatureIcon' import { KeyboardKey } from '@standardnotes/ui-services' import { mergeRefs } from '@/Hooks/mergeRefs' type Props = { linkingController: LinkingController focusPreviousItem: () => void focusedId: string | undefined setFocusedId: (id: string) => void hoverLabel?: string item: DecryptedItem } const ItemLinkAutocompleteInput = forwardRef( ( { linkingController, focusPreviousItem, focusedId, setFocusedId, hoverLabel, item }: Props, forwardedRef: ForwardedRef, ) => { const application = useApplication() const { getLinkedTagsForItem, linkItems, createAndAddNewTag, isEntitledToNoteLinking } = linkingController const tagsLinkedToItem = getLinkedTagsForItem(item) || [] const combobox = useComboboxStore() const value = combobox.useState('value') const searchQuery = useDeferredValue(value) const { unlinkedItems, shouldShowCreateTag } = getLinkingSearchResults(searchQuery, application, item) const inputRef = useRef(null) const onFormSubmit: FormEventHandler = async (event) => { event.preventDefault() if (searchQuery !== '') { await createAndAddNewTag(searchQuery) combobox.setValue('') } } const handleFocus = () => { if (focusedId !== ElementIds.ItemLinkAutocompleteInput) { setFocusedId(ElementIds.ItemLinkAutocompleteInput) } } const onKeyDown: KeyboardEventHandler = (event) => { switch (event.key) { case KeyboardKey.Left: if (searchQuery.length === 0) { focusPreviousItem() } break } } useEffect(() => { if (focusedId === ElementIds.ItemLinkAutocompleteInput) { inputRef.current?.focus() } }, [focusedId]) return (
{unlinkedItems.map((result) => { const cannotLinkItem = !isEntitledToNoteLinking && result instanceof SNNote return ( { linkItems(item, result).catch(console.error) combobox.setValue('') }} > {cannotLinkItem && } ) })} {shouldShowCreateTag && ( { void createAndAddNewTag(searchQuery) combobox.setValue('') }} > )}
) }, ) export default observer(ItemLinkAutocompleteInput)