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

[feat] Create Custom Multi-Select Dropdown and Style Seasonal Planting Guide #62

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
28 changes: 20 additions & 8 deletions app/seasonal-planting-guide/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import FilterDropdownMultiple from '@/components/FilterDropdownMultiple';
import FilterDropdownSingle from '@/components/FilterDropdownSingle';
import { PlantCalendarList } from '@/components/PlantCalendarList';
import SearchBar from '@/components/SearchBar';
import SeasonColorKey from '@/components/SeasonColorKey';
import COLORS from '@/styles/colors';
import { Box } from '@/styles/containers';
import { Box, Flex } from '@/styles/containers';
import { H1, H3 } from '@/styles/text';
import { DropdownOption, PlantingTypeEnum, SeasonEnum } from '@/types/schema';
import { useProfile } from '@/utils/ProfileProvider';
Expand All @@ -16,6 +17,7 @@ import {
PageContainer,
PageTitle,
StateOptionsContainer,
VerticalSeparator,
} from './styles';

// Declaring (static) filter options outside so they're not re-rendered
Expand All @@ -36,7 +38,7 @@ const plantingTypeOptions: DropdownOption<PlantingTypeEnum>[] = [
{ label: 'Start Seeds Indoors', value: 'INDOORS' },
{ label: 'Start Seeds Outdoors', value: 'OUTDOORS' },
{
label: 'Plant Seedlings/Transplant Outdoors',
label: 'Plant Seedlings / Transplant Outdoors',
value: 'TRANSPLANT',
},
];
Expand All @@ -56,7 +58,8 @@ export default function SeasonalPlantingGuide() {
const [selectedPlantingType, setSelectedPlantingType] = useState<
DropdownOption<PlantingTypeEnum>[]
>([]);
const [selectedUsState, setSelectedUsState] = useState<string>('');
const [selectedUsState, setSelectedUsState] =
useState<DropdownOption<string> | null>(null);
const [searchTerm, setSearchTerm] = useState<string>('');

const clearFilters = () => {
Expand All @@ -67,7 +70,12 @@ export default function SeasonalPlantingGuide() {

useEffect(() => {
if (profileReady && profileData) {
setSelectedUsState(profileData.us_state);
setSelectedUsState({
label:
profileData.us_state.charAt(0) +
profileData.us_state.slice(1).toLowerCase(), // can't use useTitleCase here, lint error
value: profileData.us_state,
});
}
}, [profileData, profileReady]);

Expand All @@ -82,14 +90,17 @@ export default function SeasonalPlantingGuide() {
<SearchBar searchTerm={searchTerm} setSearchTerm={setSearchTerm} />
<FilterContainer>
<FilterDropdownSingle
id="usState"
value={selectedUsState}
setStateAction={setSelectedUsState}
placeholder="State"
options={usStateOptions}
disabled={!selectedUsState}
small={true}
/>

{/* vertical bar to separate state and other filters */}
<VerticalSeparator />

<FilterDropdownMultiple
value={selectedGrowingSeason}
setStateAction={setSelectedGrowingSeason}
Expand Down Expand Up @@ -121,16 +132,17 @@ export default function SeasonalPlantingGuide() {
<StateOptionsContainer>
<H3 $color={COLORS.shrub}>Choose Your State</H3>
<FilterDropdownSingle
name="usState"
id="usState"
value={selectedUsState}
setStateAction={setSelectedUsState}
placeholder="State"
options={usStateOptions}
/>
</StateOptionsContainer>
) : (
<Box $pl="16px" $pt="12px">
<Box $p="20px">
<Flex $direction="row" $justify="center">
<SeasonColorKey />
</Flex>
<PlantCalendarList
growingSeasonFilterValue={selectedGrowingSeason}
harvestSeasonFilterValue={selectedHarvestSeason}
Expand Down
16 changes: 14 additions & 2 deletions app/seasonal-planting-guide/styles.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import styled from 'styled-components';
import COLORS from '@/styles/colors';

export const PageContainer = styled.div`
display: flex;
Expand All @@ -20,17 +21,22 @@ export const HeaderContainer = styled.div`
export const FilterContainer = styled.div`
display: flex;
flex-direction: row;
gap: 0.5rem;
gap: 8px;
margin-top: 12px;
position: relative;
overflow-x: auto;
padding-top: 1px;
padding-bottom: 1px;
`;

export const StateOptionsContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1rem;
gap: 16px;
flex-grow: 1;
background-color: ${COLORS.glimpse};
`;

export const PageTitle = styled.div`
Expand All @@ -40,3 +46,9 @@ export const PageTitle = styled.div`
gap: 12px;
align-items: center;
`;

export const VerticalSeparator = styled.div`
height: inherit;
width: 1px;
background-color: ${COLORS.lightgray};
`;
54 changes: 50 additions & 4 deletions app/view-plants/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
'use client';

import { useEffect, useMemo, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
getAllPlants,
getMatchingPlantForUserPlant,
} from '@/api/supabase/queries/plants';
import { getCurrentUserPlantsByUserId } from '@/api/supabase/queries/userPlants';
import FilterDropdownMultiple from '@/components/FilterDropdownMultiple';
import Icon from '@/components/Icon';
import PlantCard from '@/components/PlantCard';
import PlantCardKey from '@/components/PlantCardKey';
import SearchBar from '@/components/SearchBar';
import COLORS from '@/styles/colors';
import { Box, Flex } from '@/styles/containers';
Expand All @@ -32,6 +34,7 @@ import {
AddButton,
FilterContainer,
HeaderButton,
InfoButton,
NumberSelectedPlants,
NumberSelectedPlantsContainer,
PlantGridContainer,
Expand Down Expand Up @@ -82,6 +85,9 @@ export default function Page() {
const [searchTerm, setSearchTerm] = useState<string>('');
const [selectedPlants, setSelectedPlants] = useState<Plant[]>([]);
const [ownedPlants, setOwnedPlants] = useState<OwnedPlant[]>([]);
const [isCardKeyOpen, setIsCardKeyOpen] = useState<boolean>(false);
const cardKeyRef = useRef<HTMLDivElement>(null);
const infoButtonRef = useRef<HTMLButtonElement>(null);
const userState = profileData?.us_state ?? null;

const profileAndAuthReady = profileReady && !authLoading;
Expand Down Expand Up @@ -319,12 +325,52 @@ export default function Page() {

const plantPluralityString = selectedPlants.length > 1 ? 'Plants' : 'Plant';

// close plant card key when clicking outside, even on info button
const handleClickOutside = (event: MouseEvent) => {
if (
cardKeyRef.current &&
!cardKeyRef.current.contains(event.target as Node) &&
infoButtonRef.current &&
!infoButtonRef.current.contains(event.target as Node)
) {
setIsCardKeyOpen(false);
}
};

// handle clicking outside PlantCardKey to close it if open
useEffect(() => {
if (isCardKeyOpen) {
document.addEventListener('mousedown', handleClickOutside);
} else {
document.removeEventListener('mousedown', handleClickOutside);
}

return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [isCardKeyOpen]);

return (
<div id="plantContent">
<TopRowContainer>
<H1 $color={COLORS.shrub} $fontWeight={500}>
View Plants
</H1>
<Flex $direction="row" $gap="10px" $align="center">
<H1 $color={COLORS.shrub} $fontWeight={500}>
View Plants
</H1>
<div style={{ position: 'relative' }}>
<InfoButton
onClick={() => setIsCardKeyOpen(!isCardKeyOpen)}
ref={infoButtonRef}
>
<Icon type="info" />
</InfoButton>
{isCardKeyOpen && (
<div ref={cardKeyRef}>
<PlantCardKey />
</div>
)}
</div>
</Flex>
<SearchBar searchTerm={searchTerm} setSearchTerm={setSearchTerm} />
<FilterContainer>
<FilterDropdownMultiple
Expand Down
10 changes: 10 additions & 0 deletions app/view-plants/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const FilterContainer = styled.div`
flex-direction: row;
gap: 8px;
margin-bottom: 20px;
overflow-x: auto;
`;

export const TopRowContainer = styled.div`
Expand Down Expand Up @@ -96,3 +97,12 @@ export const NumberSelectedPlants = styled.p`
line-height: 16px;
color: #fff;
`;

export const InfoButton = styled.button`
display: flex;
align-items: center;
justify-content: center;
background: none;
border: none;
cursor: pointer;
`;
92 changes: 84 additions & 8 deletions components/FilterDropdownMultiple/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import React from 'react';
import Select, {
components,
GroupBase,
MultiValue,
MultiValueProps,
OptionProps,
} from 'react-select';
import { P3 } from '@/styles/text';
import { DropdownOption } from '@/types/schema';
import { StyledMultiSelect } from './styles';
import { customSelectStyles, StyledOption } from './styles';

interface FilterDropdownProps<T> {
value: DropdownOption<T>[];
Expand All @@ -17,16 +25,84 @@ export default function FilterDropdownMultiple<T>({
placeholder,
disabled = false,
}: FilterDropdownProps<T>) {
const handleChange = (selectedOptions: MultiValue<DropdownOption<T>>) => {
setStateAction(selectedOptions as DropdownOption<T>[]);
};

// overrides the default MultiValue to display custom text
// displays first selected value followed by + n if more than 1 selected
// StyledMultiValue appears for each selected option, so if more than 1 is selected,
// the rest of the selected options are not shown, instead the + n is shown as part of the first option
const StyledMultiValue = ({
...props
}: MultiValueProps<
DropdownOption<T>,
true,
GroupBase<DropdownOption<T>>
>) => {
const { selectProps, data } = props;
if (Array.isArray(selectProps.value)) {
// find index of the selected option and check if its the first
const index = selectProps.value.findIndex(
(option: DropdownOption<T>) => option.value === data.value,
);
const isFirst = index === 0;
// find number of remaining selected options
const additionalCount = selectProps.value.length - 1;

return (
<P3>
{/* display label of first selected option */}
{isFirst ? (
<>
{data.label}
{/* display additional count only if more than one option is selected*/}
{additionalCount > 0 && ` +${additionalCount}`}
</>
) : // don't display anything if not the first selected option
null}
</P3>
);
}

// nothing is selected yet
return null;
};

// overrides the default Options to display a checkbox that ticks when option selected
const CustomOption = (
props: OptionProps<DropdownOption<T>, true, GroupBase<DropdownOption<T>>>,
) => {
return (
<components.Option {...props}>
<StyledOption>
<input
type="checkbox"
checked={props.isSelected}
onChange={() => null} //no-op
style={{ marginRight: 8 }} // spacing between checkbox and text
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm getting a console error:
"You provided a checked prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultChecked. Otherwise, set either onChange or readOnly."

perhaps we need to pass an onChange here?

here's more from the console error
Screen Shot 2024-12-13 at 2 19 48 AM

/>
{props.label}
</StyledOption>
</components.Option>
);
};

return (
<StyledMultiSelect
<Select
options={options}
isMulti
value={value}
onChange={setStateAction}
labelledBy={placeholder}
hasSelectAll={false}
overrideStrings={{ selectSomeItems: placeholder }}
disableSearch
disabled={disabled}
isDisabled={disabled}
placeholder={placeholder}
onChange={handleChange}
closeMenuOnSelect={false}
styles={customSelectStyles<T>()}
isSearchable={false}
hideSelectedOptions={false}
// use custom styled components instead of default components
components={{ MultiValue: StyledMultiValue, Option: CustomOption }}
menuPosition="fixed"
/>
);
}
Loading
Loading