Skip to content

Commit

Permalink
[gem-book] Fixed init locationStore.path
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed Jan 7, 2024
1 parent 4dfdacf commit ef5d774
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 45 deletions.
2 changes: 1 addition & 1 deletion packages/gem-book/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "gem-book",
"version": "1.5.30",
"version": "1.5.31",
"description": "Create your document website easily and quickly",
"keywords": [
"doc",
Expand Down
10 changes: 8 additions & 2 deletions packages/gem-book/src/element/elements/nav.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ import {
connectStore,
boolattribute,
classMap,
history,
} from '@mantou/gem';
import { mediaQuery } from '@mantou/gem/helper/mediaquery';

import { NavItem } from '../../common/config';
import { theme } from '../helper/theme';
import { capitalize, isSameOrigin } from '../lib/utils';
import { bookStore } from '../store';
import { bookStore, updateBookConfig } from '../store';

import { icons } from './icons';
import { sidebarStore, updateSidebarStore } from './sidebar';
Expand All @@ -34,7 +35,12 @@ import './nav-logo';
export class Nav extends GemElement {
@boolattribute logo: boolean;

@globalemitter languagechange = (v: string) => bookStore.languagechangeHandle?.(v);
@globalemitter languagechange = (lang: string) => {
const { path, query, hash } = history.getParams();
history.basePath = `/${lang}`;
history.replace({ path, query, hash });
updateBookConfig(bookStore.config);
};

@refobject i18nRef: RefObject<HTMLSelectElement>;

Expand Down
12 changes: 6 additions & 6 deletions packages/gem-book/src/element/helper/i18n.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { I18n } from '@mantou/gem/helper/i18n';

export const Resources = {
const resources = {
en: {
editOnGithub: 'Edit this page on GitHub',
createOnGithub: 'Create on GitHub',
Expand All @@ -15,9 +15,9 @@ export const Resources = {
},
};

export const selfI18n = new I18n<typeof Resources.en>({
fallbackLanguage: 'en',
resources: Resources,
// 默认是自动识别,如果不是多语言版本使用 `--template` 模版指定语言
currentLanguage: document.documentElement.lang,
export const fallbackLanguage = document.documentElement.lang;

export const selfI18n = new I18n<typeof resources.en>({
fallbackLanguage: fallbackLanguage in resources ? fallbackLanguage : 'en',
resources,
});
39 changes: 15 additions & 24 deletions packages/gem-book/src/element/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { I18n } from '@mantou/gem/helper/i18n';

import { BookConfig, NavItem } from '../common/config';

import { selfI18n } from './helper/i18n';
import { fallbackLanguage, selfI18n } from './helper/i18n';
import { getLinkPath, getUserLink, NavItemWithLink, flatNav, capitalize, getURL } from './lib/utils';
import { getRenderer } from './lib/renderer';

Expand All @@ -19,7 +19,6 @@ interface CurrentBookConfig {

lang: string;
langList: { code: string; name: string }[];
languagechangeHandle: (_: string) => void;
currentSidebar: NavItemWithLink[];
// 当没有提供 readme 或者 index 时,homePage 是第一个有效页面
homePage: string;
Expand All @@ -34,36 +33,29 @@ function getI18nSidebar(config: BookConfig = {}) {
let sidebar: NavItem[] = [];
let lang = '';
let langList: { code: string; name: string }[] = [];
let languagechangeHandle = (_lang: string) => {
//
};

const sidebarConfig = config.sidebar || [];
if (sidebarConfig instanceof Array) {
sidebar = sidebarConfig;
} else {
langList = Object.keys(sidebarConfig).map((code) => ({ code, name: sidebarConfig[code].name }));
const fallbackLanguage = langList[0].code;
// detect language
const i18n = new I18n<any>({ fallbackLanguage, resources: sidebarConfig, cache: true, urlParamsType: 'path' });
lang = i18n.currentLanguage;
const { currentLanguage } = new I18n<any>({
fallbackLanguage: fallbackLanguage in sidebarConfig ? fallbackLanguage : langList[0]?.code,
resources: sidebarConfig,
cache: true,
urlParamsType: 'path',
});
lang = currentLanguage;
history.basePath = `/${lang}`;
sidebar = sidebarConfig[lang].data;
languagechangeHandle = async (lang: string) => {
const { path, query, hash } = history.getParams();
// will modify `history.getParams()`
history.basePath = `/${lang}`;
await i18n.setLanguage(lang);
// Use custom anchors id to ensure that the hash is correct after i18n switching
history.replace({ path, query, hash });
updateBookConfig(bookStore.config);
};
// 初始页面需要立即更新才能读取到
locationStore.path = history.getParams().path;
if (lang !== selfI18n.currentLanguage) {
selfI18n.setLanguage(lang);
}
}

if (lang) {
selfI18n.setLanguage(lang in selfI18n.resources ? lang : selfI18n.fallbackLanguage);
}
return { sidebar, lang, langList, languagechangeHandle };
return { sidebar, lang, langList };
}

function processSidebar(sidebar: NavItem[], displayRank: boolean | undefined) {
Expand Down Expand Up @@ -242,7 +234,7 @@ function getHomePage(links: RouteItem[]) {
}

export function updateBookConfig(config?: BookConfig, gemBookElement?: GemBookElement) {
const { sidebar, lang, langList, languagechangeHandle } = getI18nSidebar(config);
const { sidebar, lang, langList } = getI18nSidebar(config);
const sidebarResult = processSidebar(sidebar, config?.displayRank);
const links = flatNav(sidebarResult);
const nav = getNav(sidebarResult, config?.nav || []);
Expand All @@ -263,7 +255,6 @@ export function updateBookConfig(config?: BookConfig, gemBookElement?: GemBookEl
routes,
lang,
langList,
languagechangeHandle,
homePage,
currentSidebar,
currentLinks,
Expand Down
8 changes: 4 additions & 4 deletions packages/gem/docs/en/001-guide/002-advance/005-i18n.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ html`${i18n.get('detail', (s) => html`<a href="#">${s}</a>`)}`;

Some multi-language front-end projects may need SEO support, so you need to specify different language versions in the URL. `urlParamsType` allows `I18n` to check the URL when instantiating, and supports multiple types:

- path: root path, for example `/zh/home`
- querystring: located in URL querystring, the name is specified with `urlParamsName`
- ccTLD: Subdomain, such as `jp.mywebsite.com`
- gTLD: Top-level domain name, such as `mywebsite.jp`
- `path`: root path, for example `/zh/home`
- `querystring`: located in URL query string, the name is specified with `urlParamsName`
- `ccTLD`: Subdomain, such as `jp.website.com`
- `gTLD`: Top-level domain name, such as `website.jp`

```js
const i18n = new I18n({
Expand Down
15 changes: 8 additions & 7 deletions packages/gem/docs/zh/001-guide/002-advance/005-i18n.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,12 +99,12 @@ html`${i18n.get('detail', (s) => html`<a href="#">${s}</a>`)}`;

## URL 中指定语言

一些多语言前端项目希望是 SEO 友好的,所以需要在 URL 中指定不同的语言版本,`urlParamsType` 可以让 `I18n` 在实例化时检查 URL,并且支持多种类型
一般会为不同的语言生成唯一的 URL,因为这样能让搜索引擎进行准确的索引。`I18n` 在实例化时根据 `urlParamsType` 检查 URL,它支持

- path:根路径,例如 `/zh/home`
- querystring:位于 URL querystring,名称使用 `urlParamsName` 指定
- ccTLD:子域名,例如 `jp.mywebsite.com`
- gTLD:顶级域名,例如 `mywebsite.jp`
- `path`:根路径,例如 `/zh/home`
- `querystring`:查询字符串,名称使用 `urlParamsName` 指定
- `ccTLD`:子域名,例如 `jp.website.com`
- `gTLD`:顶级域名,例如 `website.jp`

```js
const i18n = new I18n({
Expand All @@ -119,8 +119,9 @@ const i18n = new I18n({
```

> [!TIP]
> `urlParamsType``path`,那么页面中的链接、[`history`](../../003-api/004-history.md) 路由切换都需要修改,
> 可以通过设置 `history.basePath` 来全局定义此操作:
> `urlParamsType``path` 或者 `querystring`
> 页面中的链接、[`history`](../../003-api/004-history.md) 路由切换都需要修改。
> 例如,`urlParamsType``path` 时可以通过设置 `history.basePath` 来全局定义此操作:
>
> ```js
> new I18n({
Expand Down
2 changes: 1 addition & 1 deletion packages/gem/src/helper/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ export class I18n<T = Record<string, Msg>> implements RouteTrigger {
pack = data;
}
this.resources[lang] = pack;
updateStore(this.store, {});
updateStore(this.store);
if (lang !== this.currentLanguage) {
this.#lang = lang;
}
Expand Down

0 comments on commit ef5d774

Please sign in to comment.