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

#695 Article Category selection handling in "Aktuality" page #715

Merged
merged 3 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
8 changes: 6 additions & 2 deletions next/public/locales/sk/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"aria.close": "Zavrieť",
"articlePage.shareblock.buttonText": "Zdieľať článok",
"articlePage.shareblock.text": "Páčil sa vám článok?",
"articlesSection.selectionOptions.allArticles": "Všetky články",
"articlesSection.selectionOptions.aria": "Kategórie článkov",
"branchPageContent.directionsTitle": "Adresa a doprava",
"breadcrumbs.back": "Späť",
"breadcrumbs.homepage": "Domov",
Expand Down Expand Up @@ -46,13 +48,11 @@
"documentPageContent.documentCategory": "Kategória",
"documentPageContent.downloadButtonLabel": "Stiahnuť súbor",
"documentPageContent.fileGroupTitle": "Súbory",
"documentPageContent.identificationNumber": "Identifikačné číslo",
"documentPageContent.numberOfFiles_one": "{{count}} súbor",
"documentPageContent.numberOfFiles_two": "{{count}} súbory",
"documentPageContent.numberOfFiles_few": "{{count}} súbory",
"documentPageContent.numberOfFiles_many": "{{count}} súbory",
"documentPageContent.numberOfFiles_other": "{{count}} súborov",
"documentPageContent.priceWithoutTax": "Cena bez DPH",
"documentPageContent.publishedAt": "Dátum pridania",
"documentsAllSection.filters.chooseCategory": "Vyberte kategóriu",
"documentsAllSection.metadata.publishDate": "Pridané {{date}}",
Expand Down Expand Up @@ -90,6 +90,10 @@
"globalSearch.searchResultsFound.all_many": "Našli sme {{count}} výsledky",
"globalSearch.searchResultsFound.all_other": "Našli sme {{count}} výsledkov",
"globalSearch.searchResultsFound.specific": "Zobrazujeme {{from}}–{{to}} z {{all}} výsledkov",
"globalSearch.searchResultsFound.specific.singlepage_one": "",
"globalSearch.searchResultsFound.specific.singlepage_few": "",
"globalSearch.searchResultsFound.specific.singlepage_many": "",
"globalSearch.searchResultsFound.specific.singlepage_other": "",
Comment on lines +93 to +96
Copy link
Contributor

Choose a reason for hiding this comment

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

This seems to be used somewhere

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

✅ not anymore

