Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Dropdown component & add automatic "null option" #1517

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions frontend/src/Components/Dropdown/Dropdown.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

@import 'src/mixins';

.italic {
font-style: italic;
}

// label som wrapper
.select_wrapper {
display: flex;
Expand Down
94 changes: 63 additions & 31 deletions frontend/src/Components/Dropdown/Dropdown.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,74 @@
import type { ComponentMeta, ComponentStory } from '@storybook/react';
import type { ComponentMeta, ComponentStory, Meta, StoryObj } from '@storybook/react';
import { Dropdown } from './Dropdown';

// Local component config.
export default {
const meta = {
title: 'Components/Dropdown',
component: Dropdown,
} satisfies Meta<typeof Dropdown>;

export default meta;

type Story = StoryObj<typeof meta>;

const options = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Orange', value: 'orange' },
{ label: 'Mango', value: 'mango' },
];

const onChange = (value: unknown) => console.log('Selected:', value);

// Basic uncontrolled dropdown
export const Basic: Story = {
args: {
options,
onChange,
},
};

// With default value
export const WithDefaultValue: Story = {
args: {
options,
defaultValue: 'banana',
onChange,
},
};

// With null option
export const WithNullOption: Story = {
args: {
name: 'name',
label: 'Choose option',
options,
nullOption: true,
onChange,
},
} as ComponentMeta<typeof Dropdown>;
};

const Template: ComponentStory<typeof Dropdown> = (args) => <Dropdown {...args} />;
// With custom null option
export const WithCustomNullOption: Story = {
args: {
options,
nullOption: { label: 'Select a fruit...', disabled: false },
onChange,
},
};

