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(theme-{classic,common}): split navbar into smaller components + cleanup + swizzle config #6895

Merged
merged 18 commits into from
Mar 18, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/docusaurus-theme-classic/src/theme-classic.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ declare module '@theme/ColorModeToggle' {
readonly onChange: (e: SyntheticEvent) => void;
}

export default function Toggle(props: Props): JSX.Element;
export default function ColorModeToggle(props: Props): JSX.Element;
}

declare module '@theme/Logo' {
Expand Down
153 changes: 21 additions & 132 deletions packages/docusaurus-theme-classic/src/theme/Navbar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,19 @@
* LICENSE file in the root directory of this source tree.
*/

import React, {useCallback, useState, useEffect} from 'react';
import React from 'react';
import clsx from 'clsx';
import Translate from '@docusaurus/Translate';
import SearchBar from '@theme/SearchBar';
import ColorModeToggle from '@theme/ColorModeToggle';
import {
useThemeConfig,
useMobileSecondaryMenuRenderer,
usePrevious,
useHistoryPopHandler,
useHideableNavbar,
useLockBodyScroll,
useWindowSize,
useColorMode,
splitNavbarItems,
useNavbarSecondaryMenu,
useNavbarMobileSidebar,
} from '@docusaurus/theme-common';
import {useActivePlugin} from '@docusaurus/plugin-content-docs/client';
import NavbarItem, {type Props as NavbarItemConfig} from '@theme/NavbarItem';
Expand All @@ -28,119 +27,24 @@ import IconClose from '@theme/IconClose';

import styles from './styles.module.css';

// retrocompatible with v1
const DefaultNavItemPosition = 'right';

function useNavbarItems() {
// TODO temporary casting until ThemeConfig type is improved
return useThemeConfig().navbar.items as NavbarItemConfig[];
}

// If split links by left/right
// if position is unspecified, fallback to right (as v1)
function splitNavItemsByPosition(items: NavbarItemConfig[]) {
const leftItems = items.filter(
(item) => (item.position ?? DefaultNavItemPosition) === 'left',
);
const rightItems = items.filter(
(item) => (item.position ?? DefaultNavItemPosition) === 'right',
);
return {
leftItems,
rightItems,
};
}

function useMobileSidebar() {
const windowSize = useWindowSize();

// Mobile sidebar not visible on hydration: can avoid SSR rendering
const shouldRender = windowSize === 'mobile'; // || windowSize === 'ssr';

const [shown, setShown] = useState(false);

// Close mobile sidebar on navigation pop
// Most likely firing when using the Android back button (but not only)
useHistoryPopHandler(() => {
if (shown) {
setShown(false);
// Should we prevent the navigation here?
// See https://github.com/facebook/docusaurus/pull/5462#issuecomment-911699846
return false; // prevent pop navigation
}
return undefined;
});

const toggle = useCallback(() => {
setShown((s) => !s);
}, []);

useEffect(() => {
if (windowSize === 'desktop') {
setShown(false);
}
}, [windowSize]);

return {shouldRender, toggle, shown};
}

function useColorModeToggle() {
const {
colorMode: {disableSwitch},
} = useThemeConfig();
const {isDarkTheme, setLightTheme, setDarkTheme} = useColorMode();
const toggle = useCallback(
(e) => (e.target.checked ? setDarkTheme() : setLightTheme()),
[setLightTheme, setDarkTheme],
);
return {isDarkTheme, toggle, disabled: disableSwitch};
}

function useSecondaryMenu({
sidebarShown,
toggleSidebar,
}: NavbarMobileSidebarProps) {
const content = useMobileSecondaryMenuRenderer()?.({
toggleSidebar,
});
const previousContent = usePrevious(content);

const [shown, setShown] = useState<boolean>(
() =>
// /!\ content is set with useEffect,
// so it's not available on mount anyway
// "return !!content" => always returns false
false,
function NavbarColorModeToggle({className}: {className?: string}) {
const disabled = useThemeConfig().colorMode.disableSwitch;
const {isDarkTheme, toggle} = useColorMode();
if (disabled) {
return null;
}
return (
<ColorModeToggle
className={className}
checked={isDarkTheme}
onChange={toggle}
/>
);

// When content is become available for the first time (set in useEffect)
// we set this content to be shown!
useEffect(() => {
const contentBecameAvailable = content && !previousContent;
if (contentBecameAvailable) {
setShown(true);
}
}, [content, previousContent]);

const hasContent = !!content;

// On sidebar close, secondary menu is set to be shown on next re-opening
// (if any secondary menu content available)
useEffect(() => {
if (!hasContent) {
setShown(false);
return;
}
if (!sidebarShown) {
setShown(true);
}
}, [sidebarShown, hasContent]);

const hide = useCallback(() => {
setShown(false);
}, []);

return {shown, hide, content};
}

type NavbarMobileSidebarProps = {
Expand All @@ -155,9 +59,7 @@ function NavbarMobileSidebar({
useLockBodyScroll(sidebarShown);
const items = useNavbarItems();

const colorModeToggle = useColorModeToggle();

const secondaryMenu = useSecondaryMenu({
const secondaryMenu = useNavbarSecondaryMenu({
sidebarShown,
toggleSidebar,
});
Expand All @@ -170,13 +72,7 @@ function NavbarMobileSidebar({
imageClassName="navbar__logo"
titleClassName="navbar__title"
/>
{!colorModeToggle.disabled && (
<ColorModeToggle
className={styles.navbarSidebarToggle}
checked={colorModeToggle.isDarkTheme}
onChange={colorModeToggle.toggle}
/>
)}
<NavbarColorModeToggle className={styles.navbarSidebarToggle} />
<button
type="button"
className="clean-btn navbar-sidebar__close"
Expand Down Expand Up @@ -225,14 +121,13 @@ export default function Navbar(): JSX.Element {
navbar: {hideOnScroll, style},
} = useThemeConfig();

const mobileSidebar = useMobileSidebar();
const colorModeToggle = useColorModeToggle();
const mobileSidebar = useNavbarMobileSidebar();
const activeDocPlugin = useActivePlugin();
const {navbarRef, isNavbarVisible} = useHideableNavbar(hideOnScroll);

const items = useNavbarItems();
const hasSearchNavbarItem = items.some((item) => item.type === 'search');
const {leftItems, rightItems} = splitNavItemsByPosition(items);
const [leftItems, rightItems] = splitNavbarItems(items);

return (
<nav
Expand Down Expand Up @@ -276,13 +171,7 @@ export default function Navbar(): JSX.Element {
{rightItems.map((item, i) => (
<NavbarItem {...item} key={i} />
))}
{!colorModeToggle.disabled && (
<ColorModeToggle
className={styles.toggle}
checked={colorModeToggle.isDarkTheme}
onChange={colorModeToggle.toggle}
/>
)}
<NavbarColorModeToggle className={styles.toggle} />
{!hasSearchNavbarItem && <SearchBar />}
</div>
</div>
Expand Down
6 changes: 6 additions & 0 deletions packages/docusaurus-theme-common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ export {
TabGroupChoiceProvider,
} from './utils/tabGroupChoiceUtils';

export {
splitNavbarItems,
useNavbarMobileSidebar,
useNavbarSecondaryMenu,
} from './utils/navbarUtils';

export {default as useHideableNavbar} from './hooks/useHideableNavbar';
export {
default as useKeyboardNavigation,
Expand Down
15 changes: 12 additions & 3 deletions packages/docusaurus-theme-common/src/utils/colorModeUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type ColorModeContextValue = {
readonly isDarkTheme: boolean;
readonly setLightTheme: () => void;
readonly setDarkTheme: () => void;
readonly toggle: () => void;
};

const ThemeStorageKey = 'theme';
Expand Down Expand Up @@ -116,10 +117,17 @@ function useColorModeContextValue(): ColorModeContextValue {
};
}, [disableSwitch, respectPrefersColorScheme]);

const toggle = useCallback(() => {
setTheme((currentTheme) =>
currentTheme === themes.dark ? themes.light : themes.dark,
);
}, []);

return {
isDarkTheme: theme === themes.dark,
setLightTheme,
setDarkTheme,
toggle,
};
}

Expand All @@ -132,10 +140,11 @@ export function ColorModeProvider({
}: {
children: ReactNode;
}): JSX.Element {
const {isDarkTheme, setLightTheme, setDarkTheme} = useColorModeContextValue();
const {isDarkTheme, setLightTheme, setDarkTheme, toggle} =
useColorModeContextValue();
const contextValue = useMemo(
() => ({isDarkTheme, setLightTheme, setDarkTheme}),
[isDarkTheme, setLightTheme, setDarkTheme],
() => ({isDarkTheme, setLightTheme, setDarkTheme, toggle}),
[isDarkTheme, setLightTheme, setDarkTheme, toggle],
);
return (
<ColorModeContext.Provider value={contextValue}>
Expand Down
117 changes: 117 additions & 0 deletions packages/docusaurus-theme-common/src/utils/navbarUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {type ReactNode, useCallback, useEffect, useState} from 'react';
import useWindowSize from '../hooks/useWindowSize';
import {useHistoryPopHandler} from './historyUtils';
import {useMobileSecondaryMenuRenderer} from './mobileSecondaryMenu';
import {usePrevious} from './usePrevious';

const DefaultNavItemPosition = 'right';

// If split links by left/right
// if position is unspecified, fallback to right
export function splitNavbarItems<
// TODO BAD, temporary type hack
T extends {position?: 'left' | 'right'},
>(items: T[]): [leftItems: T[], rightItems: T[]] {
function isLeft(item: T): boolean {
return (item.position ?? DefaultNavItemPosition) === 'left';
}

const leftItems = items.filter(isLeft);
const rightItems = items.filter((item) => !isLeft(item));

return [leftItems, rightItems];
}

export function useNavbarMobileSidebar(): {
shouldRender: boolean;
toggle: () => void;
shown: boolean;
} {
slorber marked this conversation as resolved.
Show resolved Hide resolved
const windowSize = useWindowSize();

// Mobile sidebar not visible on hydration: can avoid SSR rendering
const shouldRender = windowSize === 'mobile'; // || windowSize === 'ssr';

const [shown, setShown] = useState(false);

// Close mobile sidebar on navigation pop
// Most likely firing when using the Android back button (but not only)
useHistoryPopHandler(() => {
if (shown) {
setShown(false);
// Should we prevent the navigation here?
// See https://github.com/facebook/docusaurus/pull/5462#issuecomment-911699846
return false; // prevent pop navigation
}
return undefined;
});

const toggle = useCallback(() => {
setShown((s) => !s);
}, []);

useEffect(() => {
if (windowSize === 'desktop') {
setShown(false);
}
}, [windowSize]);

return {shouldRender, toggle, shown};
}

export function useNavbarSecondaryMenu({
sidebarShown,
toggleSidebar,
}: {
sidebarShown: boolean;
toggleSidebar: () => void;
}): {shown: boolean; hide: () => void; content: ReactNode} {
const content = useMobileSecondaryMenuRenderer()?.({
toggleSidebar,
});
const previousContent = usePrevious(content);

const [shown, setShown] = useState<boolean>(
() =>
// /!\ content is set with useEffect,
// so it's not available on mount anyway
// "return !!content" => always returns false
false,
);

// When content is become available for the first time (set in useEffect)
// we set this content to be shown!
useEffect(() => {
const contentBecameAvailable = content && !previousContent;
if (contentBecameAvailable) {
setShown(true);
}
}, [content, previousContent]);

const hasContent = !!content;

// On sidebar close, secondary menu is set to be shown on next re-opening
// (if any secondary menu content available)
useEffect(() => {
if (!hasContent) {
setShown(false);
return;
}
if (!sidebarShown) {
setShown(true);
}
}, [sidebarShown, hasContent]);

const hide = useCallback(() => {
setShown(false);
}, []);

return {shown, hide, content};
}