From 88b575b0d81e97531b70e90c1e124719b547614b Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Thu, 14 Apr 2022 22:14:35 +0200
Subject: chore: add a Search component

---
 src/components/organisms/toolbar/search.test.tsx | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
 create mode 100644 src/components/organisms/toolbar/search.test.tsx

(limited to 'src/components/organisms/toolbar/search.test.tsx')

diff --git a/src/components/organisms/toolbar/search.test.tsx b/src/components/organisms/toolbar/search.test.tsx
new file mode 100644
index 0000000..0ce09d8
--- /dev/null
+++ b/src/components/organisms/toolbar/search.test.tsx
@@ -0,0 +1,19 @@
+import { render, screen } from '@test-utils';
+import Search from './search';
+
+describe('Search', () => {
+  it('renders a button to open search modal', () => {
+    render(<Search isActive={false} setIsActive={() => null} />);
+    expect(screen.getByRole('checkbox')).toHaveAccessibleName('Open search');
+  });
+
+  it('renders a button to close search modal', () => {
+    render(<Search isActive={true} setIsActive={() => null} />);
+    expect(screen.getByRole('checkbox')).toHaveAccessibleName('Close search');
+  });
+
+  it('renders a search form', () => {
+    render(<Search isActive={true} setIsActive={() => null} />);
+    expect(screen.getByRole('searchbox')).toBeInTheDocument();
+  });
+});
-- 
cgit v1.2.3


From 235fe67d770f83131c9ec10b99012319440db690 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Sun, 15 May 2022 16:36:58 +0200
Subject: chore: add Search page

---
 .../organisms/forms/search-form.stories.tsx        |   9 +-
 .../organisms/forms/search-form.test.tsx           |   4 +-
 src/components/organisms/forms/search-form.tsx     |  14 +-
 src/components/organisms/layout/header.stories.tsx |   9 +-
 src/components/organisms/layout/header.test.tsx    |  12 +-
 src/components/organisms/layout/header.tsx         |  21 +-
 .../organisms/modals/search-modal.stories.tsx      |  11 +-
 .../organisms/modals/search-modal.test.tsx         |   2 +-
 src/components/organisms/modals/search-modal.tsx   |   8 +-
 .../organisms/toolbar/search.stories.tsx           |  10 +-
 src/components/organisms/toolbar/search.test.tsx   |   6 +-
 src/components/organisms/toolbar/search.tsx        |  12 +-
 .../organisms/toolbar/toolbar.stories.tsx          |  11 +-
 src/components/organisms/toolbar/toolbar.test.tsx  |   2 +-
 src/components/organisms/toolbar/toolbar.tsx       |   7 +-
 src/components/templates/layout/layout.tsx         |   3 +-
 src/pages/blog/index.tsx                           |   4 +-
 src/pages/recherche/index.tsx                      | 324 +++++++++++++++++++++
 src/services/graphql/api.ts                        |  15 +-
 src/services/graphql/articles.query.ts             |   4 +-
 src/services/graphql/articles.ts                   |   3 +-
 src/services/graphql/contact.ts                    |   4 +-
 src/utils/hooks/use-data-from-api.tsx              |  23 ++
 src/utils/hooks/use-pagination.tsx                 |   3 +-
 24 files changed, 436 insertions(+), 85 deletions(-)
 create mode 100644 src/pages/recherche/index.tsx
 create mode 100644 src/utils/hooks/use-data-from-api.tsx

(limited to 'src/components/organisms/toolbar/search.test.tsx')

diff --git a/src/components/organisms/forms/search-form.stories.tsx b/src/components/organisms/forms/search-form.stories.tsx
index 7f4c7c0..6ea6122 100644
--- a/src/components/organisms/forms/search-form.stories.tsx
+++ b/src/components/organisms/forms/search-form.stories.tsx
@@ -1,5 +1,4 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
-import { IntlProvider } from 'react-intl';
 import SearchForm from './search-form';
 
 /**
@@ -10,6 +9,7 @@ export default {
   component: SearchForm,
   args: {
     hideLabel: false,
+    searchPage: '#',
   },
   argTypes: {
     className: {
@@ -40,13 +40,6 @@ export default {
       },
     },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
 } as ComponentMeta<typeof SearchForm>;
 
 const Template: ComponentStory<typeof SearchForm> = (args) => (
diff --git a/src/components/organisms/forms/search-form.test.tsx b/src/components/organisms/forms/search-form.test.tsx
index 4e3d285..59a2f68 100644
--- a/src/components/organisms/forms/search-form.test.tsx
+++ b/src/components/organisms/forms/search-form.test.tsx
@@ -3,14 +3,14 @@ import SearchForm from './search-form';
 
 describe('SearchForm', () => {
   it('renders a search input', () => {
-    render(<SearchForm />);
+    render(<SearchForm searchPage="#" />);
     expect(
       screen.getByRole('searchbox', { name: 'Search for:' })
     ).toBeInTheDocument();
   });
 
   it('renders a submit button', () => {
-    render(<SearchForm />);
+    render(<SearchForm searchPage="#" />);
     expect(screen.getByRole('button', { name: 'Search' })).toBeInTheDocument();
   });
 });
diff --git a/src/components/organisms/forms/search-form.tsx b/src/components/organisms/forms/search-form.tsx
index 18b7c08..56d3895 100644
--- a/src/components/organisms/forms/search-form.tsx
+++ b/src/components/organisms/forms/search-form.tsx
@@ -4,18 +4,24 @@ import MagnifyingGlass from '@components/atoms/icons/magnifying-glass';
 import LabelledField, {
   type LabelledFieldProps,
 } from '@components/molecules/forms/labelled-field';
+import { useRouter } from 'next/router';
 import { FC, useState } from 'react';
 import { useIntl } from 'react-intl';
 import styles from './search-form.module.scss';
 
-export type SearchFormProps = Pick<LabelledFieldProps, 'hideLabel'>;
+export type SearchFormProps = Pick<LabelledFieldProps, 'hideLabel'> & {
+  /**
+   * The search page url.
+   */
+  searchPage: string;
+};
 
 /**
  * SearchForm component
  *
  * Render a search form.
  */
