{"version":3,"file":"Typeahead.mjs","sources":["../../../../src/components/Typeahead/Typeahead.tsx"],"sourcesContent":["import { css } from '@emotion/css';\nimport { autoUpdate, offset, useFloating } from '@floating-ui/react';\nimport { useEffect, useMemo, useRef, useState, type PropsWithChildren } from 'react';\nimport { FixedSizeList } from 'react-window';\n\nimport { type GrafanaTheme2 } from '@grafana/data';\n\nimport { useStyles2, useTheme2 } from '../../themes/ThemeContext';\nimport { type CompletionItem, type CompletionItemGroup, CompletionItemKind } from '../../types/completion';\nimport { SelectionReference } from '../../utils/SelectionReference';\nimport { getPositioningMiddleware } from '../../utils/floating';\nimport { flattenGroupItems, calculateLongestLabel, calculateListSizes } from '../../utils/typeahead';\nimport { Portal } from '../Portal/Portal';\n\nimport { TypeaheadInfo } from './TypeaheadInfo';\nimport { TypeaheadItem } from './TypeaheadItem';\n\nconst modulo = (a: number, n: number) => a - n * Math.floor(a / n);\n\ninterface Props {\n  origin: string;\n  groupedItems: CompletionItemGroup[];\n  prefix?: string;\n  menuRef?: (el: TypeaheadMenu) => void;\n  onSelectSuggestion?: (suggestion: CompletionItem) => void;\n  isOpen?: boolean;\n}\n\n/** Imperative handle exposed via the `menuRef` prop so the keyboard plugin can drive the menu. */\nexport interface TypeaheadMenu {\n  moveMenuIndex: (moveAmount: number) => void;\n  insertSuggestion: () => void;\n}\n\nfunction useTypeaheadList(groupedItems: CompletionItemGroup[]) {\n  const theme = useTheme2();\n\n  return useMemo(() => {\n    const allItems = flattenGroupItems(groupedItems);\n    const longestLabel = calculateLongestLabel(allItems);\n    const { listWidth, listHeight, itemHeight } = calculateListSizes(theme, allItems, longestLabel);\n    return { allItems, listWidth, listHeight, itemHeight };\n  }, [groupedItems, theme]);\n}\n\nexport function Typeahead({ prefix, isOpen = false, groupedItems, menuRef, onSelectSuggestion }: Props) {\n  const listRef = useRef<FixedSizeList>(null);\n\n  const [hoveredItem, setHoveredItem] = useState<number | null>(null);\n  const [typeaheadIndex, setTypeaheadIndex] = useState<number | null>(null);\n  const { allItems, listWidth, listHeight, itemHeight } = useTypeaheadList(groupedItems);\n\n  // Reset the highlighted suggestion whenever the items change. Assigning state during render is the\n  // React-recommended way to adjust state in response to a changed prop: it re-renders immediately\n  // instead of committing the stale selection first, which an effect would not avoid.\n  const [prevGroupedItems, setPrevGroupedItems] = useState(groupedItems);\n  if (groupedItems !== prevGroupedItems) {\n    setPrevGroupedItems(groupedItems);\n    setTypeaheadIndex(null);\n  }\n\n  // The menu handle is stable, but the keyboard plugin invokes it outside of render, so the methods\n  // read the latest props/state through a ref and functional state updates.\n  const latest = useRef({ allItems, typeaheadIndex, onSelectSuggestion });\n  latest.current = { allItems, typeaheadIndex, onSelectSuggestion };\n\n  const menu = useMemo<TypeaheadMenu>(\n    () => ({\n      moveMenuIndex: (moveAmount: number) => {\n        const itemCount = latest.current.allItems.length;\n        if (!itemCount) {\n          return;\n        }\n        setTypeaheadIndex((current) => {\n          // Select next suggestion\n          let newTypeaheadIndex = modulo((current || 0) + moveAmount, itemCount);\n\n          if (latest.current.allItems[newTypeaheadIndex].kind === CompletionItemKind.GroupTitle) {\n            newTypeaheadIndex = modulo(newTypeaheadIndex + moveAmount, itemCount);\n          }\n\n          return newTypeaheadIndex;\n        });\n      },\n      insertSuggestion: () => {\n        const { onSelectSuggestion, allItems, typeaheadIndex } = latest.current;\n        if (onSelectSuggestion && typeaheadIndex !== null) {\n          onSelectSuggestion(allItems[typeaheadIndex]);\n        }\n      },\n    }),\n    []\n  );\n\n  useEffect(() => {\n    menuRef?.(menu);\n  }, [menuRef, menu]);\n\n  useEffect(() => {\n    if (typeaheadIndex === null || !listRef.current) {\n      return;\n    }\n    if (typeaheadIndex === 1) {\n      listRef.current.scrollToItem(0); // special case for handling the first group label\n      return;\n    }\n    listRef.current.scrollToItem(typeaheadIndex);\n  }, [typeaheadIndex]);\n\n  const styles = useStyles2(getStyles);\n\n  const showDocumentation = hoveredItem || typeaheadIndex;\n  const documentationItem = allItems[hoveredItem ? hoveredItem : typeaheadIndex || 0];\n\n  return (\n    <TypeaheadPortal isOpen={isOpen}>\n      <ul role=\"menu\" className={styles.typeahead} data-testid=\"typeahead\">\n        <FixedSizeList\n          ref={listRef}\n          itemCount={allItems.length}\n          itemSize={itemHeight}\n          itemKey={(index) => {\n            const item = allItems && allItems[index];\n            const key = item ? `${index}-${item.label}` : `${index}`;\n            return key;\n          }}\n          width={listWidth}\n          height={listHeight}\n        >\n          {({ index, style }) => {\n            const item = allItems && allItems[index];\n            if (!item) {\n              return null;\n            }\n\n            return (\n              <TypeaheadItem\n                onClickItem={() => (onSelectSuggestion ? onSelectSuggestion(item) : {})}\n                isSelected={typeaheadIndex === null ? false : allItems[typeaheadIndex] === item}\n                item={item}\n                prefix={prefix}\n                style={style}\n                onMouseEnter={() => setHoveredItem(index)}\n                onMouseLeave={() => setHoveredItem(null)}\n              />\n            );\n          }}\n        </FixedSizeList>\n      </ul>\n\n      {showDocumentation && <TypeaheadInfo height={listHeight} item={documentationItem} />}\n    </TypeaheadPortal>\n  );\n}\n\n/**\n * Positions the typeahead menu next to the caret in the Slate editor and renders it into the\n * shared overlay portal. Uses floating-ui with a selection-anchored virtual reference, the same\n * pattern used by other caret-anchored menus (e.g. DataLinkInput).\n */\nfunction TypeaheadPortal({ isOpen, children }: PropsWithChildren<{ isOpen: boolean }>) {\n  const { refs, floatingStyles, update } = useFloating({\n    open: isOpen,\n    placement: 'bottom-start',\n    strategy: 'fixed',\n    // Mirror the previous manual offsets: 6px below the caret line, nudged 2px to the left.\n    middleware: [offset({ mainAxis: 6, crossAxis: -2 }), ...getPositioningMiddleware('bottom-start')],\n    whileElementsMounted: autoUpdate,\n  });\n\n  // Anchor positioning to the current text selection (the caret). Set once; the virtual element\n  // reads the live selection rect on every reposition.\n  useEffect(() => {\n    refs.setReference(new SelectionReference());\n  }, [refs]);\n\n  // The caret moves as the user types or navigates, so reposition on selection changes while open.\n  useEffect(() => {\n    if (!isOpen) {\n      return;\n    }\n    document.addEventListener('selectionchange', update);\n    return () => document.removeEventListener('selectionchange', update);\n  }, [isOpen, update]);\n\n  if (!isOpen) {\n    return null;\n  }\n\n  // The `slate-typeahead--open` class is a behavioural hook: keybindingSrv queries for it so the\n  // global Esc handler defers to the typeahead while suggestions are open.\n  return (\n    <Portal>\n      {/* display: flex lays the suggestion list and the documentation panel out side by side. */}\n      <div ref={refs.setFloating} style={{ ...floatingStyles, display: 'flex' }} className=\"slate-typeahead--open\">\n        {children}\n      </div>\n    </Portal>\n  );\n}\n\nconst getStyles = (theme: GrafanaTheme2) => ({\n  typeahead: css({\n    position: 'relative',\n    zIndex: theme.zIndex.typeahead,\n    borderRadius: theme.shape.radius.default,\n    border: `1px solid ${theme.components.panel.borderColor}`,\n    maxHeight: '66vh',\n    overflowY: 'scroll',\n    overflowX: 'hidden',\n    outline: 'none',\n    listStyle: 'none',\n    background: theme.components.panel.background,\n    color: theme.colors.text.primary,\n    boxShadow: theme.shadows.z2,\n\n    strong: {\n      color: theme.v1.palette.yellow,\n    },\n  }),\n});\n"],"names":["onSelectSuggestion","allItems","typeaheadIndex"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAM,MAAA,GAAS,CAAC,CAAA,EAAW,CAAA,KAAc,IAAI,CAAA,GAAI,IAAA,CAAK,KAAA,CAAM,CAAA,GAAI,CAAC,CAAA;AAiBjE,SAAS,iBAAiB,YAAA,EAAqC;AAC7D,EAAA,MAAM,QAAQ,SAAA,EAAU;AAExB,EAAA,OAAO,QAAQ,MAAM;AACnB,IAAA,MAAM,QAAA,GAAW,kBAAkB,YAAY,CAAA;AAC/C,IAAA,MAAM,YAAA,GAAe,sBAAsB,QAAQ,CAAA;AACnD,IAAA,MAAM,EAAE,WAAW,UAAA,EAAY,UAAA,KAAe,kBAAA,CAAmB,KAAA,EAAO,UAAU,YAAY,CAAA;AAC9F,IAAA,OAAO,EAAE,QAAA,EAAU,SAAA,EAAW,UAAA,EAAY,UAAA,EAAW;AAAA,EACvD,CAAA,EAAG,CAAC,YAAA,EAAc,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