导航中没有语言切换菜单 修改布局后更新 #3

Merged
honeymoose merged 2 commits from docs_init into main 2026-12-01 19:57:14 -05:00
270 changed files with 50460 additions and 37 deletions
+122 -33
View File
@@ -1,22 +1,53 @@
import fs from 'node:fs';
import { defineConfig, type DefaultTheme } from 'vitepress';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig, type DefaultTheme, type LocaleConfig } from 'vitepress';
// Sidebar of the official documentation, written by scripts/import-typescript-website.mjs.
const docsSidebar: DefaultTheme.SidebarItem[] = JSON.parse(
fs.readFileSync(new URL('../scripts/nav.json', import.meta.url), 'utf8'));
// Same layout as Angular-iSharkFly-Com: Simplified Chinese at the site root, English under /en/.
const EN_PREFIX = '/en';
const siteDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'site');
function enLink(link: string) {
return link.startsWith('/') ? EN_PREFIX + link : link;
}
function mapSidebarLinks(items: DefaultTheme.SidebarItem[], mapLink: (link: string) => string): DefaultTheme.SidebarItem[] {
return items.map(item => ({
...item,
...(item.items ? { items: mapSidebarLinks(item.items, mapLink) } : {}),
...(item.link ? { link: mapLink(item.link) } : {}),
}));
}
// Pages that exist on the English site (relative to site/en/). The language switcher links to
// the same page in the other language when it is listed here, otherwise to that language's home.
function listPages(dir: string, rel = ''): string[] {
if (!fs.existsSync(dir))
return [];
return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
const entryRel = rel + entry.name;
if (entry.isDirectory())
return listPages(path.join(dir, entry.name), `${entryRel}/`);
return entry.name.endsWith('.md') ? [entryRel] : [];
});
}
const UPSTREAM_REPO_URL = 'https://github.com/microsoft/TypeScript-website';
const FORUM_URL = 'https://www.isharkfly.com/';
const REPO_URL = 'https://src.sharkdat.com/iSharkFly-Docs/TypeScript-iSharkFly-Com';
// iSharkFly links shown as a dropdown at the end of the nav bar.
function isharkflyNav(): DefaultTheme.NavItem {
function isharkflyNav(zh: boolean): DefaultTheme.NavItem {
return {
text: 'iSharkFly',
items: [
{ text: 'iSharkFly', link: FORUM_URL },
{ text: '文档导航', link: 'https://docs.isharkfly.com/' },
{ text: '本站源码', link: REPO_URL },
{ text: zh ? '文档导航' : 'Docs Portal', link: 'https://docs.isharkfly.com/' },
{ text: zh ? '本站源码' : 'Source Code', link: REPO_URL },
],
};
}
@@ -38,6 +69,28 @@ const guideSidebar: DefaultTheme.SidebarItem[] = [
},
];
const zhThemeText: DefaultTheme.Config = {
outline: { level: [2, 3], label: '本页目录' },
docFooter: { prev: '上一页', next: '下一页' },
darkModeSwitchLabel: '外观',
lightModeSwitchTitle: '切换到浅色模式',
darkModeSwitchTitle: '切换到深色模式',
sidebarMenuLabel: '菜单',
returnToTopLabel: '回到顶部',
langMenuLabel: '切换语言',
skipToContentLabel: '跳到正文',
notFound: {
title: '页面未找到',
quote: '你要找的页面不存在,或者已经被移动。',
linkLabel: '返回首页',
linkText: '返回首页',
},
footer: {
message: '本书采用「保持署名—非商用」创意共享 4.0 许可证。',
copyright: 'Copyright © iSharkFly',
},
};
const zhSearchText = {
button: { buttonText: '搜索', buttonAriaLabel: '搜索' },
modal: {
@@ -57,6 +110,49 @@ const zhSearchText = {
},
};
const locales: LocaleConfig<DefaultTheme.Config> = {
root: {
label: '简体中文',
lang: 'zh-CN',
link: '/',
title: 'TypeScript',
description: 'TypeScript 文档手册',
themeConfig: {
...zhThemeText,
nav: [
{ text: '官方文档', link: '/docs/handbook/intro', activeMatch: '^/docs/' },
{ text: '简介', link: '/overview/', activeMatch: '^/overview/' },
{ text: '关于', link: '/about', activeMatch: '^/(about|contact)' },
isharkflyNav(true),
],
sidebar: {
'/docs/': docsSidebar,
'/': guideSidebar,
},
},
},
en: {
label: 'English',
lang: 'en-US',
link: `${EN_PREFIX}/`,
title: 'TypeScript',
description: 'TypeScript documentation',
themeConfig: {
nav: [
{ text: 'Docs', link: enLink('/docs/handbook/intro'), activeMatch: `^${EN_PREFIX}/docs/` },
isharkflyNav(false),
],
sidebar: {
[`${EN_PREFIX}/docs/`]: mapSidebarLinks(docsSidebar, enLink),
},
footer: {
message: 'Licensed under CC BY-NC 4.0.',
copyright: 'Copyright © iSharkFly',
},
},
},
};
export default defineConfig({
srcDir: 'site',
lang: 'zh-CN',
@@ -94,45 +190,38 @@ export default defineConfig({
defaultText(tokens, idx, options, env, self).replace(/\{\{/g, '&#123;&#123;').replace(/\}\}/g, '&#125;&#125;');
},
},
locales,
themeConfig: {
logo: 'https://www.typescriptlang.org/favicon-32x32.png',
nav: [
{ text: '官方文档', link: '/docs/handbook/intro', activeMatch: '^/docs/' },
{ text: '简介', link: '/overview/', activeMatch: '^/overview/' },
{ text: '关于', link: '/about', activeMatch: '^/(about|contact)' },
isharkflyNav(),
],
sidebar: {
'/docs/': docsSidebar,
'/': guideSidebar,
},
search: {
provider: 'local',
options: { translations: zhSearchText },
},
outline: { level: [2, 3], label: '本页目录' },
docFooter: { prev: '上一页', next: '下一页' },
darkModeSwitchLabel: '外观',
lightModeSwitchTitle: '切换到浅色模式',
darkModeSwitchTitle: '切换到深色模式',
sidebarMenuLabel: '菜单',
returnToTopLabel: '回到顶部',
skipToContentLabel: '跳到正文',
notFound: {
title: '页面未找到',
quote: '你要找的页面不存在,或者已经被移动。',
linkLabel: '返回首页',
linkText: '返回首页',
options: {
locales: { root: { translations: zhSearchText } },
},
},
outline: { level: [2, 3] },
socialLinks: [
{ icon: 'github', link: UPSTREAM_REPO_URL },
],
footer: {
message: '本书采用「保持署名—非商用」创意共享 4.0 许可证。',
copyright: 'Copyright © iSharkFly',
languageSwitcher: {
enPrefix: EN_PREFIX,
pages: { root: listPages(path.join(siteDir, 'en')) },
},
},
} as DefaultTheme.Config,
vite: {
build: { chunkSizeWarningLimit: 4096 },
resolve: {
// Replace VitePress's locale menu with the reading-language switcher (as in Angular-iSharkFly-Com).
alias: [
{
find: /^.*\/VPNavBarTranslations\.vue$/,
replacement: fileURLToPath(new URL('./theme/components/NavBarLanguageSwitcher.vue', import.meta.url)),
},
{
find: /^.*\/VPNavScreenTranslations\.vue$/,
replacement: fileURLToPath(new URL('./theme/components/NavScreenLanguageSwitcher.vue', import.meta.url)),
},
],
},
},
});
@@ -0,0 +1,71 @@
<script setup lang="ts">
import VPFlyout from 'vitepress/dist/client/theme-default/components/VPFlyout.vue';
import { VPLink } from 'vitepress/theme';
import { useLanguageSwitcher } from '../languageSwitcher';
const { readingLanguages, labels } = useLanguageSwitcher();
</script>
<template>
<VPFlyout class="NavBarLanguageSwitcher" icon="vpi-languages" :label="labels.menu">
<div class="items">
<p class="title">{{ labels.reading }}</p>
<VPLink
v-for="item in readingLanguages"
:key="item.text"
class="link"
:class="{ active: item.active }"
:href="item.link"
:lang="item.lang"
:hreflang="item.lang"
rel="alternate"
>{{ item.text }}</VPLink>
</div>
</VPFlyout>
</template>
<style scoped>
.NavBarLanguageSwitcher {
display: none;
}
@media (min-width: 1280px) {
.NavBarLanguageSwitcher {
display: flex;
align-items: center;
}
}
.items {
min-width: 180px;
}
.title {
padding: 0 12px;
line-height: 32px;
font-size: 12px;
font-weight: 600;
color: var(--vp-c-text-2);
}
.link {
display: block;
border-radius: 6px;
padding: 0 12px;
line-height: 32px;
font-size: 14px;
font-weight: 500;
color: var(--vp-c-text-1);
white-space: nowrap;
transition: background-color 0.25s, color 0.25s;
}
.link:hover {
color: var(--vp-c-brand-1);
background-color: var(--vp-c-default-soft);
}
.link.active {
color: var(--vp-c-brand-1);
}
</style>
@@ -0,0 +1,85 @@
<script setup lang="ts">
import { ref } from 'vue';
import { VPLink } from 'vitepress/theme';
import { useLanguageSwitcher } from '../languageSwitcher';
const { readingLanguages, labels, currentLabel } = useLanguageSwitcher();
const isOpen = ref(false);
</script>
<template>
<div class="NavScreenLanguageSwitcher" :class="{ open: isOpen }">
<button class="toggle" :aria-expanded="isOpen" @click="isOpen = !isOpen">
<span class="vpi-languages icon lang" />
{{ currentLabel }}
<span class="vpi-chevron-down icon chevron" />
</button>
<div class="groups">
<p class="title">{{ labels.reading }}</p>
<ul class="list">
<li v-for="item in readingLanguages" :key="item.text">
<VPLink class="link" :class="{ active: item.active }" :href="item.link" :lang="item.lang">
{{ item.text }}
</VPLink>
</li>
</ul>
</div>
</div>
</template>
<style scoped>
.NavScreenLanguageSwitcher {
height: 24px;
overflow: hidden;
}
.NavScreenLanguageSwitcher.open {
height: auto;
}
.toggle {
display: flex;
align-items: center;
font-size: 14px;
font-weight: 500;
color: var(--vp-c-text-1);
}
.icon {
font-size: 16px;
}
.icon.lang {
margin-right: 8px;
}
.icon.chevron {
margin-left: 4px;
}
.groups {
padding: 4px 0 0 24px;
}
.title {
margin-top: 8px;
font-size: 12px;
font-weight: 600;
color: var(--vp-c-text-2);
}
.list {
padding-left: 8px;
}
.link {
line-height: 32px;
font-size: 13px;
color: var(--vp-c-text-1);
}
.link.active {
color: var(--vp-c-brand-1);
}
</style>
@@ -0,0 +1,35 @@
<script setup lang="ts">
import { computed } from 'vue';
import { useData } from 'vitepress';
const { frontmatter, page } = useData();
const englishLink = computed(() =>
'/en/' + page.value.relativePath.replace(/(^|\/)index\.md$/, '$1').replace(/\.md$/, ''));
</script>
<template>
<div v-if="frontmatter.untranslated" class="untranslated-notice" lang="zh-CN">
本页尚未翻译成中文,以下为英文原文。
<a :href="englishLink">查看英文版</a>
</div>
</template>
<style scoped>
.untranslated-notice {
margin: 0 0 24px;
border: 1px solid var(--vp-custom-block-info-border);
border-radius: 8px;
padding: 12px 16px;
font-size: 14px;
line-height: 24px;
color: var(--vp-custom-block-info-text);
background-color: var(--vp-custom-block-info-bg);
}
.untranslated-notice a {
font-weight: 500;
color: var(--vp-c-brand-1);
text-decoration: underline;
text-underline-offset: 2px;
}
</style>
+5
View File
@@ -1,7 +1,12 @@
import { h } from 'vue';
import DefaultTheme from 'vitepress/theme';
import type { Theme } from 'vitepress';
import UntranslatedNotice from './components/UntranslatedNotice.vue';
import './custom.css';
export default {
extends: DefaultTheme,
Layout: () => h(DefaultTheme.Layout, null, {
'doc-before': () => h(UntranslatedNotice),
}),
} satisfies Theme;
+58
View File
@@ -0,0 +1,58 @@
import { computed } from 'vue';
import { useData } from 'vitepress';
type SwitcherConfig = {
enPrefix: string;
pages: Record<string, string[]>;
};
export type SwitcherLink = { text: string; link: string; lang?: string; active: boolean };
const READING_LANGUAGES = [
{ key: 'zh', text: '简体中文', lang: 'zh-CN' },
{ key: 'en', text: 'English', lang: 'en-US' },
] as const;
function pageUrl(base: string, page: string) {
return base + page.replace(/(^|\/)index\.md$/, '$1').replace(/\.md$/, '');
}
export function useLanguageSwitcher() {
const { page, theme, hash } = useData();
const config = computed(() => theme.value.languageSwitcher as SwitcherConfig);
const current = computed(() => {
let rest = page.value.relativePath;
const enDir = config.value.enPrefix.replace(/^\//, '') + '/';
const reading = rest.startsWith(enDir) ? 'en' : 'zh';
if (reading === 'en')
rest = rest.slice(enDir.length);
return { reading, page: rest };
});
function linkFor(reading: string, keepHash: boolean) {
const base = reading === 'en' ? config.value.enPrefix + '/' : '/';
const pages = config.value.pages['root'] ?? [];
if (!pages.includes(current.value.page))
return base;
return pageUrl(base, current.value.page) + (keepHash ? hash.value : '');
}
const isZh = computed(() => current.value.reading === 'zh');
const readingLanguages = computed<SwitcherLink[]>(() => READING_LANGUAGES.map(reading => ({
text: reading.text,
lang: reading.lang,
link: linkFor(reading.key, true),
active: reading.key === current.value.reading,
})));
const labels = computed(() => isZh.value
? { menu: '切换语言', reading: '阅读语言' }
: { menu: 'Change language', reading: 'Language' });
const currentLabel = computed(() =>
READING_LANGUAGES.find(reading => reading.key === current.value.reading)!.text);
return { readingLanguages, labels, currentLabel, isZh };
}
+26 -4
View File
@@ -1,5 +1,6 @@
// Imports the official TypeScript documentation from a checkout of
// https://github.com/microsoft/TypeScript-website into site/docs/, converting
// https://github.com/microsoft/TypeScript-website into site/docs/ (Chinese site, marked
// untranslated) and site/en/docs/ (English site), converting
// typescriptlang.org-specific Markdown (twoslash code samples, site links) to VitePress Markdown.
// The English text is copied as is (no translation).
//
@@ -18,6 +19,7 @@ import { fileURLToPath } from 'node:url';
const SITE_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT_DIR = path.join(SITE_DIR, 'site', 'docs');
const EN_OUT_DIR = path.join(SITE_DIR, 'site', 'en', 'docs');
const ASSET_DIR = path.join(SITE_DIR, 'site', 'public', 'docs', '_assets');
const NAV_FILE =path.join(SITE_DIR, 'scripts', 'nav.json');
const UPSTREAM_FILE = path.join(SITE_DIR, 'scripts', 'upstream.json');
@@ -202,6 +204,22 @@ function convertPage(page) {
return `${fm.join('\n')}\n${head}${body.replace(/^\n+/, '')}`;
}
// Same idea as Angular-iSharkFly-Com's scripts/sync-zh.mjs: Simplified Chinese is served from
// the site root, English from /en/. There are no translations yet, so the Chinese pages carry
// `untranslated: true` (see .vitepress/theme/components/UntranslatedNotice.vue).
function markUntranslated(text) {
return text.replace(/^---\n/, '---\nuntranslated: true\n');
}
function moveLinksUnderEnglish(text) {
return text.replace(/(\]\(|\bhref=["'])\/docs\/(?!_assets\/)/g, '$1/en/docs/');
}
function write(file, text) {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, text);
}
// ---------------------------------------------------------------------------
// Navigation parsing (a tolerant reader for the object literal in the nav script)
// ---------------------------------------------------------------------------
@@ -315,10 +333,14 @@ function main() {
fs.rmSync(OUT_DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
fs.rmSync(ASSET_DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
fs.rmSync(EN_OUT_DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
for (const page of pages.values()) {
const out = path.join(OUT_DIR, ...page.route.replace(/^\/docs\//, '').split('/')) + '.md';
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, convertPage(page));
const rel = page.route.replace(/^\/docs\//, '').split('/');
const text = convertPage(page);
// Chinese site (root): the English text, flagged so the page shows the "untranslated" notice.
write(path.join(OUT_DIR, ...rel) + '.md', markUntranslated(text));
// English site (/en/): same text, with page links kept under /en/.
write(path.join(EN_OUT_DIR, ...rel) + '.md', moveLinksUnderEnglish(text));
}
for (const [source, rel] of copiedAssets) {
const out = path.join(ASSET_DIR, ...rel.split('/'));
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "The Basics"
description: "Step one in learning TypeScript: The basic types."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Basics.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Classes"
description: "How classes work in TypeScript"
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Classes.md"
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Conditional Types"
description: "Create types which act like if statements in the type system."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Conditional Types.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Everyday Types"
description: "The language primitives."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Everyday Types.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "More on Functions"
description: "Learn about how Functions work in TypeScript."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/More on Functions.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Generics"
description: "Types which take parameters"
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Generics.md"
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Indexed Access Types"
description: "Using Type['a'] syntax to access a subset of a type."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Indexed Access Types.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Keyof Type Operator"
description: "Using the keyof operator in type contexts."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Keyof Type Operator.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Mapped Types"
description: "Generating types by re-using an existing type."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Mapped Types.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Modules"
description: "How JavaScript handles communicating across file boundaries."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Modules.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Narrowing"
description: "Understand how TypeScript uses JavaScript knowledge to reduce the amount of type syntax in your projects."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Narrowing.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Object Types"
description: "How TypeScript describes the shapes of JavaScript objects."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Object Types.md"
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Template Literal Types"
description: "Generating mapping types which change properties via template literal strings."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Template Literal Types.md"
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Type Declarations"
description: "How TypeScript provides types for un-typed JavaScript."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Declarations.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Typeof Type Operator"
description: "Using the typeof operator in type contexts."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/Typeof Type Operator.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Creating Types from Types"
description: "An overview of the ways in which you can create more types from existing types."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Type Manipulation/_Creating Types from Types.md"
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Understanding Errors"
description: "How to read TypeScript errors."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v2/Understanding Errors.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Advanced Types"
description: "Advanced concepts around types in TypeScript"
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/reference/Advanced Types.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Angular"
description: "Using Angular with TypeScript"
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/tutorials/Angular.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "ASP.NET Core"
description: "Using TypeScript in ASP.NET Core"
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/tutorials/ASP.NET Core.md"
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Using Babel with TypeScript"
description: "How to create a hybrid Babel + TypeScript project"
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/tutorials/Babel with TypeScript.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Basic Types"
description: "Step two in learning TypeScript: The basic types."
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v1/Basic Types.md"
+1
View File
@@ -1,4 +1,5 @@
---
untranslated: true
title: "Classes"
description: "How classes work in TypeScript"
upstream: "https://github.com/microsoft/TypeScript-website/blob/v2/packages/documentation/copy/en/handbook-v1/Classes.md"

Some files were not shown because too many files have changed in this diff Show More