From c95928a1d9669c661673688b9c66109205030e5c Mon Sep 17 00:00:00 2001 From: Takahiro Suzuki Date: Tue, 19 Jan 2021 18:38:46 +0900 Subject: [PATCH] =?UTF-8?q?Explore:=20Fix=20a=20bug=20where=20Typeahead=20?= =?UTF-8?q?crashes=20when=20a=20large=20amount=20of=20ite=E2=80=A6=20(#296?= =?UTF-8?q?37)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Explore: Fix a bug where Typeahead crashes when a large amount of items is given * Fix format * Improve memory efficiency of flattenGroupItems --- .../src/components/Typeahead/Typeahead.test.tsx | 12 +++++++++++- packages/grafana-ui/src/utils/typeahead.ts | 10 ++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/grafana-ui/src/components/Typeahead/Typeahead.test.tsx b/packages/grafana-ui/src/components/Typeahead/Typeahead.test.tsx index 34cac0ba896..ffe7380e941 100644 --- a/packages/grafana-ui/src/components/Typeahead/Typeahead.test.tsx +++ b/packages/grafana-ui/src/components/Typeahead/Typeahead.test.tsx @@ -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(); + expect(component.find('.typeahead')).toHaveLength(1); + }); }); diff --git a/packages/grafana-ui/src/utils/typeahead.ts b/packages/grafana-ui/src/utils/typeahead.ts index 6842a72296d..980cbe63a61 100644 --- a/packages/grafana-ui/src/utils/typeahead.ts +++ b/packages/grafana-ui/src/utils/typeahead.ts @@ -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); }, []); };