Explore: Fix a bug where Typeahead crashes when a large amount of ite… (#29637)

* Explore: Fix a bug where Typeahead crashes when a large amount of items is given

* Fix format

* Improve memory efficiency of flattenGroupItems
This commit is contained in:
Takahiro Suzuki 2021-01-19 18:38:46 +09:00 committed by GitHub
parent a310511571
commit c95928a1d9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 5 deletions

View File

@ -3,7 +3,7 @@ import { mount } from 'enzyme';
import { Typeahead, State } from './Typeahead';
import { TypeaheadItem } from './TypeaheadItem';
import { CompletionItemKind } from '../../types';
import { CompletionItemGroup, CompletionItemKind } from '../../types';
describe('Typeahead', () => {
const completionItemGroups = [{ label: 'my group', items: [{ label: 'first item' }] }];
@ -43,4 +43,14 @@ describe('Typeahead', () => {
expect(items.get(0).props.isSelected).toBeFalsy();
expect(items.get(1).props.isSelected).toBeTruthy();
});
it('can be rendered properly even if the size of items is large', () => {
const completionItemGroups: CompletionItemGroup[] = [{ label: 'my group', items: [] }];
const itemsSize = 1000000;
for (let i = 0; i < itemsSize; i++) {
completionItemGroups[0].items.push({ label: 'item' + i });
}
const component = mount(<Typeahead origin="test" groupedItems={completionItemGroups} isOpen />);
expect(component.find('.typeahead')).toHaveLength(1);
});
});

View File

@ -4,12 +4,14 @@ import { GrafanaTheme } from '@grafana/data';
export const flattenGroupItems = (groupedItems: CompletionItemGroup[]): CompletionItem[] => {
return groupedItems.reduce((all: CompletionItem[], { items, label }) => {
const titleItem: CompletionItem = {
all.push({
label,
kind: CompletionItemKind.GroupTitle,
};
all.push(titleItem, ...items);
return all;
});
return items.reduce((all, item) => {
all.push(item);
return all;
}, all);
}, []);
};