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

fix: ui switch query #634

Merged
merged 1 commit into from
Feb 18, 2024
Merged
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
2 changes: 1 addition & 1 deletion .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"access": "restricted",
"baseBranch": "main",
"fixed": [
["@rspress/*", "rspress", "create-rspress", "@modern-js/plugin-rspress", "@rspress-fixture/*"]
["@rspress/*", "rspress", "create-rspress", "@modern-js/plugin-rspress"]
],
"___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": {
"onlyUpdatePeerDependentsWhenOutOfRange": true,
Expand Down
6 changes: 6 additions & 0 deletions .changeset/spotty-needles-clap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@rspress/theme-default": patch
"@rspress/docs": patch
---

fix: ui switch query
7 changes: 4 additions & 3 deletions packages/document/rspress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,10 @@ export default defineConfig({
{
tag: 'meta',
attrs: {
content: 'https://github.com/web-infra-dev/rspress/assets/39261479/999e7946-45ff-45d5-b9cd-594e634e0e5a',
property: "og:image",
}
content:
'https://github.com/web-infra-dev/rspress/assets/39261479/999e7946-45ff-45d5-b9cd-594e634e0e5a',
property: 'og:image',
},
},
{
tag: 'script',
Expand Down
4 changes: 4 additions & 0 deletions packages/theme-default/src/components/LocalSideBar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import ArrowRight from '../../assets/arrow-right.svg';
import { SideBar } from '../Sidebar';
import './index.scss';
import { Toc } from '../Toc';
import { UISwitchResult } from '#theme/logic/useUISwitch';

export function SideMenu({
beforeSidebar,
afterSidebar,
uiSwitch,
}: {
beforeSidebar?: React.ReactNode;
afterSidebar?: React.ReactNode;
uiSwitch?: UISwitchResult;
}) {
const [isSidebarOpen, setSidebarIsOpen] = useState<boolean>(false);
const [isTocOpen, setIsTocOpen] = useState<boolean>(false);
Expand Down Expand Up @@ -81,6 +84,7 @@ export function SideMenu({
isSidebarOpen={isSidebarOpen}
beforeSidebar={beforeSidebar}
afterSidebar={afterSidebar}
uiSwitch={uiSwitch}
/>
{isSidebarOpen ? (
<div
Expand Down
14 changes: 5 additions & 9 deletions packages/theme-default/src/components/Sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@ import {
} from '@rspress/shared';
import { routes } from 'virtual-routes';
import { matchRoutes, useLocation, removeBase } from '@rspress/runtime';
import {
isActive,
useDisableNav,
useLocaleSiteData,
useSidebarData,
} from '../../logic';
import { isActive, useLocaleSiteData, useSidebarData } from '../../logic';
import { NavBarTitle } from '../Nav/NavBarTitle';
import styles from './index.module.scss';
import { SidebarItem } from './SidebarItem';
import { SidebarDivider } from './SidebarDivider';
import { UISwitchResult } from '#theme/logic/useUISwitch';

export interface SidebarItemProps {
id: string;
Expand All @@ -36,6 +32,7 @@ interface Props {
isSidebarOpen?: boolean;
beforeSidebar?: React.ReactNode;
afterSidebar?: React.ReactNode;
uiSwitch?: UISwitchResult;
}

export const highlightTitleStyle = {
Expand All @@ -52,13 +49,12 @@ export let matchCache: WeakMap<
> = new WeakMap();

export function SideBar(props: Props) {
const { isSidebarOpen, beforeSidebar, afterSidebar } = props;
const { isSidebarOpen, beforeSidebar, afterSidebar, uiSwitch } = props;
const { items: rawSidebarData } = useSidebarData();
const localesData = useLocaleSiteData();
const { pathname: rawPathname } = useLocation();

const langRoutePrefix = normalizeSlash(localesData.langRoutePrefix || '');
const [hideNavbar] = useDisableNav();
const [sidebarData, setSidebarData] = useState<
(ISidebarDivider | ISidebarItem | NormalizedSidebarGroup)[]
>(rawSidebarData.filter(Boolean).flat());
Expand Down Expand Up @@ -131,7 +127,7 @@ export function SideBar(props: Props) {
isSidebarOpen ? styles.open : ''
}`}
>
{hideNavbar ? null : (
{!uiSwitch.showNavbar ? null : (
<div className={styles.navTitleMask}>
<NavBarTitle />
</div>
Expand Down
69 changes: 22 additions & 47 deletions packages/theme-default/src/layout/DocLayout/index.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { useEffect, useState } from 'react';
import { useState } from 'react';
import { MDXProvider } from '@mdx-js/react';
import { getCustomMDXComponent } from '@theme';
import { Content, useLocation, usePageData, NoSSR } from '@rspress/runtime';
import { Content, usePageData, NoSSR } from '@rspress/runtime';
import { Aside } from '../../components/Aside';
import { DocFooter } from '../../components/DocFooter';
import { useDisableNav, useLocaleSiteData } from '../../logic';
import { useLocaleSiteData } from '../../logic';
import { SideMenu } from '../../components/LocalSideBar';
import { Overview } from '../../components/Overview';
import { TabDataContext } from '../../logic/TabDataContext';
import { QueryStatus } from '../Layout';
import ScrollToTop from '../../components/ScrollToTop/index';
import styles from './index.module.scss';
import { UISwitchResult } from '#theme/logic/useUISwitch';

export interface DocLayoutProps {
beforeSidebar?: React.ReactNode;
Expand All @@ -20,6 +20,7 @@ export interface DocLayoutProps {
afterDoc?: React.ReactNode;
beforeOutline?: React.ReactNode;
afterOutline?: React.ReactNode;
uiSwitch?: UISwitchResult;
}

export function DocLayout(props: DocLayoutProps) {
Expand All @@ -31,51 +32,19 @@ export function DocLayout(props: DocLayoutProps) {
afterOutline,
beforeSidebar,
afterSidebar,
uiSwitch,
} = props;
const { siteData, page } = usePageData();
const { toc = [], frontmatter } = page;
const [tabData, setTabData] = useState({});
const headers = toc;
const { themeConfig } = siteData;
const localesData = useLocaleSiteData();
const sidebar = localesData.sidebar || {};
const [disableNavbar] = useDisableNav();
const enableScrollToTop = themeConfig.enableScrollToTop ?? false;
// siderbar Priority
// 1. frontmatter.sidebar
// 2. themeConfig.locales.sidebar
// 3. themeConfig.sidebar
const hasSidebar =
frontmatter?.sidebar !== false && Object.keys(sidebar).length > 0;
const localesData = useLocaleSiteData();

const outlineTitle =
localesData?.outlineTitle || themeConfig?.outlineTitle || 'ON THIS PAGE';
const isOverviewPage = frontmatter?.overview ?? false;
const [hasFooter, setHasFooter] = useState(frontmatter?.footer ?? true);
const location = useLocation();

const getHasAside = () => {
// if in iframe, default value is false
const defaultHasAside =
typeof window === 'undefined' ? true : window.top === window.self;
return (
(frontmatter?.outline ?? themeConfig?.outline ?? defaultHasAside) &&
!isOverviewPage
);
};
const [hasAside, setHasAside] = useState(getHasAside());

useEffect(() => {
setHasAside(getHasAside());
}, [page, siteData]);

useEffect(() => {
const query = new URLSearchParams(location.search);
const footer = query.get('footer');
if (footer === QueryStatus.Hide) {
setHasFooter(false);
}
}, []);

const docContent = (
<TabDataContext.Provider value={{ tabData, setTabData }}>
Expand All @@ -85,16 +54,22 @@ export function DocLayout(props: DocLayoutProps) {
</TabDataContext.Provider>
);

console.log('uiSwitch', uiSwitch);

return (
<div
className={`${styles.docLayout} pt-0`}
style={{
...(disableNavbar ? { marginTop: 0 } : {}),
...(uiSwitch.showNavbar ? {} : { marginTop: 0 }),
}}
>
{beforeDoc}
{hasSidebar ? (
<SideMenu beforeSidebar={beforeSidebar} afterSidebar={afterSidebar} />
{uiSwitch.showSidebar ? (
<SideMenu
beforeSidebar={beforeSidebar}
afterSidebar={afterSidebar}
uiSwitch={uiSwitch}
/>
) : null}
<div
className={`${styles.content} rspress-doc-container flex flex-shrink-0 mx-auto`}
Expand All @@ -107,7 +82,7 @@ export function DocLayout(props: DocLayoutProps) {
<div className="rspress-doc">{docContent}</div>
<div className="rspress-doc-footer">
{beforeDocFooter}
{hasFooter && <DocFooter />}
{uiSwitch.showDocFooter && <DocFooter />}
</div>
</div>
)}
Expand All @@ -117,16 +92,16 @@ export function DocLayout(props: DocLayoutProps) {
<ScrollToTop />
</NoSSR>
)}
{hasAside ? (
{uiSwitch.showAside ? (
<div
className={styles.asideContainer}
style={{
...(disableNavbar
? {
...(uiSwitch.showNavbar
? {}
: {
marginTop: 0,
paddingTop: '32px',
}
: {}),
}),
}}
>
<div>
Expand Down
81 changes: 11 additions & 70 deletions packages/theme-default/src/layout/Layout/index.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import 'nprogress/nprogress.css';
import '../../styles';
import React, { useEffect } from 'react';
import React from 'react';
import { Helmet } from 'react-helmet-async';
import Theme, { Nav } from '@theme';
import { usePageData, Content, removeBase, withBase } from '@rspress/runtime';
import { usePageData, Content } from '@rspress/runtime';
import { DocLayout, DocLayoutProps } from '../DocLayout';
import { HomeLayoutProps } from '../HomeLayout';
import type { NavProps } from '../../components/Nav';
import { useDisableNav, useLocaleSiteData } from '#theme/logic';

export enum QueryStatus {
Show = '1',
Hide = '0',
}
import { useLocaleSiteData } from '#theme/logic';
import { useRedirect4FirstVisit } from '#theme/logic/useRedirect4FirstVisit';
import { useUISwitch } from '#theme/logic/useUISwitch';

export type LayoutProps = {
top?: React.ReactNode;
Expand Down Expand Up @@ -65,14 +62,11 @@ export const Layout: React.FC<LayoutProps> = props => {
frontmatter,
} = page;
const localesData = useLocaleSiteData();
const defaultLang = siteData.lang || '';
const [hideNavbar, setHideNavbar] = useDisableNav();
useRedirect4FirstVisit();
// Always show sidebar by default
// Priority: front matter title > h1 title
let title = (frontmatter?.title as string) ?? articleTitle;
const mainTitle = siteData.title || localesData.title;
const localeLanguages = Object.values(siteData.themeConfig.locales || {});
const langs = localeLanguages.map(item => item.lang) || [];

if (title && pageType === 'doc') {
// append main title as a suffix
Expand All @@ -84,13 +78,16 @@ export const Layout: React.FC<LayoutProps> = props => {
(frontmatter?.description as string) ||
siteData.description ||
localesData.description;
// Control whether to show navbar/sidebar/outline/footer
const uiSwitch = useUISwitch();
console.log('uiSwitch', uiSwitch);
// Use doc layout by default
const getContentLayout = () => {
switch (pageType) {
case 'home':
return <Theme.HomeLayout {...homeProps} />;
case 'doc':
return <DocLayout {...docProps} />;
return <DocLayout {...docProps} uiSwitch={uiSwitch} />;
case '404':
return <Theme.NotFoundLayout />;
// The custom pageType will have navbar while the blank pageType will not.
Expand All @@ -102,62 +99,6 @@ export const Layout: React.FC<LayoutProps> = props => {
}
};

useEffect(() => {
if (!defaultLang || process.env.TEST === '1') {
// Check the window.navigator.language to determine the default language
// If the default language is not the same as the current language, redirect to the default language
// The default language will not have a lang prefix in the URL
return;
}
// Normalize current url, to ensure that the home url is always with a trailing slash
const { pathname } = window.location;
const cleanPathname = removeBase(pathname);
// Check if the user is visiting the site for the first time
const FIRST_VISIT_KEY = 'rspress-visited';
const visited = localStorage.getItem(FIRST_VISIT_KEY);
if (visited) {
return;
} else {
localStorage.setItem(FIRST_VISIT_KEY, '1');
}
const targetLang = window.navigator.language.split('-')[0];
if (!langs.includes(targetLang)) {
return;
}
if (targetLang !== currentLang) {
if (targetLang === defaultLang) {
// Redirect to the default language
window.location.replace(pathname.replace(`/${currentLang}`, ''));
} else if (currentLang === defaultLang) {
// Redirect to the current language
window.location.replace(withBase(`/${targetLang}${cleanPathname}`));
} else {
// Redirect to the current language
window.location.replace(
pathname.replace(`/${currentLang}`, `/${targetLang}`),
);
}
}
}, []);

// Control the display of the navbar, sidebar and aside
useEffect(() => {
const query = new URLSearchParams(location.search);
const navbar = query.get('navbar');
const sidebar = query.get('sidebar');
const aside = query.get('outline');
if (navbar === QueryStatus.Hide) {
setHideNavbar(true);
}

if (sidebar === QueryStatus.Hide) {
document.documentElement.style.setProperty('--rp-sidebar-width', '0');
}

if (aside === QueryStatus.Hide) {
document.documentElement.style.setProperty('--rp-aside-width', '0');
}
}, []);
return (
<div>
<Helmet
Expand All @@ -170,7 +111,7 @@ export const Layout: React.FC<LayoutProps> = props => {
</Helmet>
{top}

{pageType !== 'blank' && !hideNavbar && (
{pageType !== 'blank' && uiSwitch.showNavbar && (
<Nav
beforeNavTitle={beforeNavTitle}
afterNavTitle={afterNavTitle}
Expand Down
3 changes: 2 additions & 1 deletion packages/theme-default/src/logic/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
export { usePrevNextPage } from './usePrevNextPage';
export { useEditLink } from './useEditLink';
export { useSidebarData } from './useSidebarData';
export { useHiddenNav, useDisableNav } from './useHiddenNav';
export { useHiddenNav, useEnableNav } from './useHiddenNav';
export { useLocaleSiteData } from './useLocaleSiteData';
export { setup, bindingAsideScroll, scrollToTarget } from './sideEffects';
export { usePathUtils } from './usePathUtils';
export { useFullTextSearch } from './useFullTextSearch';
export { useRedirect4FirstVisit } from './useRedirect4FirstVisit';
export * from './utils';
Loading
Loading