Grafana UI: Make DashboardPicker focusable (#104242)

This commit is contained in:
Juan Cabanas
2025-04-24 11:27:04 -03:00
committed by GitHub
parent 08205d64d1
commit 20b50e5f16
3 changed files with 64 additions and 62 deletions
@@ -1,5 +1,5 @@
import { isArray, negate } from 'lodash'; import { isArray, negate } from 'lodash';
import { ComponentProps, useCallback, useEffect, useRef, useState } from 'react'; import { ComponentProps, useCallback, useEffect, useRef, useState, useImperativeHandle } from 'react';
import * as React from 'react'; import * as React from 'react';
import { import {
default as ReactSelect, default as ReactSelect,
@@ -152,16 +152,19 @@ export function SelectBase<T, Rest = {}>({
isValidNewOption, isValidNewOption,
formatOptionLabel, formatOptionLabel,
hideSelectedOptions, hideSelectedOptions,
selectRef,
...rest ...rest
}: SelectBaseProps<T> & Rest) { }: SelectBaseProps<T> & Rest) {
const theme = useTheme2(); const theme = useTheme2();
const styles = getSelectStyles(theme); const styles = getSelectStyles(theme);
const reactSelectRef = useRef<{ controlRef: HTMLElement }>(null); const reactSelectRef = useRef<HTMLElement & { controlRef: HTMLElement }>(null);
const [closeToBottom, setCloseToBottom] = useState<boolean>(false); const [closeToBottom, setCloseToBottom] = useState<boolean>(false);
const selectStyles = useCustomSelectStyles(theme, width); const selectStyles = useCustomSelectStyles(theme, width);
const [hasInputValue, setHasInputValue] = useState<boolean>(!!inputValue); const [hasInputValue, setHasInputValue] = useState<boolean>(!!inputValue);
useImperativeHandle(selectRef, () => reactSelectRef.current!, []);
// Infer the menu position for asynchronously loaded options. menuPlacement="auto" doesn't work when the menu is // Infer the menu position for asynchronously loaded options. menuPlacement="auto" doesn't work when the menu is
// automatically opened when the component is created (it happens in SegmentSelect by setting menuIsOpen={true}). // automatically opened when the component is created (it happens in SegmentSelect by setting menuIsOpen={true}).
// We can remove this workaround when the bug in react-select is fixed: https://github.com/JedWatson/react-select/issues/4936 // We can remove this workaround when the bug in react-select is fixed: https://github.com/JedWatson/react-select/issues/4936
@@ -116,6 +116,8 @@ export interface SelectCommonProps<T> {
loadingMessage?: string; loadingMessage?: string;
/** Disables wrapping of multi value values when closed */ /** Disables wrapping of multi value values when closed */
noMultiValueWrap?: boolean; noMultiValueWrap?: boolean;
/** Use a custom ref because generic component as output of React.forwardRef is not directly possible */
selectRef?: React.Ref<HTMLElement>;
} }
export interface SelectAsyncProps<T> { export interface SelectAsyncProps<T> {
@@ -1,5 +1,5 @@
import debounce from 'debounce-promise'; import debounce from 'debounce-promise';
import { useCallback, useEffect, useState } from 'react'; import { forwardRef, useCallback, useEffect, useState } from 'react';
import { SelectableValue } from '@grafana/data'; import { SelectableValue } from '@grafana/data';
import { AsyncSelectProps, AsyncSelect } from '@grafana/ui'; import { AsyncSelectProps, AsyncSelect } from '@grafana/ui';
@@ -38,72 +38,69 @@ async function findDashboards(query = '') {
const getDashboards = debounce(findDashboards, 250, { leading: true }); const getDashboards = debounce(findDashboards, 250, { leading: true });
// TODO: this component should provide a way to apply different filters to the search APIs // TODO: this component should provide a way to apply different filters to the search APIs
export const DashboardPicker = ({ export const DashboardPicker = forwardRef<HTMLElement, Props>(
value, ({ value, onChange, placeholder = 'Select dashboard', noOptionsMessage = 'No dashboards found', ...props }, ref) => {
onChange, const [current, setCurrent] = useState<SelectableValue<DashboardPickerDTO>>();
placeholder = 'Select dashboard',
noOptionsMessage = 'No dashboards found',
...props
}: Props) => {
const [current, setCurrent] = useState<SelectableValue<DashboardPickerDTO>>();
// This is required because the async select does not match the raw uid value // This is required because the async select does not match the raw uid value
// We can not use a simple Select because the dashboard search should not return *everything* // We can not use a simple Select because the dashboard search should not return *everything*
useEffect(() => { useEffect(() => {
if (!value || value === current?.value?.uid) { if (!value || value === current?.value?.uid) {
return; return;
} }
(async () => { (async () => {
// value was manually changed from outside or we are rendering for the first time. // value was manually changed from outside or we are rendering for the first time.
// We need to fetch dashboard information. // We need to fetch dashboard information.
const dto = await getDashboardAPI().getDashboardDTO(value, undefined); const dto = await getDashboardAPI().getDashboardDTO(value, undefined);
if (isDashboardV2Resource(dto)) { if (isDashboardV2Resource(dto)) {
setCurrent({
value: {
uid: dto.metadata.name,
title: dto.spec.title,
folderTitle: dto.metadata.annotations?.[AnnoKeyFolderTitle],
folderUid: dto.metadata.annotations?.[AnnoKeyFolder],
},
label: formatLabel(dto.metadata.annotations?.[AnnoKeyFolder], dto.spec.title),
});
} else {
if (dto.dashboard) {
setCurrent({ setCurrent({
value: { value: {
uid: dto.dashboard.uid, uid: dto.metadata.name,
title: dto.dashboard.title, title: dto.spec.title,
folderTitle: dto.meta.folderTitle, folderTitle: dto.metadata.annotations?.[AnnoKeyFolderTitle],
folderUid: dto.meta.folderUid, folderUid: dto.metadata.annotations?.[AnnoKeyFolder],
}, },
label: formatLabel(dto.meta?.folderTitle, dto.dashboard.title), label: formatLabel(dto.metadata.annotations?.[AnnoKeyFolder], dto.spec.title),
}); });
} else {
if (dto.dashboard) {
setCurrent({
value: {
uid: dto.dashboard.uid,
title: dto.dashboard.title,
folderTitle: dto.meta.folderTitle,
folderUid: dto.meta.folderUid,
},
label: formatLabel(dto.meta?.folderTitle, dto.dashboard.title),
});
}
} }
} })();
})(); // we don't need to rerun this effect every time `current` changes
// we don't need to rerun this effect every time `current` changes // eslint-disable-next-line react-hooks/exhaustive-deps
// eslint-disable-next-line react-hooks/exhaustive-deps }, [value]);
}, [value]);
const onPicked = useCallback( const onPicked = useCallback(
(sel: SelectableValue<DashboardPickerDTO>) => { (sel: SelectableValue<DashboardPickerDTO>) => {
setCurrent(sel); setCurrent(sel);
onChange?.(sel?.value); onChange?.(sel?.value);
}, },
[onChange, setCurrent] [onChange, setCurrent]
); );
return ( return (
<AsyncSelect <AsyncSelect
loadOptions={getDashboards} loadOptions={getDashboards}
onChange={onPicked} onChange={onPicked}
placeholder={placeholder} placeholder={placeholder}
noOptionsMessage={noOptionsMessage} noOptionsMessage={noOptionsMessage}
value={current} value={current}
defaultOptions={true} defaultOptions={true}
{...props} {...props}
/> selectRef={ref}
); />
}; );
}
);