-const SearchForm: FC<SearchFormProps> = ({ hideLabel }) => {
+const SearchForm: FC<SearchFormProps> = ({ hideLabel, searchPage }) => {
   const intl = useIntl();
   const fieldLabel = intl.formatMessage({
     defaultMessage: 'Search for:',
@@ -28,10 +34,12 @@ const SearchForm: FC<SearchFormProps> = ({ hideLabel }) => {
     id: 'WMqQrv',
   });
 
+  const router = useRouter();
   const [value, setValue] = useState<string>('');
 
   const submitHandler = () => {
-    return;
+    router.push({ pathname: searchPage, query: { s: value } });
+    setValue('');
   };
 
   return (
diff --git a/src/components/organisms/layout/header.stories.tsx b/src/components/organisms/layout/header.stories.tsx
index c58c344..98d6377 100644
--- a/src/components/organisms/layout/header.stories.tsx
+++ b/src/components/organisms/layout/header.stories.tsx
@@ -1,5 +1,4 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
-import { IntlProvider } from 'react-intl';
 import HeaderComponent from './header';
 
 /**
@@ -10,6 +9,7 @@ export default {
   component: HeaderComponent,
   args: {
     isHome: false,
+    searchPage: '#',
     withLink: false,
   },
   argTypes: {
@@ -95,13 +95,6 @@ export default {
       },
     },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
   parameters: {
     layout: 'fullscreen',
   },
diff --git a/src/components/organisms/layout/header.test.tsx b/src/components/organisms/layout/header.test.tsx
index 05baaec..a9896f8 100644
--- a/src/components/organisms/layout/header.test.tsx
+++ b/src/components/organisms/layout/header.test.tsx
@@ -14,14 +14,22 @@ const title = 'Assumenda quis quod';
 
 describe('Header', () => {
   it('renders the website title', () => {
-    render(<Header title={title} photo={photo} nav={nav} isHome={true} />);
+    render(
+      <Header
+        searchPage="#"
+        title={title}
+        photo={photo}
+        nav={nav}
+        isHome={true}
+      />
+    );
     expect(
       screen.getByRole('heading', { level: 1, name: title })
     ).toBeInTheDocument();
   });
 
   it('renders the main nav', () => {
-    render(<Header title={title} photo={photo} nav={nav} />);
+    render(<Header searchPage="#" title={title} photo={photo} nav={nav} />);
     expect(screen.getByRole('navigation')).toBeInTheDocument();
   });
 });
diff --git a/src/components/organisms/layout/header.tsx b/src/components/organisms/layout/header.tsx
index f6ebc9c..18ebb31 100644
--- a/src/components/organisms/layout/header.tsx
+++ b/src/components/organisms/layout/header.tsx
@@ -5,28 +5,25 @@ import { FC } from 'react';
 import Toolbar, { type ToolbarProps } from '../toolbar/toolbar';
 import styles from './header.module.scss';
 
-export type HeaderProps = BrandingProps & {
-  /**
-   * Set additional classnames to the header element.
-   */
-  className?: string;
-  /**
-   * The main nav items.
-   */
-  nav: ToolbarProps['nav'];
-};
+export type HeaderProps = BrandingProps &
+  Pick<ToolbarProps, 'nav' | 'searchPage'> & {
+    /**
+     * Set additional classnames to the header element.
+     */
+    className?: string;
+  };
 
 /**
  * Header component
  *
  * Render the website header.
  */
-const Header: FC<HeaderProps> = ({ className, nav, ...props }) => {
+const Header: FC<HeaderProps> = ({ className, nav, searchPage, ...props }) => {
   return (
     <header className={`${styles.wrapper} ${className}`}>
       <div className={styles.body}>
         <Branding {...props} />
-        <Toolbar nav={nav} className={styles.toolbar} />
+        <Toolbar nav={nav} searchPage={searchPage} className={styles.toolbar} />
       </div>
     </header>
   );
diff --git a/src/components/organisms/modals/search-modal.stories.tsx b/src/components/organisms/modals/search-modal.stories.tsx
index 3ad6abd..f40696c 100644
--- a/src/components/organisms/modals/search-modal.stories.tsx
+++ b/src/components/organisms/modals/search-modal.stories.tsx
@@ -1,5 +1,4 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
-import { IntlProvider } from 'react-intl';
 import SearchModal from './search-modal';
 
 /**
@@ -8,6 +7,9 @@ import SearchModal from './search-modal';
 export default {
   title: 'Organisms/Modals',
   component: SearchModal,
+  args: {
+    searchPage: '#',
+  },
   argTypes: {
     className: {
       control: {
@@ -23,13 +25,6 @@ export default {
       },
     },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
 } as ComponentMeta<typeof SearchModal>;
 
 const Template: ComponentStory<typeof SearchModal> = (args) => (
diff --git a/src/components/organisms/modals/search-modal.test.tsx b/src/components/organisms/modals/search-modal.test.tsx
index 249c523..7ba08c0 100644
--- a/src/components/organisms/modals/search-modal.test.tsx
+++ b/src/components/organisms/modals/search-modal.test.tsx
@@ -3,7 +3,7 @@ import SearchModal from './search-modal';
 
 describe('SearchModal', () => {
   it('renders a search modal', () => {
-    render(<SearchModal />);
+    render(<SearchModal searchPage="#" />);
     expect(screen.getByText('Search')).toBeInTheDocument();
   });
 });
diff --git a/src/components/organisms/modals/search-modal.tsx b/src/components/organisms/modals/search-modal.tsx
index 0e0ceed..866bc25 100644
--- a/src/components/organisms/modals/search-modal.tsx
+++ b/src/components/organisms/modals/search-modal.tsx
@@ -1,10 +1,10 @@
 import Modal, { type ModalProps } from '@components/molecules/modals/modal';
 import { FC } from 'react';
 import { useIntl } from 'react-intl';
-import SearchForm from '../forms/search-form';
+import SearchForm, { SearchFormProps } from '../forms/search-form';
 import styles from './search-modal.module.scss';
 
-export type SearchModalProps = {
+export type SearchModalProps = Pick<SearchFormProps, 'searchPage'> & {
   /**
    * Set additional classnames to modal wrapper.
    */
@@ -16,7 +16,7 @@ export type SearchModalProps = {
  *
  * Render a search form modal.
  */
-const SearchModal: FC<SearchModalProps> = ({ className }) => {
+const SearchModal: FC<SearchModalProps> = ({ className, searchPage }) => {
   const intl = useIntl();
   const modalTitle = intl.formatMessage({
     defaultMessage: 'Search',
@@ -26,7 +26,7 @@ const SearchModal: FC<SearchModalProps> = ({ className }) => {
 
   return (
     <Modal title={modalTitle} className={`${styles.wrapper} ${className}`}>
-      <SearchForm hideLabel={true} />
+      <SearchForm hideLabel={true} searchPage={searchPage} />
     </Modal>
   );
 };
diff --git a/src/components/organisms/toolbar/search.stories.tsx b/src/components/organisms/toolbar/search.stories.tsx
index 0421c8c..c6063a0 100644
--- a/src/components/organisms/toolbar/search.stories.tsx
+++ b/src/components/organisms/toolbar/search.stories.tsx
@@ -9,6 +9,9 @@ import Search from './search';
 export default {
   title: 'Organisms/Toolbar/Search',
   component: Search,
+  args: {
+    searchPage: '#',
+  },
   argTypes: {
     className: {
       control: {
@@ -44,13 +47,6 @@ export default {
       },
     },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
 } as ComponentMeta<typeof Search>;
 
 const Template: ComponentStory<typeof Search> = ({
diff --git a/src/components/organisms/toolbar/search.test.tsx b/src/components/organisms/toolbar/search.test.tsx
index 0ce09d8..a18b679 100644
--- a/src/components/organisms/toolbar/search.test.tsx
+++ b/src/components/organisms/toolbar/search.test.tsx
@@ -3,17 +3,17 @@ import Search from './search';
 
 describe('Search', () => {
   it('renders a button to open search modal', () => {
-    render(<Search isActive={false} setIsActive={() => null} />);
+    render(<Search searchPage="#" isActive={false} setIsActive={() => null} />);
     expect(screen.getByRole('checkbox')).toHaveAccessibleName('Open search');
   });
 
   it('renders a button to close search modal', () => {
-    render(<Search isActive={true} setIsActive={() => null} />);
+    render(<Search searchPage="#" isActive={true} setIsActive={() => null} />);
     expect(screen.getByRole('checkbox')).toHaveAccessibleName('Close search');
   });
 
   it('renders a search form', () => {
-    render(<Search isActive={true} setIsActive={() => null} />);
+    render(<Search searchPage="#" isActive={true} setIsActive={() => null} />);
     expect(screen.getByRole('searchbox')).toBeInTheDocument();
   });
 });
diff --git a/src/components/organisms/toolbar/search.tsx b/src/components/organisms/toolbar/search.tsx
index 72cd576..a1471ef 100644
--- a/src/components/organisms/toolbar/search.tsx
+++ b/src/components/organisms/toolbar/search.tsx
@@ -16,13 +16,22 @@ export type SearchProps = {
    * The button state.
    */
   isActive: CheckboxProps['value'];
+  /**
+   * A callback function to execute search.
+   */
+  searchPage: SearchModalProps['searchPage'];
   /**
    * A callback function to handle button state.
    */
   setIsActive: CheckboxProps['setValue'];
 };
 
-const Search: FC<SearchProps> = ({ className = '', isActive, setIsActive }) => {
+const Search: FC<SearchProps> = ({
+  className = '',
+  isActive,
+  searchPage,
+  setIsActive,
+}) => {
   const intl = useIntl();
   const label = isActive
     ? intl.formatMessage({
@@ -53,6 +62,7 @@ const Search: FC<SearchProps> = ({ className = '', isActive, setIsActive }) => {
         <MagnifyingGlass />
       </Label>
       <SearchModal
+        searchPage={searchPage}
         className={`${sharedStyles.modal} ${searchStyles.modal} ${className}`}
       />
     </div>
diff --git a/src/components/organisms/toolbar/toolbar.stories.tsx b/src/components/organisms/toolbar/toolbar.stories.tsx
index 4f9a3de..477cb55 100644
--- a/src/components/organisms/toolbar/toolbar.stories.tsx
+++ b/src/components/organisms/toolbar/toolbar.stories.tsx
@@ -1,5 +1,4 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
-import { IntlProvider } from 'react-intl';
 import ToolbarComponent from './toolbar';
 
 /**
@@ -8,6 +7,9 @@ import ToolbarComponent from './toolbar';
 export default {
   title: 'Organisms/Toolbar',
   component: ToolbarComponent,
+  args: {
+    searchPage: '#',
+  },
   argTypes: {
     className: {
       control: {
@@ -31,13 +33,6 @@ export default {
       },
     },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
   parameters: {
     layout: 'fullscreen',
   },
diff --git a/src/components/organisms/toolbar/toolbar.test.tsx b/src/components/organisms/toolbar/toolbar.test.tsx
index 4bfe8a8..05e84ff 100644
--- a/src/components/organisms/toolbar/toolbar.test.tsx
+++ b/src/components/organisms/toolbar/toolbar.test.tsx
@@ -10,7 +10,7 @@ const nav = [
 
 describe('Toolbar', () => {
   it('renders a navigation menu', () => {
-    render(<Toolbar nav={nav} />);
+    render(<Toolbar nav={nav} searchPage="#" />);
     expect(screen.getByRole('navigation')).toBeInTheDocument();
   });
 });
diff --git a/src/components/organisms/toolbar/toolbar.tsx b/src/components/organisms/toolbar/toolbar.tsx
index f1ce530..6593055 100644
--- a/src/components/organisms/toolbar/toolbar.tsx
+++ b/src/components/organisms/toolbar/toolbar.tsx
@@ -1,10 +1,10 @@
 import { FC, useState } from 'react';
 import MainNav, { type MainNavProps } from '../toolbar/main-nav';
-import Search from '../toolbar/search';
+import Search, { type SearchProps } from '../toolbar/search';
 import Settings from '../toolbar/settings';
 import styles from './toolbar.module.scss';
 
-export type ToolbarProps = {
+export type ToolbarProps = Pick<SearchProps, 'searchPage'> & {
   /**
    * Set additional classnames to the toolbar wrapper.
    */
@@ -20,7 +20,7 @@ export type ToolbarProps = {
  *
  * Render the website toolbar.
  */
-const Toolbar: FC<ToolbarProps> = ({ className = '', nav }) => {
+const Toolbar: FC<ToolbarProps> = ({ className = '', nav, searchPage }) => {
   const [isNavOpened, setIsNavOpened] = useState<boolean>(false);
   const [isSettingsOpened, setIsSettingsOpened] = useState<boolean>(false);
   const [isSearchOpened, setIsSearchOpened] = useState<boolean>(false);
@@ -34,6 +34,7 @@ const Toolbar: FC<ToolbarProps> = ({ className = '', nav }) => {
         className={styles.modal}
       />
       <Search
+        searchPage={searchPage}
         isActive={isSearchOpened}
         setIsActive={setIsSearchOpened}
         className={`${styles.modal} ${styles['modal--search']}`}
diff --git a/src/components/templates/layout/layout.tsx b/src/components/templates/layout/layout.tsx
index e1be1af..bfb918b 100644
--- a/src/components/templates/layout/layout.tsx
+++ b/src/components/templates/layout/layout.tsx
@@ -171,9 +171,10 @@ const Layout: FC<LayoutProps> = ({ children, isHome, ...props }) => {
         baseline={baseline}
         photo={picture}
         nav={mainNav}
+        searchPage="/recherche"
         isHome={isHome}
-        className={styles.header}
         withLink={true}
+        className={styles.header}
       />
       <Main id="main" className={styles.main}>
         <article {...props}>{children}</article>
diff --git a/src/pages/blog/index.tsx b/src/pages/blog/index.tsx
index 3acf6a9..38fabd5 100644
--- a/src/pages/blog/index.tsx
+++ b/src/pages/blog/index.tsx
@@ -1,9 +1,7 @@
 import Notice from '@components/atoms/layout/notice';
 import { type BreadcrumbItem } from '@components/molecules/nav/breadcrumb';
 import PostsList, { type Post } from '@components/organisms/layout/posts-list';
-import LinksListWidget, {
-  LinksListItems,
-} from '@components/organisms/widgets/links-list-widget';
+import LinksListWidget from '@components/organisms/widgets/links-list-widget';
 import PageLayout from '@components/templates/page/page-layout';
 import { type EdgesResponse } from '@services/graphql/api';
 import {
diff --git a/src/pages/recherche/index.tsx b/src/pages/recherche/index.tsx
new file mode 100644
index 0000000..bf14861
--- /dev/null
+++ b/src/pages/recherche/index.tsx
@@ -0,0 +1,324 @@
+import Notice from '@components/atoms/layout/notice';
+import Spinner from '@components/atoms/loaders/spinner';
+import { type BreadcrumbItem } from '@components/molecules/nav/breadcrumb';
+import PostsList, { type Post } from '@components/organisms/layout/posts-list';
+import LinksListWidget from '@components/organisms/widgets/links-list-widget';
+import PageLayout from '@components/templates/page/page-layout';
+import { type EdgesResponse } from '@services/graphql/api';
+import {
+  getArticleFromRawData,
+  getArticles,
+  getTotalArticles,
+} from '@services/graphql/articles';
+import {
+  getThematicsPreview,
+  getTotalThematics,
+} from '@services/graphql/thematics';
+import { getTopicsPreview, getTotalTopics } from '@services/graphql/topics';
+import { type Article, type Meta } from '@ts/types/app';
+import {
+  RawThematicPreview,
+  RawTopicPreview,
+  type RawArticle,
+} from '@ts/types/raw-data';
+import { loadTranslation, type Messages } from '@utils/helpers/i18n';
+import {
+  getLinksListItems,
+  getPageLinkFromRawData,
+} from '@utils/helpers/pages';
+import useDataFromAPI from '@utils/hooks/use-data-from-api';
+import usePagination from '@utils/hooks/use-pagination';
+import useSettings from '@utils/hooks/use-settings';
+import { GetStaticProps, NextPage } from 'next';
+import Head from 'next/head';
+import { useRouter } from 'next/router';
+import Script from 'next/script';
+import { useIntl } from 'react-intl';
+import { Blog, Graph, WebPage } from 'schema-dts';
+
+type SearchPageProps = {
+  thematicsList: RawThematicPreview[];
+  topicsList: RawTopicPreview[];
+  translation: Messages;
+};
+
+/**
+ * Search page.
+ */
+const SearchPage: NextPage<SearchPageProps> = ({
+  thematicsList,
+  topicsList,
+}) => {
+  const intl = useIntl();
+  const { asPath, query } = useRouter();
+  const title = query.s
+    ? intl.formatMessage(
+        {
+          defaultMessage: 'Search results for {query}',
+          description: 'SearchPage: SEO - Page title',
+          id: 'ZNBhDP',
+        },
+        { query: query.s as string }
+      )
+    : intl.formatMessage({
+        defaultMessage: 'Search',
+        description: 'SearchPage: SEO - Page title',
+        id: 'WDwNDl',
+      });
+  const homeLabel = intl.formatMessage({
+    defaultMessage: 'Home',
+    description: 'Breadcrumb: home label',
+    id: 'j5k9Fe',
+  });
+  const blogLabel = intl.formatMessage({
+    defaultMessage: 'Blog',
+    description: 'Breadcrumb: blog label',
+    id: 'Es52wh',
+  });
+  const breadcrumb: BreadcrumbItem[] = [
+    { id: 'home', name: homeLabel, url: '/' },
+    { id: 'blog', name: blogLabel, url: '/blog' },
+    { id: 'search', name: title, url: '/recherche' },
+  ];
+
+  const { blog, website } = useSettings();
+  const pageTitle = `${title} - ${website.name}`;
+  const pageDescription = query.s
+    ? intl.formatMessage(
+        {
+          defaultMessage:
+            'Discover search results for {query} on {websiteName}.',
+          description: 'SearchPage: SEO - Meta description',
+          id: 'pg26sn',
+        },
+        { query: query.s as string, websiteName: website.name }
+      )
+    : intl.formatMessage(
+        {
+          defaultMessage: 'Search for a post on {websiteName}.',
+          description: 'SearchPage: SEO - Meta description',
+          id: 'npisb3',
+        },
+        { websiteName: website.name }
+      );
+  const pageUrl = `${website.url}${asPath}`;
+
+  const webpageSchema: WebPage = {
+    '@id': `${pageUrl}`,
+    '@type': 'WebPage',
+    breadcrumb: { '@id': `${website.url}/#breadcrumb` },
+    name: pageTitle,
+    description: pageDescription,
+    inLanguage: website.locales.default,
+    reviewedBy: { '@id': `${website.url}/#branding` },
+    url: `${website.url}`,
+    isPartOf: {
+      '@id': `${website.url}`,
+    },
+  };
+
+  const blogSchema: Blog = {
+    '@id': `${website.url}/#blog`,
+    '@type': 'Blog',
+    author: { '@id': `${website.url}/#branding` },
+    creator: { '@id': `${website.url}/#branding` },
+    editor: { '@id': `${website.url}/#branding` },
+    inLanguage: website.locales.default,
+    license: 'https://creativecommons.org/licenses/by-sa/4.0/deed.fr',
+    mainEntityOfPage: { '@id': `${pageUrl}` },
+  };
+
+  const schemaJsonLd: Graph = {
+    '@context': 'https://schema.org',
+    '@graph': [webpageSchema, blogSchema],
+  };
+
+  const {
+    data,
+    error,
+    isLoadingInitialData,
+    isLoadingMore,
+    hasNextPage,
+    setSize,
+  } = usePagination<RawArticle>({
+    fallbackData: [],
+    fetcher: getArticles,
+    perPage: blog.postsPerPage,
+    search: query.s as string,
+  });
+
+  const totalArticles = useDataFromAPI<number>(() =>
+    getTotalArticles(query.s as string)
+  );
+
+  const postsCount = intl.formatMessage(
+    {
+      defaultMessage:
+        '{postsCount, plural, =0 {No articles} one {# article} other {# articles}}',
+      id: 'LtsVOx',
+      description: 'SearchPage: posts count meta',
+    },
+    { postsCount: totalArticles || 0 }
+  );
+
+  /**
+   * Retrieve the formatted meta.
+   *
+   * @param {Meta<'article'>} meta - The article meta.
+   * @returns {Post['meta']} The formatted meta.
+   */
+  const getPostMeta = (meta: Meta<'article'>): Post['meta'] => {
+    const { commentsCount, dates, thematics, wordsCount } = meta;
+
+    return {
+      commentsCount,
+      dates,
+      readingTime: { wordsCount: wordsCount || 0, onlyMinutes: true },
+      thematics: thematics?.map((thematic) => {
+        return { ...thematic, url: `/thematique/${thematic.slug}` };
+      }),
+    };
+  };
+
+  /**
+   * Retrieve the formatted posts.
+   *
+   * @param {Article[]} posts - An array of articles.
+   * @returns {Post[]} An array of formatted posts.
+   */
+  const getPosts = (posts: Article[]): Post[] => {
+    return posts.map((post) => {
+      return {
+        ...post,
+        cover: post.meta.cover,
+        excerpt: post.intro,
+        meta: getPostMeta(post.meta),
+        url: `/article/${post.slug}`,
+      };
+    });
+  };
+
+  /**
+   * Retrieve the posts list from raw data.
+   *
+   * @param {EdgesResponse<RawArticle>[]} rawData - The raw data.
+   * @returns {Post[]} An array of posts.
+   */
+  const getPostsList = (rawData: EdgesResponse<RawArticle>[]): Post[] => {
+    const articlesList: RawArticle[] = [];
+    rawData.forEach((articleData) =>
+      articleData.edges.forEach((edge) => {
+        articlesList.push(edge.node);
+      })
+    );
+
+    return getPosts(
+      articlesList.map((article) => getArticleFromRawData(article))
+    );
+  };
+
+  /**
+   * Load more posts handler.
+   */
+  const loadMore = () => {
+    setSize((prevSize) => prevSize + 1);
+  };
+
+  const thematicsListTitle = intl.formatMessage({
+    defaultMessage: 'Thematics',
+    description: 'SearchPage: thematics list widget title',
+    id: 'Dq6+WH',
+  });
+
+  const topicsListTitle = intl.formatMessage({
+    defaultMessage: 'Topics',
+    description: 'SearchPage: topics list widget title',
+    id: 'N804XO',
+  });
+
+  return (
+    <>
+      <Head>
+        <title>{pageTitle}</title>
+        <meta name="description" content={pageDescription} />
+        <meta property="og:url" content={`${pageUrl}`} />
+        <meta property="og:type" content="website" />
+        <meta property="og:title" content={title} />
+        <meta property="og:description" content={pageDescription} />
+      </Head>
+      <Script
+        id="schema-blog"
+        type="application/ld+json"
+        dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaJsonLd) }}
+      />
+      <PageLayout
+        title={title}
+        breadcrumb={breadcrumb}
+        headerMeta={{ total: postsCount }}
+        widgets={[
+          <LinksListWidget
+            key="thematics-list"
+            items={getLinksListItems(
+              thematicsList.map(getPageLinkFromRawData),
+              'thematic'
+            )}
+            title={thematicsListTitle}
+            level={2}
+          />,
+          <LinksListWidget
+            key="topics-list"
+            items={getLinksListItems(
+              topicsList.map(getPageLinkFromRawData),
+              'topic'
+            )}
+            title={topicsListTitle}
+            level={2}
+          />,
+        ]}
+      >
+        {data && data.length > 0 ? (
+          <PostsList
+            byYear={true}
+            isLoading={isLoadingMore || isLoadingInitialData}
+            loadMore={loadMore}
+            posts={getPostsList(data)}
+            showLoadMoreBtn={hasNextPage}
+            total={totalArticles || 0}
+          />
+        ) : (
+          <Spinner />
+        )}
+        {error && (
+          <Notice
+            kind="error"
+            message={intl.formatMessage({
+              defaultMessage: 'Failed to load.',
+              description: 'SearchPage: failed to load text',
+              id: 'fOe8rH',
+            })}
+          />
+        )}
+      </PageLayout>
+    </>
+  );
+};
+
+export const getStaticProps: GetStaticProps<SearchPageProps> = async ({
+  locale,
+}) => {
+  const totalThematics = await getTotalThematics();
+  const thematics = await getThematicsPreview({ first: totalThematics });
+  const totalTopics = await getTotalTopics();
+  const topics = await getTopicsPreview({ first: totalTopics });
+  const translation = await loadTranslation(locale);
+
+  return {
+    props: {
+      thematicsList: thematics.edges.map((edge) => edge.node),
+      topicsList: topics.edges.map((edge) => edge.node),
+      translation,
+    },
+  };
+};
+
+export default SearchPage;
diff --git a/src/services/graphql/api.ts b/src/services/graphql/api.ts
index 5bed9f9..171ab23 100644
--- a/src/services/graphql/api.ts
+++ b/src/services/graphql/api.ts
@@ -48,7 +48,7 @@ export type ArticlesResponse<T> = {
 };
 
 export type CommentsResponse<T> = {
-  comments: T[];
+  comments: T;
 };
 
 export type SendMailResponse<T> = {
@@ -147,7 +147,14 @@ export type ByContentIdVar = {
   contentId: number;
 };
 
-export type sendMailVars = {
+export type SearchVar = {
+  /**
+   * A search term.
+   */
+  search?: string;
+};
+
+export type SendMailVars = {
   body: string;
   clientMutationId: string;
   replyTo: string;
@@ -160,14 +167,14 @@ export type VariablesMap = {
   [articlesQuery]: EdgesVars;
   [articlesSlugQuery]: EdgesVars;
   [commentsQuery]: ByContentIdVar;
-  [sendMailMutation]: sendMailVars;
+  [sendMailMutation]: SendMailVars;
   [thematicBySlugQuery]: BySlugVar;
   [thematicsListQuery]: EdgesVars;
   [thematicsSlugQuery]: EdgesVars;
   [topicBySlugQuery]: BySlugVar;
   [topicsListQuery]: EdgesVars;
   [topicsSlugQuery]: EdgesVars;
-  [totalArticlesQuery]: null;
+  [totalArticlesQuery]: SearchVar;
   [totalThematicsQuery]: null;
   [totalTopicsQuery]: null;
 };
diff --git a/src/services/graphql/articles.query.ts b/src/services/graphql/articles.query.ts
index e62835d..d65bc9e 100644
--- a/src/services/graphql/articles.query.ts
+++ b/src/services/graphql/articles.query.ts
@@ -166,8 +166,8 @@ export const articlesSlugQuery = `query ArticlesSlug($first: Int = 10, $after: S
 /**
  * Query the total number of articles.
  */
-export const totalArticlesQuery = `query PostsTotal {
-  posts {
+export const totalArticlesQuery = `query PostsTotal($search: String = "") {
+  posts(where: {search: $search}) {
     pageInfo {
       total
     }
diff --git a/src/services/graphql/articles.ts b/src/services/graphql/articles.ts
index 1eb112e..41052c4 100644
--- a/src/services/graphql/articles.ts
+++ b/src/services/graphql/articles.ts
@@ -21,10 +21,11 @@ import {
  *
  * @returns {Promise<number>} - The articles total number.
  */
-export const getTotalArticles = async (): Promise<number> => {
+export const getTotalArticles = async (search?: string): Promise<number> => {
   const response = await fetchAPI<TotalItems, typeof totalArticlesQuery>({
     api: getAPIUrl(),
     query: totalArticlesQuery,
+    variables: { search },
   });
 
   return response.posts.pageInfo.total;
diff --git a/src/services/graphql/contact.ts b/src/services/graphql/contact.ts
index fca718f..00c6ca2 100644
--- a/src/services/graphql/contact.ts
+++ b/src/services/graphql/contact.ts
@@ -1,4 +1,4 @@
-import { fetchAPI, getAPIUrl, sendMailVars } from './api';
+import { fetchAPI, getAPIUrl, SendMailVars } from './api';
 import { sendMailMutation } from './contact.mutation';
 
 export type SentEmail = {
@@ -15,7 +15,7 @@ export type SentEmail = {
  * @param {sendMailVars} data - The mail data.
  * @returns {Promise<SentEmail>} The mutation response.
  */
-export const sendMail = async (data: sendMailVars): Promise<SentEmail> => {
+export const sendMail = async (data: SendMailVars): Promise<SentEmail> => {
   const response = await fetchAPI<SentEmail, typeof sendMailMutation>({
     api: getAPIUrl(),
     query: sendMailMutation,
diff --git a/src/utils/hooks/use-data-from-api.tsx b/src/utils/hooks/use-data-from-api.tsx
new file mode 100644
index 0000000..7082941
--- /dev/null
+++ b/src/utils/hooks/use-data-from-api.tsx
@@ -0,0 +1,23 @@
+import { useEffect, useState } from 'react';
+
+/**
+ * Fetch data from an API.
+ *
+ * This hook is a wrapper to `setState` + `useEffect`.
+ *
+ * @param fetcher - A function to fetch data from API.
+ * @returns {T | undefined} The requested data.
+ */
+const useDataFromAPI = <T extends unknown>(
+  fetcher: () => Promise<T>
+): T | undefined => {
+  const [data, setData] = useState<T>();
+
+  useEffect(() => {
+    fetcher().then((apiData) => setData(apiData));
+  }, [fetcher]);
+
+  return data;
+};
+
+export default useDataFromAPI;
diff --git a/src/utils/hooks/use-pagination.tsx b/src/utils/hooks/use-pagination.tsx
index 1e24b75..a80a539 100644
--- a/src/utils/hooks/use-pagination.tsx
+++ b/src/utils/hooks/use-pagination.tsx
@@ -99,7 +99,8 @@ const usePagination = <T extends object>({
     isLoadingInitialData ||
     (size > 0 && data && typeof data[size - 1] === 'undefined');
   const isRefreshing = isValidating && data && data.length === size;
-  const hasNextPage = data && data[data.length - 1].pageInfo.hasNextPage;
+  const hasNextPage =
+    data && data.length > 0 && data[data.length - 1].pageInfo.hasNextPage;
 
   return {
     data,
-- 
cgit v1.2.3


From b214baab3e17d92f784b4f782863deafc5558ee4 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Wed, 18 May 2022 14:27:11 +0200
Subject: chore: close toolbar modals on click/focus outside

---
 .../molecules/forms/select-with-tooltip.tsx        | 10 ++++-
 src/components/molecules/modals/tooltip.tsx        | 16 ++++----
 .../organisms/forms/settings-form.module.scss      | 11 +++++
 .../organisms/forms/settings-form.stories.tsx      | 47 ++++++++++++++++++++++
 .../organisms/forms/settings-form.test.tsx         | 39 ++++++++++++++++++
 src/components/organisms/forms/settings-form.tsx   | 36 +++++++++++++++++
 src/components/organisms/modals/search-modal.tsx   | 13 +++++-
 .../organisms/modals/settings-modal.module.scss    | 14 +------
 .../organisms/modals/settings-modal.stories.tsx    |  8 ----
 .../organisms/modals/settings-modal.test.tsx       | 27 +------------
 src/components/organisms/modals/settings-modal.tsx | 42 +++++++------------
 src/components/organisms/toolbar/main-nav.tsx      | 16 ++++----
 .../organisms/toolbar/search.stories.tsx           |  1 -
 src/components/organisms/toolbar/search.test.tsx   |  5 ---
 src/components/organisms/toolbar/search.tsx        | 16 ++++----
 .../organisms/toolbar/settings.stories.tsx         |  8 ----
 src/components/organisms/toolbar/settings.tsx      | 16 ++++----
 src/components/organisms/toolbar/toolbar.tsx       | 18 ++++++++-
 src/utils/hooks/use-click-outside.tsx              | 43 ++++++++++++++++++++
 19 files changed, 258 insertions(+), 128 deletions(-)
 create mode 100644 src/components/organisms/forms/settings-form.module.scss
 create mode 100644 src/components/organisms/forms/settings-form.stories.tsx
 create mode 100644 src/components/organisms/forms/settings-form.test.tsx
 create mode 100644 src/components/organisms/forms/settings-form.tsx
 create mode 100644 src/utils/hooks/use-click-outside.tsx

(limited to 'src/components/organisms/toolbar/search.test.tsx')

diff --git a/src/components/molecules/forms/select-with-tooltip.tsx b/src/components/molecules/forms/select-with-tooltip.tsx
index cf7b041..f576a15 100644
--- a/src/components/molecules/forms/select-with-tooltip.tsx
+++ b/src/components/molecules/forms/select-with-tooltip.tsx
@@ -1,4 +1,5 @@
-import { FC, useState } from 'react';
+import useClickOutside from '@utils/hooks/use-click-outside';
+import { FC, useRef, useState } from 'react';
 import HelpButton from '../buttons/help-button';
 import Tooltip, { type TooltipProps } from '../modals/tooltip';
 import LabelledSelect, { type LabelledSelectProps } from './labelled-select';
@@ -28,11 +29,17 @@ const SelectWithTooltip: FC<SelectWithTooltipProps> = ({
   ...props
 }) => {
   const [isTooltipOpened, setIsTooltipOpened] = useState<boolean>(false);
+  const tooltipRef = useRef<HTMLDivElement>(null);
   const buttonModifier = isTooltipOpened ? styles['btn--activated'] : '';
   const tooltipModifier = isTooltipOpened
     ? styles['tooltip--visible']
     : styles['tooltip--hidden'];
 
+  useClickOutside(
+    tooltipRef,
+    () => isTooltipOpened && setIsTooltipOpened(false)
+  );
+
   return (
     <div className={styles.wrapper}>
       <LabelledSelect
@@ -50,6 +57,7 @@ const SelectWithTooltip: FC<SelectWithTooltipProps> = ({
         content={content}
         icon="?"
         className={`${styles.tooltip} ${tooltipModifier} ${tooltipClassName}`}
+        ref={tooltipRef}
       />
     </div>
   );
diff --git a/src/components/molecules/modals/tooltip.tsx b/src/components/molecules/modals/tooltip.tsx
index 80721f3..efb3009 100644
--- a/src/components/molecules/modals/tooltip.tsx
+++ b/src/components/molecules/modals/tooltip.tsx
@@ -1,5 +1,5 @@
 import List, { type ListItem } from '@components/atoms/lists/list';
-import { FC, ReactNode } from 'react';
+import { forwardRef, ForwardRefRenderFunction, ReactNode } from 'react';
 import styles from './tooltip.module.scss';
 
 export type TooltipProps = {
@@ -26,12 +26,10 @@ export type TooltipProps = {
  *
  * Render a tooltip modal.
  */
-const Tooltip: FC<TooltipProps> = ({
-  className = '',
-  content,
-  icon,
-  title,
-}) => {
+const Tooltip: ForwardRefRenderFunction<HTMLDivElement, TooltipProps> = (
+  { className = '', content, icon, title },
+  ref
+) => {
   /**
    * Format an array of strings to an array of object with id and value.
    *
@@ -45,7 +43,7 @@ const Tooltip: FC<TooltipProps> = ({
   };
 
   return (
-    <div className={`${styles.wrapper} ${className}`}>
+    <div className={`${styles.wrapper} ${className}`} ref={ref}>
       <div className={styles.title}>
         <span className={styles.icon}>{icon}</span>
         {title}
@@ -59,4 +57,4 @@ const Tooltip: FC<TooltipProps> = ({
   );
 };
 
-export default Tooltip;
+export default forwardRef(Tooltip);
diff --git a/src/components/organisms/forms/settings-form.module.scss b/src/components/organisms/forms/settings-form.module.scss
new file mode 100644
index 0000000..a6a2077
--- /dev/null
+++ b/src/components/organisms/forms/settings-form.module.scss
@@ -0,0 +1,11 @@
+@use "@styles/abstracts/mixins" as mix;
+
+.label {
+  margin-right: auto;
+
+  @include mix.media("screen") {
+    @include mix.dimensions(null, "2xs", "height") {
+      font-size: var(--font-size-sm);
+    }
+  }
+}
diff --git a/src/components/organisms/forms/settings-form.stories.tsx b/src/components/organisms/forms/settings-form.stories.tsx
new file mode 100644
index 0000000..46305e7
--- /dev/null
+++ b/src/components/organisms/forms/settings-form.stories.tsx
@@ -0,0 +1,47 @@
+import { ComponentMeta, ComponentStory } from '@storybook/react';
+import SettingsForm from './settings-form';
+
+/**
+ * SettingsModal - Storybook Meta
+ */
+export default {
+  title: 'Organisms/Forms',
+  component: SettingsForm,
+  argTypes: {
+    className: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set additional classnames to the modal wrapper.',
+      table: {
+        category: 'Styles',
+      },
+      type: {
+        name: 'string',
+        required: false,
+      },
+    },
+    tooltipClassName: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set additional classnames to the tooltip wrapper.',
+      table: {
+        category: 'Styles',
+      },
+      type: {
+        name: 'string',
+        required: false,
+      },
+    },
+  },
+} as ComponentMeta<typeof SettingsForm>;
+
+const Template: ComponentStory<typeof SettingsForm> = (args) => (
+  <SettingsForm {...args} />
+);
+
+/**
+ * Form Stories - Settings
+ */
+export const Settings = Template.bind({});
diff --git a/src/components/organisms/forms/settings-form.test.tsx b/src/components/organisms/forms/settings-form.test.tsx
new file mode 100644
index 0000000..beb65ec
--- /dev/null
+++ b/src/components/organisms/forms/settings-form.test.tsx
@@ -0,0 +1,39 @@
+import { render, screen } from '@test-utils';
+import SettingsForm from './settings-form';
+
+describe('SettingsForm', () => {
+  it('renders a form', () => {
+    render(<SettingsForm />);
+    expect(
+      screen.getByRole('form', { name: /^Settings form/i })
+    ).toBeInTheDocument();
+  });
+
+  it('renders a theme toggle setting', () => {
+    render(<SettingsForm />);
+    expect(
+      screen.getByRole('checkbox', { name: /^Theme:/i })
+    ).toBeInTheDocument();
+  });
+
+  it('renders a code blocks toggle setting', () => {
+    render(<SettingsForm />);
+    expect(
+      screen.getByRole('checkbox', { name: /^Code blocks:/i })
+    ).toBeInTheDocument();
+  });
+
+  it('renders a motion setting', () => {
+    render(<SettingsForm />);
+    expect(
+      screen.getByRole('checkbox', { name: /^Animations:/i })
+    ).toBeInTheDocument();
+  });
+
+  it('renders a Ackee setting', () => {
+    render(<SettingsForm />);
+    expect(
+      screen.getByRole('combobox', { name: /^Tracking:/i })
+    ).toBeInTheDocument();
+  });
+});
diff --git a/src/components/organisms/forms/settings-form.tsx b/src/components/organisms/forms/settings-form.tsx
new file mode 100644
index 0000000..0a34601
--- /dev/null
+++ b/src/components/organisms/forms/settings-form.tsx
@@ -0,0 +1,36 @@
+import Form from '@components/atoms/forms/form';
+import AckeeSelect, {
+  type AckeeSelectProps,
+} from '@components/molecules/forms/ackee-select';
+import MotionToggle from '@components/molecules/forms/motion-toggle';
+import PrismThemeToggle from '@components/molecules/forms/prism-theme-toggle';
+import ThemeToggle from '@components/molecules/forms/theme-toggle';
+import { FC } from 'react';
+import { useIntl } from 'react-intl';
+import styles from './settings-form.module.scss';
+
+export type SettingsFormProps = Pick<AckeeSelectProps, 'tooltipClassName'>;
+
+const SettingsForm: FC<SettingsFormProps> = ({ tooltipClassName }) => {
+  const intl = useIntl();
+  const ariaLabel = intl.formatMessage({
+    defaultMessage: 'Settings form',
+    id: 'gX+YVy',
+    description: 'SettingsForm: an accessible form name',
+  });
+
+  return (
+    <Form aria-label={ariaLabel} onSubmit={() => null}>
+      <ThemeToggle labelClassName={styles.label} value={false} />
+      <PrismThemeToggle labelClassName={styles.label} value={false} />
+      <MotionToggle labelClassName={styles.label} value={false} />
+      <AckeeSelect
+        initialValue="full"
+        labelClassName={styles.label}
+        tooltipClassName={tooltipClassName}
+      />
+    </Form>
+  );
+};
+
+export default SettingsForm;
diff --git a/src/components/organisms/modals/search-modal.tsx b/src/components/organisms/modals/search-modal.tsx
index 866bc25..e92bf1b 100644
--- a/src/components/organisms/modals/search-modal.tsx
+++ b/src/components/organisms/modals/search-modal.tsx
@@ -1,9 +1,18 @@
+import Spinner from '@components/atoms/loaders/spinner';
 import Modal, { type ModalProps } from '@components/molecules/modals/modal';
+import dynamic from 'next/dynamic';
 import { FC } from 'react';
 import { useIntl } from 'react-intl';
-import SearchForm, { SearchFormProps } from '../forms/search-form';
+import { type SearchFormProps } from '../forms/search-form';
 import styles from './search-modal.module.scss';
 
+const DynamicSearchForm = dynamic(
+  () => import('@components/organisms/forms/search-form'),
+  {
+    loading: () => <Spinner />,
+  }
+);
+
 export type SearchModalProps = Pick<SearchFormProps, 'searchPage'> & {
   /**
    * Set additional classnames to modal wrapper.
@@ -26,7 +35,7 @@ const SearchModal: FC<SearchModalProps> = ({ className, searchPage }) => {
 
   return (
     <Modal title={modalTitle} className={`${styles.wrapper} ${className}`}>
-      <SearchForm hideLabel={true} searchPage={searchPage} />
+      <DynamicSearchForm hideLabel={true} searchPage={searchPage} />
     </Modal>
   );
 };
diff --git a/src/components/organisms/modals/settings-modal.module.scss b/src/components/organisms/modals/settings-modal.module.scss
index ebae3da..a6a2077 100644
--- a/src/components/organisms/modals/settings-modal.module.scss
+++ b/src/components/organisms/modals/settings-modal.module.scss
@@ -1,21 +1,11 @@
 @use "@styles/abstracts/mixins" as mix;
 
-.wrapper {
-  .label {
-    margin-right: auto;
-  }
+.label {
+  margin-right: auto;
 
   @include mix.media("screen") {
     @include mix.dimensions(null, "2xs", "height") {
       font-size: var(--font-size-sm);
-
-      .heading {
-        font-size: var(--font-size-lg);
-      }
-
-      .label {
-        font-size: var(--font-size-sm);
-      }
     }
   }
 }
diff --git a/src/components/organisms/modals/settings-modal.stories.tsx b/src/components/organisms/modals/settings-modal.stories.tsx
index 0abe004..0fe8c18 100644
--- a/src/components/organisms/modals/settings-modal.stories.tsx
+++ b/src/components/organisms/modals/settings-modal.stories.tsx
@@ -1,5 +1,4 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
-import { IntlProvider } from 'react-intl';
 import SettingsModal from './settings-modal';
 
 /**
@@ -36,13 +35,6 @@ export default {
       },
     },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
 } as ComponentMeta<typeof SettingsModal>;
 
 const Template: ComponentStory<typeof SettingsModal> = (args) => (
diff --git a/src/components/organisms/modals/settings-modal.test.tsx b/src/components/organisms/modals/settings-modal.test.tsx
index 6291e54..acbf7d1 100644
--- a/src/components/organisms/modals/settings-modal.test.tsx
+++ b/src/components/organisms/modals/settings-modal.test.tsx
@@ -2,31 +2,8 @@ import { render, screen } from '@test-utils';
 import SettingsModal from './settings-modal';
 
 describe('SettingsModal', () => {
-  it('renders a theme toggle setting', () => {
+  it('renders a fake heading', () => {
     render(<SettingsModal />);
-    expect(
-      screen.getByRole('checkbox', { name: /^Theme:/i })
-    ).toBeInTheDocument();
-  });
-
-  it('renders a code blocks toggle setting', () => {
-    render(<SettingsModal />);
-    expect(
-      screen.getByRole('checkbox', { name: /^Code blocks:/i })
-    ).toBeInTheDocument();
-  });
-
-  it('renders a motion setting', () => {
-    render(<SettingsModal />);
-    expect(
-      screen.getByRole('checkbox', { name: /^Animations:/i })
-    ).toBeInTheDocument();
-  });
-
-  it('renders a Ackee setting', () => {
-    render(<SettingsModal />);
-    expect(
-      screen.getByRole('combobox', { name: /^Tracking:/i })
-    ).toBeInTheDocument();
+    expect(screen.getByText(/Settings/i)).toBeInTheDocument();
   });
 });
diff --git a/src/components/organisms/modals/settings-modal.tsx b/src/components/organisms/modals/settings-modal.tsx
index 20d2605..e724076 100644
--- a/src/components/organisms/modals/settings-modal.tsx
+++ b/src/components/organisms/modals/settings-modal.tsx
@@ -1,25 +1,20 @@
-import Form from '@components/atoms/forms/form';
-import AckeeSelect, {
-  type AckeeSelectProps,
-} from '@components/molecules/forms/ackee-select';
-import MotionToggle from '@components/molecules/forms/motion-toggle';
-import PrismThemeToggle from '@components/molecules/forms/prism-theme-toggle';
-import ThemeToggle from '@components/molecules/forms/theme-toggle';
+import Spinner from '@components/atoms/loaders/spinner';
 import Modal, { type ModalProps } from '@components/molecules/modals/modal';
+import dynamic from 'next/dynamic';
 import { FC } from 'react';
 import { useIntl } from 'react-intl';
+import { type SettingsFormProps } from '../forms/settings-form';
 import styles from './settings-modal.module.scss';
 
-export type SettingsModalProps = {
-  /**
-   * Set additional classnames to the modal wrapper.
-   */
-  className?: ModalProps['className'];
-  /**
-   * Set additional classnames to the tooltip wrapper.
-   */
-  tooltipClassName?: AckeeSelectProps['tooltipClassName'];
-};
+const DynamicSettingsForm = dynamic(
+  () => import('@components/organisms/forms/settings-form'),
+  {
+    loading: () => <Spinner />,
+  }
+);
+
+export type SettingsModalProps = Pick<ModalProps, 'className'> &
+  Pick<SettingsFormProps, 'tooltipClassName'>;
 
 /**
  * SettingsModal component
@@ -28,7 +23,7 @@ export type SettingsModalProps = {
  */
 const SettingsModal: FC<SettingsModalProps> = ({
   className = '',
-  tooltipClassName = '',
+  ...props
 }) => {
   const intl = useIntl();
   const title = intl.formatMessage({
@@ -44,16 +39,7 @@ const SettingsModal: FC<SettingsModalProps> = ({
       className={`${styles.wrapper} ${className}`}
       headingClassName={styles.heading}
     >
-      <Form onSubmit={() => null}>
-        <ThemeToggle labelClassName={styles.label} value={false} />
-        <PrismThemeToggle labelClassName={styles.label} value={false} />
-        <MotionToggle labelClassName={styles.label} value={false} />
-        <AckeeSelect
-          initialValue="full"
-          labelClassName={styles.label}
-          tooltipClassName={tooltipClassName}
-        />
-      </Form>
+      <DynamicSettingsForm {...props} />
     </Modal>
   );
 };
diff --git a/src/components/organisms/toolbar/main-nav.tsx b/src/components/organisms/toolbar/main-nav.tsx
index 35e3fd6..d205112 100644
--- a/src/components/organisms/toolbar/main-nav.tsx
+++ b/src/components/organisms/toolbar/main-nav.tsx
@@ -5,7 +5,7 @@ import Nav, {
   type NavProps,
   type NavItem,
 } from '@components/molecules/nav/nav';
-import { FC } from 'react';
+import { forwardRef, ForwardRefRenderFunction } from 'react';
 import { useIntl } from 'react-intl';
 import mainNavStyles from './main-nav.module.scss';
 import sharedStyles from './toolbar-items.module.scss';
@@ -34,12 +34,10 @@ export type MainNavProps = {
  *
  * Render the main navigation.
  */
-const MainNav: FC<MainNavProps> = ({
-  className = '',
-  isActive,
-  items,
-  setIsActive,
-}) => {
+const MainNav: ForwardRefRenderFunction<HTMLDivElement, MainNavProps> = (
+  { className = '', isActive, items, setIsActive },
+  ref
+) => {
   const intl = useIntl();
   const label = isActive
     ? intl.formatMessage({
@@ -54,7 +52,7 @@ const MainNav: FC<MainNavProps> = ({
       });
 
   return (
-    <div className={`${sharedStyles.item} ${mainNavStyles.item}`}>
+    <div className={`${sharedStyles.item} ${mainNavStyles.item}`} ref={ref}>
       <Checkbox
         id="main-nav-button"
         name="main-nav-button"
@@ -79,4 +77,4 @@ const MainNav: FC<MainNavProps> = ({
   );
 };
 
-export default MainNav;
+export default forwardRef(MainNav);
diff --git a/src/components/organisms/toolbar/search.stories.tsx b/src/components/organisms/toolbar/search.stories.tsx
index c6063a0..6aaffde 100644
--- a/src/components/organisms/toolbar/search.stories.tsx
+++ b/src/components/organisms/toolbar/search.stories.tsx
@@ -1,6 +1,5 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
 import { useState } from 'react';
-import { IntlProvider } from 'react-intl';
 import Search from './search';
 
 /**
diff --git a/src/components/organisms/toolbar/search.test.tsx b/src/components/organisms/toolbar/search.test.tsx
index a18b679..7c77eac 100644
--- a/src/components/organisms/toolbar/search.test.tsx
+++ b/src/components/organisms/toolbar/search.test.tsx
@@ -11,9 +11,4 @@ describe('Search', () => {
     render(<Search searchPage="#" isActive={true} setIsActive={() => null} />);
     expect(screen.getByRole('checkbox')).toHaveAccessibleName('Close search');
   });
-
-  it('renders a search form', () => {
-    render(<Search searchPage="#" isActive={true} setIsActive={() => null} />);
-    expect(screen.getByRole('searchbox')).toBeInTheDocument();
-  });
 });
diff --git a/src/components/organisms/toolbar/search.tsx b/src/components/organisms/toolbar/search.tsx
index a1471ef..5695348 100644
--- a/src/components/organisms/toolbar/search.tsx
+++ b/src/components/organisms/toolbar/search.tsx
@@ -1,7 +1,7 @@
 import Checkbox, { type CheckboxProps } from '@components/atoms/forms/checkbox';
 import Label from '@components/atoms/forms/label';
 import MagnifyingGlass from '@components/atoms/icons/magnifying-glass';
-import { FC } from 'react';
+import { forwardRef, ForwardRefRenderFunction } from 'react';
 import { useIntl } from 'react-intl';
 import SearchModal, { type SearchModalProps } from '../modals/search-modal';
 import searchStyles from './search.module.scss';
@@ -26,12 +26,10 @@ export type SearchProps = {
   setIsActive: CheckboxProps['setValue'];
 };
 
-const Search: FC<SearchProps> = ({
-  className = '',
-  isActive,
-  searchPage,
-  setIsActive,
-}) => {
+const Search: ForwardRefRenderFunction<HTMLDivElement, SearchProps> = (
+  { className = '', isActive, searchPage, setIsActive },
+  ref
+) => {
   const intl = useIntl();
   const label = isActive
     ? intl.formatMessage({
@@ -46,7 +44,7 @@ const Search: FC<SearchProps> = ({
       });
 
   return (
-    <div className={`${sharedStyles.item} ${searchStyles.item}`}>
+    <div className={`${sharedStyles.item} ${searchStyles.item}`} ref={ref}>
       <Checkbox
         id="search-button"
         name="search-button"
@@ -69,4 +67,4 @@ const Search: FC<SearchProps> = ({
   );
 };
 
-export default Search;
+export default forwardRef(Search);
diff --git a/src/components/organisms/toolbar/settings.stories.tsx b/src/components/organisms/toolbar/settings.stories.tsx
index 1ec0897..aab4b9e 100644
--- a/src/components/organisms/toolbar/settings.stories.tsx
+++ b/src/components/organisms/toolbar/settings.stories.tsx
@@ -1,6 +1,5 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
 import { useState } from 'react';
-import { IntlProvider } from 'react-intl';
 import Settings from './settings';
 
 /**
@@ -57,13 +56,6 @@ export default {
       },
     },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
 } as ComponentMeta<typeof Settings>;
 
 const Template: ComponentStory<typeof Settings> = ({
diff --git a/src/components/organisms/toolbar/settings.tsx b/src/components/organisms/toolbar/settings.tsx
index 3b10226..43d3190 100644
--- a/src/components/organisms/toolbar/settings.tsx
+++ b/src/components/organisms/toolbar/settings.tsx
@@ -1,7 +1,7 @@
 import Checkbox, { type CheckboxProps } from '@components/atoms/forms/checkbox';
 import Label from '@components/atoms/forms/label';
 import Cog from '@components/atoms/icons/cog';
-import { FC } from 'react';
+import { FC, forwardRef, ForwardRefRenderFunction } from 'react';
 import { useIntl } from 'react-intl';
 import SettingsModal, {
   type SettingsModalProps,
@@ -28,12 +28,10 @@ export type SettingsProps = {
   tooltipClassName?: SettingsModalProps['tooltipClassName'];
 };
 
-const Settings: FC<SettingsProps> = ({
-  className = '',
-  isActive,
-  setIsActive,
-  tooltipClassName = '',
-}) => {
+const Settings: ForwardRefRenderFunction<HTMLDivElement, SettingsProps> = (
+  { className = '', isActive, setIsActive, tooltipClassName = '' },
+  ref
+) => {
   const intl = useIntl();
   const label = isActive
     ? intl.formatMessage({
@@ -48,7 +46,7 @@ const Settings: FC<SettingsProps> = ({
       });
 
   return (
-    <div className={`${sharedStyles.item} ${settingsStyles.item}`}>
+    <div className={`${sharedStyles.item} ${settingsStyles.item}`} ref={ref}>
       <Checkbox
         id="settings-button"
         name="settings-button"
@@ -71,4 +69,4 @@ const Settings: FC<SettingsProps> = ({
   );
 };
 
-export default Settings;
+export default forwardRef(Settings);
diff --git a/src/components/organisms/toolbar/toolbar.tsx b/src/components/organisms/toolbar/toolbar.tsx
index 6593055..e4188fe 100644
--- a/src/components/organisms/toolbar/toolbar.tsx
+++ b/src/components/organisms/toolbar/toolbar.tsx
@@ -1,4 +1,5 @@
-import { FC, useState } from 'react';
+import useClickOutside from '@utils/hooks/use-click-outside';
+import { FC, useRef, useState } from 'react';
 import MainNav, { type MainNavProps } from '../toolbar/main-nav';
 import Search, { type SearchProps } from '../toolbar/search';
 import Settings from '../toolbar/settings';
@@ -22,8 +23,18 @@ export type ToolbarProps = Pick<SearchProps, 'searchPage'> & {
  */
 const Toolbar: FC<ToolbarProps> = ({ className = '', nav, searchPage }) => {
   const [isNavOpened, setIsNavOpened] = useState<boolean>(false);
-  const [isSettingsOpened, setIsSettingsOpened] = useState<boolean>(false);
   const [isSearchOpened, setIsSearchOpened] = useState<boolean>(false);
+  const [isSettingsOpened, setIsSettingsOpened] = useState<boolean>(false);
+  const mainNavRef = useRef<HTMLDivElement>(null);
+  const searchRef = useRef<HTMLDivElement>(null);
+  const settingsRef = useRef<HTMLDivElement>(null);
+
+  useClickOutside(mainNavRef, () => isNavOpened && setIsNavOpened(false));
+  useClickOutside(searchRef, () => isSearchOpened && setIsSearchOpened(false));
+  useClickOutside(
+    settingsRef,
+    () => isSettingsOpened && setIsSettingsOpened(false)
+  );
 
   return (
     <div className={`${styles.wrapper} ${className}`}>
@@ -32,18 +43,21 @@ const Toolbar: FC<ToolbarProps> = ({ className = '', nav, searchPage }) => {
         isActive={isNavOpened}
         setIsActive={setIsNavOpened}
         className={styles.modal}
+        ref={mainNavRef}
       />
       <Search
         searchPage={searchPage}
         isActive={isSearchOpened}
         setIsActive={setIsSearchOpened}
         className={`${styles.modal} ${styles['modal--search']}`}
+        ref={searchRef}
       />
       <Settings
         isActive={isSettingsOpened}
         setIsActive={setIsSettingsOpened}
         className={`${styles.modal} ${styles['modal--settings']}`}
         tooltipClassName={styles.tooltip}
+        ref={settingsRef}
       />
     </div>
   );
diff --git a/src/utils/hooks/use-click-outside.tsx b/src/utils/hooks/use-click-outside.tsx
new file mode 100644
index 0000000..066c1c2
--- /dev/null
+++ b/src/utils/hooks/use-click-outside.tsx
@@ -0,0 +1,43 @@
+import { RefObject, useCallback, useEffect } from 'react';
+
+/**
+ * Listen for click/focus outside an element and execute the given callback.
+ *
+ * @param el - A React reference to an element.
+ * @param callback - A callback function to execute on click outside.
+ */
+const useClickOutside = (el: RefObject<HTMLElement>, callback: () => void) => {
+  /**
+   * Check if an event target is outside an element.
+   *
+   * @param {RefObject<HTMLElement>} ref - A React reference object.
+   * @param {EventTarget} target - An event target.
+   * @returns {boolean} True if the event target is outside the ref object.
+   */
+  const isTargetOutside = (
+    ref: RefObject<HTMLElement>,
+    target: EventTarget
+  ): boolean => {
+    if (!ref.current) return false;
+    return !ref.current.contains(target as Node);
+  };
+
+  const handleEvent = useCallback(
+    (e: MouseEvent | FocusEvent) => {
+      if (e.target && isTargetOutside(el, e.target)) callback();
+    },
+    [el, callback]
+  );
+
+  useEffect(() => {
+    document.addEventListener('mousedown', handleEvent);
+    document.addEventListener('focusin', handleEvent);
+
+    return () => {
+      document.removeEventListener('mousedown', handleEvent);
+      document.removeEventListener('focusin', handleEvent);
+    };
+  }, [handleEvent]);
+};
+
+export default useClickOutside;
-- 
cgit v1.2.3