"globalSearch.showAll": "Zobraziť všetky",
"imageLightBox.aria.imageLightBoxDescription": "Galéria obrázkov. Stlačte šípku vľavo pre zobrazenie predchádzajúceho obrázku. Stlačte šípku vpravo pre zobrazenie nasledujúceho obrázku. Zatvorte stlačením klávesu Escape.",
"imageLightBox.aria.nextImage": "Ďalší obrázok",
Expand Down
1 change: 1 addition & 0 deletions next/src/components/sections/ServicesSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const ServicesSection = ({ section }: Props) => {

const { title, text } = section

// TODO consider replacing with meilisearch
const { data: servicesData } = useQuery({
queryKey: ['Services', locale],
queryFn: () => client.Services({ locale }),
Expand Down
105 changes: 94 additions & 11 deletions next/src/components/sections/articles/ArticlesSectionAll.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { useTranslation } from 'next-i18next'
import React, { useEffect, useRef, useState } from 'react'
import { Selection, TagGroup, TagList } from 'react-aria-components'
import { StringParam, useQueryParam, withDefault } from 'use-query-params'
import { useDebounceValue } from 'usehooks-ts'

import ArticleCard from '@/src/components/common/Card/ArticleCard'
import Chip from '@/src/components/common/Chip/Chip'
import PaginationWithInput from '@/src/components/common/Pagination/PaginationWithInput'
import SearchBar from '@/src/components/common/SearchBar/SearchBar'
import Divider from '@/src/components/common/Sidebar/Divider'
import Typography from '@/src/components/common/Typography/Typography'
import SectionHeader from '@/src/components/layout/Section/SectionHeader'
import { client } from '@/src/services/graphql'
import { ArticlesSectionFragment } from '@/src/services/graphql/api'
import {
articlesDefaultFilters,
Expand All @@ -35,6 +39,8 @@ const ArticlesSectionAll = ({ section }: Props) => {

const { title, text } = section

// SEARCH INPUT

const [input, setInput] = useState('')
const [debouncedInput] = useDebounceValue(input, 300)

Expand All @@ -46,13 +52,66 @@ const ArticlesSectionAll = ({ section }: Props) => {
searchRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [filters.page, filters.pageSize])

// CATEGORY SELECTION

const { data: articleCategoriesData } = useQuery({
queryKey: ['ArticleCategories', locale],
queryFn: () => client.ArticleCategories({ locale }),
})

type SelectionOption = { id: string; title: string }

const selectionOptions: SelectionOption[] = [
{ id: 'all', title: t('articlesSection.selectionOptions.allArticles') },
...(articleCategoriesData?.articleCategories?.data
.map((category) => {
if (!category.attributes || !category.id) return null

return { id: category.attributes.slug, title: category.attributes.title }
})
// eslint-disable-next-line unicorn/no-array-callback-reference
.filter(isDefined) ?? []),
]

const [selection, setSelection] = useState<Selection>(new Set([selectionOptions[0].id]))

const handleSelectionChange = (newSelection: Selection) => {
// If the new selection is empty, select the first option that displays all
if (new Set(newSelection).size === 0) setSelection(new Set([selectionOptions[0].id]))
else setSelection(newSelection)
}

const selectedKey: SelectionOption['id'] =
selection !== 'all' && selection.size === 1
? selection.values().next().value
: selectionOptions[0].id

// URL QUERY PARAMS

const [routerQueryCategoryValue] = useQueryParam(
'articleCategory',
withDefault(StringParam, 'all'),
)
const [routerQuerySearchValue] = useQueryParam('search', withDefault(StringParam, ''))

useEffect(() => {
setSelection(new Set([routerQueryCategoryValue]))
}, [routerQueryCategoryValue])

useEffect(() => {
setInput(routerQuerySearchValue)
}, [routerQuerySearchValue])

// FETCHING

useEffect(() => {
setFilters((previousState) => ({
...previousState,
search: debouncedInput,
page: 1,
categorySlugs: selectedKey === 'all' ? undefined : [selectedKey],
}))
}, [debouncedInput, setFilters])
}, [debouncedInput, selectedKey, setFilters])

const { data, isPending, isError, error, isFetching } = useQuery({
queryFn: () => meiliArticlesFetcher(filters, locale),
Expand All @@ -62,18 +121,42 @@ const ArticlesSectionAll = ({ section }: Props) => {

return (
<div className="flex flex-col gap-6 lg:gap-12">
{/* <div ref={searchRef} aria-hidden /> */}
<div className="flex flex-col gap-6 lg:gap-8">
<SectionHeader title={title} text={text} />
<SearchBar
ref={searchRef}
input={input}
setInput={setInput}
setSearchQuery={(value) =>
setFilters((previousState) => ({ ...previousState, search: value, page: 1 }))
}
isLoading={isFetching}
/>
<div className="flex flex-col gap-4 lg:gap-4">
<SearchBar
ref={searchRef}
input={input}
setInput={setInput}
setSearchQuery={(value) =>
setFilters((previousState) => ({ ...previousState, search: value, page: 1 }))
}
isLoading={isFetching}
/>
<TagGroup
aria-label={t('articlesSection.selectionOptions.aria')}
selectionMode="single"
selectedKeys={selection}
onSelectionChange={handleSelectionChange}
>
<TagList className="max-md:negative-x-spacing -m-1.5 flex gap-x-2 overflow-auto p-1.5 scrollbar-hide max-md:flex-nowrap lg:gap-x-4">
{selectionOptions.map((option, index) => {
return (
<Chip
variant="single-choice"
size="large"
// eslint-disable-next-line react/no-array-index-key
key={index}
id={option.id}
data-cy={`${option.title}-tab`}
>
{option.title}
</Chip>
)
})}
</TagList>
</TagGroup>
</div>
{isError ? (
// TODO display proper error
<Typography variant="p-default">{error?.message}</Typography>
Expand Down
Loading