UNPKG

@grafana/ui

Version:
1 lines 3.36 kB
{"version":3,"file":"useMeasureMulti.mjs","sources":["../../../../src/components/Combobox/useMeasureMulti.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\nimport { useMeasure } from 'react-use';\n\nimport { measureText } from '../../utils/measureText';\n\nimport { ComboboxOption } from './types';\n\nconst FONT_SIZE = 12;\nconst EXTRA_PILL_SIZE = 50;\nconst EXTRA_PILL_DISABLED_SIZE = 10;\nexport const MAX_SHOWN_ITEMS = 15;\n\n/**\n * Updates the number of shown items in the multi combobox based on the available width.\n */\nexport function useMeasureMulti<T extends string | number>(\n selectedItems: Array<ComboboxOption<T>>,\n width?: number | 'auto',\n disabled?: boolean\n) {\n const [shownItems, setShownItems] = useState<number>(selectedItems.length);\n const [measureRef, { width: containerWidth }] = useMeasure<HTMLDivElement>();\n const [counterMeasureRef, { width: counterWidth }] = useMeasure<HTMLDivElement>();\n const [suffixMeasureRef, { width: suffixWidth }] = useMeasure<HTMLDivElement>();\n\n const finalWidth = width && width !== 'auto' ? width : containerWidth;\n\n useEffect(() => {\n const maxWidth = finalWidth - counterWidth - suffixWidth;\n let currWidth = 0;\n for (let i = 0; i < selectedItems.length; i++) {\n // Measure text width and add size of padding, separator and close button\n currWidth +=\n measureText(selectedItems[i].label || '', FONT_SIZE).width +\n (disabled ? EXTRA_PILL_DISABLED_SIZE : EXTRA_PILL_SIZE);\n if (currWidth > maxWidth) {\n // If there is no space for that item, show the current number of items,\n // but always show at least 1 item. Cap at maximum number of items.\n setShownItems(Math.min(i, MAX_SHOWN_ITEMS) || 1);\n break;\n }\n if (i === selectedItems.length - 1) {\n // If it is the last item, show all items\n setShownItems(selectedItems.length);\n }\n }\n }, [finalWidth, counterWidth, suffixWidth, selectedItems, setShownItems, disabled]);\n\n return { measureRef, counterMeasureRef, suffixMeasureRef, shownItems };\n}\n"],"names":[],"mappings":";;;;;AAOA,MAAM,SAAA,GAAY,EAAA;AAClB,MAAM,eAAA,GAAkB,EAAA;AACx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