grafana/public/app/features/datasource-drawer/DataSourcePickerWithHistory.tsx
Oscar Kilhed dc1600ff14
DataSourcePicker: Add new style of data source picker. (#63736)
* MVP of a new datasource picker

* Add datasource select history, naming DatasourceSelect -> DataSourceDrawer

* refactor cards

* Cleanup and fixing sort order for recents

* add feature flag

* fix feature flag name and use it

* Highlight selected

* Move new ds picker to core

* Restore original datasource picker

* Remove unused property

* update yarn.lock

* Rename folder, update codeowners

* add test for util functions

* Remove es-lint exception

* Change feature toggle description

* remove unnecessary if

Co-authored-by: Ivan Ortega Alba <ivanortegaalba@gmail.com>

* Make test a bit more clear

Co-authored-by: Ivan Ortega Alba <ivanortegaalba@gmail.com>

* Clean up api, filter once and before maps, minor code cleanup

* Fix prettier issue

---------

Co-authored-by: Ivan Ortega Alba <ivanortegaalba@gmail.com>
2023-03-01 11:26:19 +01:00

56 lines
1.7 KiB
TypeScript

import React from 'react';
import { dateTime } from '@grafana/data';
import { LocalStorageValueProvider } from 'app/core/components/LocalStorageValueProvider';
import { DataSourcePicker } from './DataSourcePicker';
import { DataSourcePickerHistoryItem, DataSourcePickerWithHistoryProps } from './types';
const DS_PICKER_STORAGE_KEY = 'DATASOURCE_PICKER';
export const DataSourcePickerWithHistory = (props: DataSourcePickerWithHistoryProps) => {
return (
<LocalStorageValueProvider<DataSourcePickerHistoryItem[]>
defaultValue={[]}
storageKey={props.localStorageKey ?? DS_PICKER_STORAGE_KEY}
>
{(rawValues, onSaveToStore) => {
return (
<DataSourcePicker
{...props}
recentlyUsed={rawValues.map((dsi) => dsi.uid)} //Filter recently to have a time cutoff
onChange={(ds) => {
onSaveToStore(updateHistory(rawValues, { uid: ds.uid, lastUse: dateTime(new Date()).toISOString() }));
props.onChange(ds);
}}
></DataSourcePicker>
);
}}
</LocalStorageValueProvider>
);
};
export function updateHistory(values: DataSourcePickerHistoryItem[], newValue: DataSourcePickerHistoryItem) {
const newHistory = values;
const existingIndex = newHistory.findIndex((dpi) => dpi.uid === newValue.uid);
if (existingIndex !== -1) {
newHistory[existingIndex] = newValue;
} else {
newHistory.push(newValue);
}
newHistory.sort((a, b) => {
const al = dateTime(a.lastUse);
const bl = dateTime(b.lastUse);
if (al.isBefore(bl)) {
return 1;
} else if (bl.isBefore(al)) {
return -1;
} else {
return 0;
}
});
return newHistory.slice(0, 3);
}