export const Basic = Template.bind({});
Basic.args = {
options: [
{ label: 'alternativ 1', value: 1 },
{ label: 'alternativ 2', value: 2 },
],
// With disabled null option (can't reselect null after choosing a value)
export const WithDisabledNullOption: Story = {
args: {
options,
nullOption: { label: 'Select a fruit...', disabled: true },
onChange,
},
};
export const Many = Template.bind({});
Many.args = {
options: [
{ label: 'alternativ 1', value: 1 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
{ label: 'alternativ 2', value: 2 },
],

// With label
export const WithLabel: Story = {
args: {
options,
label: 'Favorite Fruit',
onChange,
},
};
94 changes: 67 additions & 27 deletions frontend/src/Components/Dropdown/Dropdown.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,43 @@
import { Icon } from '@iconify/react';
import { default as classNames, default as classnames } from 'classnames';
import React, { type ChangeEvent, type ReactElement } from 'react';
import React, { type ChangeEvent, type ReactNode, useMemo } from 'react';
import styles from './Dropdown.module.scss';

export type DropDownOption<T> = {
export type DropdownOption<T> = {
label: string;
value: T;
disabled?: boolean;
};

type NullOption = {
label: string;
disabled?: boolean;
};

export type DropdownProps<T> = {
type PrimitiveDropdownProps<T> = {
className?: string;
classNameSelect?: string;
defaultValue?: DropDownOption<T>; // issue 1089
value?: T;
disableIcon?: boolean;
options?: DropDownOption<T>[];
label?: string | ReactElement;
options?: DropdownOption<T>[];
label?: string | ReactNode;
disabled?: boolean;
error?: boolean;
onChange?: (value?: T) => void;
disableIcon?: boolean;
nullOption?: boolean | NullOption;
onChange?: (value: T) => void;
};

type ControlledDropdownProps<T> = PrimitiveDropdownProps<T> & {
value: T | null;
defaultValue?: never;
};

type UncontrolledDropdownProps<T> = PrimitiveDropdownProps<T> & {
value?: never;
defaultValue?: T | null;
};

export type DropdownProps<T> = ControlledDropdownProps<T> | UncontrolledDropdownProps<T>;

function DropdownInner<T>(
{
options = [],
Expand All @@ -32,23 +49,45 @@ function DropdownInner<T>(
label,
disabled = false,
disableIcon = false,
nullOption = false,
error,
}: DropdownProps<T>,
ref: React.Ref<HTMLSelectElement>,
) {
/**
* Handles the raw change event from <option>
* The raw value choice is an index where -1 is reserved for
* the empty/default option. Depending on the index selected
* the onChange callback is provided with the respective DropDownOption
* @param e Standard onChange HTML event for dropdown
*/
function handleChange(e?: ChangeEvent<HTMLSelectElement>) {
const choice = Number.parseInt(e?.currentTarget.value ?? '-1', 10);
if (choice >= 0 && choice < options.length) {
onChange?.(options[choice].value);
} else {
onChange?.(defaultValue?.value ?? options[0]?.value);
const isControlled = value !== undefined;

const finalOptions = useMemo<DropdownOption<T>[]>(() => {
let opts = [...options];

if (!nullOption) {
return options;
}

if (nullOption) {
if (typeof nullOption === 'boolean') {
opts = [{ value: null, label: '' } as DropdownOption<T>, ...opts];
} else {
opts = [{ value: null, label: nullOption.label, disabled: nullOption.disabled } as DropdownOption<T>, ...opts];
}
}

return opts;
}, [options, nullOption]);

const selectedIndex = useMemo(() => {
if (isControlled) {
return finalOptions.findIndex((opt) => opt.value === value);
}
if (defaultValue !== undefined) {
return finalOptions.findIndex((opt) => opt.value === defaultValue);
}
return 0; // fall back to selecting first element
}, [isControlled, value, defaultValue, finalOptions]);

function handleChange(event: ChangeEvent<HTMLSelectElement>) {
const index = Number.parseInt(event.currentTarget.value, 10);
if (index >= 0 && index < finalOptions.length) {
onChange?.(finalOptions[index].value);
}
}

Expand All @@ -62,16 +101,17 @@ function DropdownInner<T>(
styles.samf_select,
!disableIcon && styles.icon_disabled,
error && styles.error,
nullOption && finalOptions[selectedIndex].value === finalOptions[0].value && styles.italic,
)}
onChange={handleChange}
disabled={disabled}
value={value !== undefined ? options.findIndex((e) => e.value === value) : -1}
defaultValue={!isControlled ? selectedIndex : undefined}
value={isControlled ? selectedIndex : undefined}
>
{defaultValue && <option value={-1}>{defaultValue.label}</option>}
{options.map((opt, index) => (
{finalOptions.map(({ label, value, ...props }, index) => (
// biome-ignore lint/suspicious/noArrayIndexKey: no other unique value available
<option value={index} key={index}>
{opt.label}
<option value={index} key={index} {...props}>
{label}
</option>
))}
</select>
Expand Down
37 changes: 18 additions & 19 deletions frontend/src/Components/EventQuery/EventQuery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { getEventGroups, getVenues } from '~/api';
import type { EventDto, EventGroupDto, VenueDto } from '~/dto';
import { KEY } from '~/i18n/constants';
import type { SetState } from '~/types';
import { lowerCapitalize } from '~/utils';
import { Dropdown } from '../Dropdown';
import type { DropDownOption } from '../Dropdown/Dropdown';
import type { DropdownOption } from '../Dropdown/Dropdown';
import styles from './EventQuery.module.scss';
import { eventQuery } from './utils';

Expand All @@ -24,8 +25,8 @@ export function EventQuery({ allEvents, setEvents }: EventQueryProps) {

// Search
const [search, setSearch] = useState<string>('');
const [selectedVenue, setSelectedVenue] = useState<VenueDto>();
const [selectedEventGroup, setSelectedEventGroup] = useState<EventGroupDto>();
const [selectedVenue, setSelectedVenue] = useState<VenueDto | null>();
const [selectedEventGroup, setSelectedEventGroup] = useState<EventGroupDto | null>();

// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
useEffect(() => {
Expand All @@ -37,19 +38,19 @@ export function EventQuery({ allEvents, setEvents }: EventQueryProps) {
.catch(console.error);
}, [allEvents]);

const venueOptions: DropdownOption<number | null>[] = venues.map((venue) => {
return { label: venue.name ?? '', value: venue.id } as DropdownOption<number>;
});

const eventGroupOptions: DropdownOption<number | null>[] = eventGroups.map((group) => {
return { label: group.name ?? '', value: group.id };
});

// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
useEffect(() => {
setEvents(eventQuery(allEvents, search, selectedVenue));
}, [search, selectedVenue, selectedEventGroup]);

const venueOptions: DropDownOption<VenueDto>[] = venues.map((venue) => {
return { label: venue.name ?? '', value: venue };
});

const eventGroupOptions: DropDownOption<EventGroupDto>[] = eventGroups.map((group) => {
return { label: group.name ?? '', value: group };
});

return (
<div className={styles.queryBar}>
<InputField
Expand All @@ -58,20 +59,18 @@ export function EventQuery({ allEvents, setEvents }: EventQueryProps) {
labelClassName={styles.searchBar}
icon="ic:baseline-search"
/>
<Dropdown<VenueDto | undefined>
<Dropdown
options={venueOptions}
value={selectedVenue}
onChange={(venue) => setSelectedVenue(venue)}
onChange={(val) => setSelectedVenue(venues.find((v) => v.id === val))}
className={styles.element}
defaultValue={{ label: `${t(KEY.common_choose)} ${t(KEY.common_venue)}`, value: undefined }}
nullOption={{ label: lowerCapitalize(`${t(KEY.common_choose)} ${t(KEY.common_venue)}`) }}
/>

<Dropdown<EventGroupDto | undefined>
<Dropdown
options={eventGroupOptions}
value={selectedEventGroup}
onChange={(group) => setSelectedEventGroup(group)}
onChange={(val) => setSelectedEventGroup(eventGroups.find((eg) => eg.id === val))}
className={styles.element}
defaultValue={{ label: `${t(KEY.common_choose)} ${t(KEY.event_type)}`, value: undefined }}
nullOption={{ label: lowerCapitalize(`${t(KEY.common_choose)} ${t(KEY.event_type)}`) }}
/>
</div>
);
Expand Down
10 changes: 4 additions & 6 deletions frontend/src/Components/EventQuery/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,11 @@ function toRepresentation(event: EventDto): string {
`;
}

export function eventQuery(events: EventDto[], search: string, venue?: VenueDto): EventDto[] {
const searchMatch = queryDtoCustom(search, events, toRepresentation);
export function eventQuery(events: EventDto[], search: string, venue?: VenueDto | null): EventDto[] {
let searchMatch = queryDtoCustom(search, events, toRepresentation);
// Filter by venue
if (venue !== undefined) {
return searchMatch.filter((event) => {
return event.location.toLowerCase().includes(venue.name);
});
if (venue) {
searchMatch = searchMatch.filter((event) => event.location.toLowerCase().includes(venue.name.toLowerCase()));
}
return searchMatch;
}
12 changes: 6 additions & 6 deletions frontend/src/Components/MultiSelect/MultiSelect.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useMemo, useState } from 'react';
import { InputField } from '~/Components/InputField';
import { Button } from '../Button';
import type { DropDownOption } from '../Dropdown/Dropdown';
import type { DropdownOption } from '../Dropdown/Dropdown';
import styles from './MultiSelect.module.scss';
import { exists, searchFilter } from './utils';

Expand All @@ -11,8 +11,8 @@ type MultiSelectProps<T> = {
selectedLabel?: string;
selectAllBtnTxt?: string;
unselectAllBtnTxt?: string;
selected?: DropDownOption<T>[];
options?: DropDownOption<T>[];
selected?: DropdownOption<T>[];
options?: DropdownOption<T>[];
onChange?: (values: T[]) => void;
className?: string;
};
Expand All @@ -34,7 +34,7 @@ export function MultiSelect<T>({
}: MultiSelectProps<T>) {
const [searchUnselected, setSearchUnselected] = useState('');
const [searchSelected, setSearchSelected] = useState('');
const [selected, setSelected] = useState<DropDownOption<T>[]>(initialValues);
const [selected, setSelected] = useState<DropdownOption<T>[]>(initialValues);

const filteredOptions = useMemo(
() => options.filter((item) => searchFilter(item, searchUnselected)).filter((item) => !exists(item, selected)),
Expand All @@ -46,13 +46,13 @@ export function MultiSelect<T>({
[searchSelected, selected],
);

function selectItem(item: DropDownOption<T>) {
function selectItem(item: DropdownOption<T>) {
const updatedSelected = [...selected, item];
setSelected(updatedSelected);
onChange?.(updatedSelected.map((_item) => _item.value));
}

function unselectItem(item: DropDownOption<T>) {
function unselectItem(item: DropdownOption<T>) {
const updatedSelected = selected.filter((_item) => _item !== item);
setSelected(updatedSelected);
onChange?.(updatedSelected.map((_item) => _item.value));
Expand Down
Loading
Loading