Skip to content

Commit

Permalink
feat: default matches browser language #285
Browse files Browse the repository at this point in the history
  • Loading branch information
shuashuai committed Jan 13, 2025
1 parent 43547ed commit a69b9cc
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 10 deletions.
3 changes: 0 additions & 3 deletions plugins/blog-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,6 @@ async function blogPluginExtended(...pluginArgs) {

const { createData, addRoute } = actions;

// console.log('blogPosts', blogPosts[0]);

const removeDraftPosts = allBlogPosts.filter((post) => !post.metadata.frontMatter?.draft);

// Fecommend posts list
Expand Down Expand Up @@ -264,7 +262,6 @@ async function blogPluginExtended(...pluginArgs) {
permalink: generateCategoryPath(category.label),
};

// console.log('categoryProp', categoryProp);
const categoryPropPath = await createData(
`${utils.docuHash(categoryProp.label)}.json`,
JSON.stringify(categoryProp, null, 2),
Expand Down
1 change: 0 additions & 1 deletion src/components/blog/BlogCategoryPostsPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ interface IProps extends Props {
}
const Index = (props: IProps) => {
const { category, categoriyList, items, listMetadata, } = props
// console.log('...props', props);
return (
<HtmlClassNameProvider
className={clsx(
Expand Down
1 change: 0 additions & 1 deletion src/components/blog/BlogDetailPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import BlogPostItem from '../BlogPostItem';
function BlogPostPageContent({relatedList, sidebar, children}) {
const {metadata, toc} = useBlogPost();

// console.log('BlogPostPageContent', toc);
const { frontMatter} = metadata;
const {
hide_table_of_contents: hideTableOfContents,
Expand Down
1 change: 0 additions & 1 deletion src/components/blog/BlogHome/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ interface HomeProps {
}

export function Home({ featuredPosts, categoyList, metadata, blogList }: HomeProps): JSX.Element {
// console.log('metadata', metadata);
return (
<HtmlClassNameProvider
className={clsx(
Expand Down
3 changes: 0 additions & 3 deletions src/theme/DocSidebarItem/Category/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ function CollapseButton({
categoryLabel: string;
onClick: ComponentProps<'button'>['onClick'];
}) {
// console.log('categoryLabel', categoryLabel);
return (
<button
aria-label={
Expand Down Expand Up @@ -157,8 +156,6 @@ export default function DocSidebarItemCategory({
}
}, [collapsible, expandedItem, index, setCollapsed, autoCollapseCategories]);

console.log('collapsed', item);

return (
<li
className={clsx(
Expand Down
57 changes: 57 additions & 0 deletions src/theme/Layout/BrowserLanguage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React, {useEffect} from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';

const LANGUAGE_PREFERENCE_KEY = '_lang_browser_';

export default function BrowserLanguageRedirect() {
const {
siteConfig: {
i18n: {defaultLocale, locales},
},
} = useDocusaurusContext();

useEffect(() => {
window.addEventListener('languagechange', () => {
localStorage.setItem(LANGUAGE_PREFERENCE_KEY, navigator.language);
})

const currentPath = window.location.pathname;
const storageLocale = localStorage.getItem('_lang_user_') || localStorage.getItem(LANGUAGE_PREFERENCE_KEY);
const storageLocaleIsDefault = storageLocale === defaultLocale;

if (storageLocale) {
if (storageLocaleIsDefault) {
if (currentPath === '/') return;
return;
} else {
if (currentPath.startsWith(`/${storageLocale}`)) {
return;
} else {
window.location.pathname = `/${storageLocale}${currentPath}`;
return;
}
}
} else {
const browserLanguage = navigator.language.toLowerCase();
const matchedLocale = locales.find(locale =>
browserLanguage === locale.toLowerCase() ||
browserLanguage.startsWith(locale.toLowerCase() + '-')
);
if (matchedLocale) {
localStorage.setItem(LANGUAGE_PREFERENCE_KEY, matchedLocale);
window.location.pathname = `/${matchedLocale}${currentPath}`;
} else {
window.location.pathname = currentPath;
}
}

// remove the event listener
return () => {
window.removeEventListener('languagechange', () => {
localStorage.setItem(LANGUAGE_PREFERENCE_KEY, navigator.language);
})
}
}, []);

return null;
}
3 changes: 2 additions & 1 deletion src/theme/Layout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import LayoutProvider from '@theme/Layout/Provider';
import ErrorPageContent from '@theme/ErrorPageContent';
import type {Props} from '@theme/Layout';
import mixpanel from 'mixpanel-browser';
import BrowserLanguage from './BrowserLanguage';

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

Expand All @@ -45,7 +46,6 @@ export default function Layout(props: Props): JSX.Element {
}, [])

useEffect(() => {
// console.log('Layout.tsx: location.pathname: ', location);
mixpanel.track_pageview();
}, [location]);

Expand All @@ -58,6 +58,7 @@ export default function Layout(props: Props): JSX.Element {
<AnnouncementBar />

<Navbar />
<BrowserLanguage />

<div
id={SkipToContentFallbackId}
Expand Down
8 changes: 8 additions & 0 deletions src/theme/NavbarItem/NavbarNavLink.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ export default function NavbarNavLink({
const normalizedHref = useBaseUrl(href, {forcePrependBaseUrl: true});
const isExternalLink = label && href && !isInternalUrl(href);

const clickLink = (e) => {
if (e.target?.lang) {
localStorage.setItem('_lang_user_', e.target.lang);
}
}

// Link content is set through html XOR label
const linkContentProps = html
? {dangerouslySetInnerHTML: {__html: html}}
Expand All @@ -62,6 +68,7 @@ export default function NavbarNavLink({
href={prependBaseUrlToHref ? normalizedHref : href}
{...props}
{...linkContentProps}
onClick={clickLink}
/>
);
}
Expand All @@ -78,6 +85,7 @@ export default function NavbarNavLink({
})}
{...props}
{...linkContentProps}
onClick={clickLink}
/>
);
}

0 comments on commit a69b9cc

Please sign in to comment.