UNPKG

@grafana/ui

Version:
1 lines 3.46 kB
{"version":3,"file":"ElementSelectionContext.mjs","sources":["../../../../src/components/ElementSelectionContext/ElementSelectionContext.tsx"],"sourcesContent":["import React, { createContext, useCallback, useContext } from 'react';\n\nexport interface ElementSelectionOnSelectOptions {\n /** If specified, this will ignore the shift key press */\n multi?: boolean;\n\n /** If true, this will make sure the element is selected */\n force?: boolean;\n}\n\n/** @alpha */\nexport interface ElementSelectionContextState {\n /**\n * Turn on selection mode & show selection state\n */\n enabled?: boolean;\n /** List of currently selected elements */\n selected: ElementSelectionContextItem[];\n onSelect: (item: ElementSelectionContextItem, options: ElementSelectionOnSelectOptions) => void;\n onClear: () => void;\n}\n\nexport interface ElementSelectionContextItem {\n id: string;\n}\n\nexport const ElementSelectionContext = createContext<ElementSelectionContextState | undefined>(undefined);\n\nexport interface UseElementSelectionResult {\n isSelected?: boolean;\n isSelectable?: boolean;\n onSelect?: (evt: React.MouseEvent, options?: ElementSelectionOnSelectOptions) => void;\n onClear?: () => void;\n}\n\nexport function useElementSelection(id: string | undefined): UseElementSelectionResult {\n if (!id) {\n return {};\n }\n\n const context = useContext(ElementSelectionContext);\n if (!context) {\n return {};\n }\n\n const isSelected = context.selected.some((item) => item.id === id);\n const onSelect = useCallback(\n (evt: React.MouseEvent, options: ElementSelectionOnSelectOptions = {}) => {\n if (!context.enabled) {\n return;\n }\n\n // To prevent this click form clearing the selection\n evt.stopPropagation();\n\n // Prevent text selection caused by shift click\n if (evt.shiftKey) {\n evt.preventDefault();\n window.getSelection()?.empty();\n }\n\n context.onSelect({ id }, { ...options, multi: options.multi ?? evt.shiftKey });\n },\n [context, id]\n );\n\n const onClear = useCallback(() => {\n if (!context.enabled) {\n return;\n }\n\n context.onClear();\n }, [context]);\n\n return { isSelected, onSelect, onClear, isSelectable: context.enabled };\n}\n"],"names":[],"mappings":";;;AA0BO,MAAM,uBAAA,GAA0B,cAAwD,KAAA,CAAS;AASjG,SAAS,oBAAoB,EAAA,EAAmD;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