Skip to content

Commit

Permalink
HubListToolbar - support typeaheads
Browse files Browse the repository at this point in the history
  • Loading branch information
himdel committed Nov 6, 2023
1 parent 90a46bd commit fb547b1
Showing 1 changed file with 43 additions and 5 deletions.
48 changes: 43 additions & 5 deletions src/components/shared/hub-list-toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
ToolbarGroup,
ToolbarItem,
} from '@patternfly/react-core';
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import {
AppliedFilters,
CompoundFilter,
Expand All @@ -21,24 +21,61 @@ interface IProps {
ignoredParams: string[];
params: ParamType;
sortOptions?: SortFieldType[];
typeaheads?: Record<
string,
(inputText: string) => Promise<{ id: string; title: string }[]>
>;
updateParams: (p) => void;
}

function useTypeaheads(typeaheads, { inputText, selectedFilter }) {
const [options, setOptions] = useState({});
const loader = typeaheads[selectedFilter];
const setter = (value) =>
setOptions((options) => ({ ...options, [selectedFilter]: value }));

useEffect(() => {
if (selectedFilter && loader) {
loader('').then(setter);
}
}, [selectedFilter]);

useEffect(() => {
if (inputText && loader) {
loader(inputText).then(setter);
}
}, [inputText]);

return options;
}

// FIXME: missing Buttons & CardListSwitcher to be usable everywhere
export function HubListToolbar({
count,
filterConfig,
ignoredParams,
params,
updateParams,
filterConfig,
sortOptions,
count,
typeaheads,
updateParams,
}: IProps) {
const [inputText, setInputText] = useState('');
const [selectedFilter, setSelectedFilter] = useState(null);
const typeaheadOptions = useTypeaheads(typeaheads || {}, {
inputText,
selectedFilter,
});

const niceNames = Object.fromEntries(
filterConfig.map(({ id, title }) => [id, title]),
);

const filterWithOptions = filterConfig.map((item) =>
item.inputType !== 'typeahead'
? item
: { ...item, options: item.options || typeaheadOptions[item.id] || [] },
);

return (
<Toolbar>
<ToolbarContent>
Expand All @@ -51,10 +88,11 @@ export function HubListToolbar({
>
<ToolbarItem>
<CompoundFilter
filterConfig={filterConfig}
filterConfig={filterWithOptions}
inputText={inputText}
onChange={setInputText}
params={params}
selectFilter={setSelectedFilter}
updateParams={updateParams}
/>
</ToolbarItem>
Expand Down

0 comments on commit fb547b1

Please sign in to comment.