Skip to content

Commit

Permalink
[gem-book] Support empty file fallback
Browse files Browse the repository at this point in the history
Closed #149
  • Loading branch information
mantou132 committed Apr 21, 2024
1 parent 1b02da2 commit 7521aa9
Show file tree
Hide file tree
Showing 12 changed files with 95 additions and 7 deletions.
1 change: 1 addition & 0 deletions packages/duoyun-ui/docs/en/30-blog/200-crud.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Use pattern create CRUD app
2 changes: 2 additions & 0 deletions packages/duoyun-ui/docs/en/30-blog/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
isNav: true
reverse: true
1 change: 1 addition & 0 deletions packages/duoyun-ui/gem-book.cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"title": "DuoyunUI",
"icon": "../../logo.png",
"i18n": true,
"fallbackLanguage": "zh",
"sourceBranch": "docs",
"plugin": ["media", "api", "sandpack", "raw", "docsearch?local", "example"],
"debug": true
Expand Down
2 changes: 1 addition & 1 deletion packages/gem-book/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"/index.*"
],
"scripts": {
"schema": "npx ts-json-schema-generator -p src/common/config.ts -t CliConfig -o schema.json",
"schema": "npx ts-json-schema-generator@1.5 -p src/common/config.ts -t CliConfig -o schema.json",
"build:cli": "esbuild ./src/bin/index.ts --tsconfig=./tsconfig.cli.json --outdir=./bin --platform=node --sourcemap --bundle --external:anymatch --external:cheerio --external:chokidar --external:jimp --external:marked --external:yaml --external:front-matter --external:commander --external:webpack --external:ts-loader --external:typescript --external:webpack-dev-server --external:html-webpack-plugin --external:copy-webpack-plugin --external:workbox-webpack-plugin",
"start:cli": "yarn build:cli --watch",
"docs": "node ./bin docs",
Expand Down
8 changes: 8 additions & 0 deletions packages/gem-book/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@
"displayRank": {
"type": "boolean"
},
"fallbackLanguage": {
"enum": [
"zh",
"en",
""
],
"type": "string"
},
"footer": {
"type": "string"
},
Expand Down
20 changes: 18 additions & 2 deletions packages/gem-book/src/bin/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,12 @@ export async function build(dir: string, options: Required<CliUniqueConfig>, boo
const docsDir = path.resolve(dir);
// 开发模式时使用 docsDir 避免不必要的复制
const outputDir = build && output ? path.resolve(output) : docsDir;
const pluginRecord = getPluginRecord(plugin);
const pluginRecord = getPluginRecord(
plugin
// 自动加载
.concat(options.fallbackLanguage && 'trans-status')
.filter((e) => !!e),
);
const plugins = Object.values(pluginRecord);
const themePath = resolveTheme(theme);

Expand Down Expand Up @@ -168,13 +173,24 @@ export async function build(dir: string, options: Required<CliUniqueConfig>, boo
plugins: [
new HtmlWebpackPlugin({
title: bookConfig.title || 'GemBook App',
...(template ? { template: path.resolve(process.cwd(), template) } : undefined),
template: template ? path.resolve(process.cwd(), template) : undefined,
// Automatically copied to the output directory
favicon: !isRemoteIcon && icon,
meta: {
viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no',
},
}),
{
apply(compiler: Compiler) {
options.fallbackLanguage &&
compiler.hooks.compilation.tap('htmlWebpackInjectAttributesPlugin', (compilation) => {
HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tapAsync('MyPlugin', (data, cb) => {
data.html = data.html.replace('<html>', `<html lang="${options.fallbackLanguage}">`);
cb(null, data);
});
});
},
},
new DefinePlugin({
// 插件 query 参数传递
'import.meta.url': DefinePlugin.runtimeValue(({ module }) => {
Expand Down
1 change: 1 addition & 0 deletions packages/gem-book/src/bin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ let cliConfig: Required<CliUniqueConfig> = {
icon: '',
output: '',
i18n: false,
fallbackLanguage: '',
plugin: [],
ga: '',
template: '',
Expand Down
4 changes: 4 additions & 0 deletions packages/gem-book/src/common/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,14 @@ export type BookConfig = {
onlyFile?: boolean;
} & CommonConfig;

export type SupportLang = 'zh' | 'en';

export interface CliUniqueConfig {
icon?: string;
output?: string;
i18n?: boolean;
// packages/gem-book/src/element/helper/i18n.ts
fallbackLanguage?: SupportLang | '';
plugin?: string[];
ga?: string;
template?: string;
Expand Down
3 changes: 3 additions & 0 deletions packages/gem-book/src/element/elements/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { debounce } from '../../common/utils';
import { icons } from '../elements/icons';
import { getRanges, getParts, joinPath, getURL, escapeHTML, capitalize } from '../lib/utils';
import { parseMarkdown, unsafeRenderHTML } from '../lib/renderer';
import { originDocLang, selfI18n } from '../helper/i18n';

/**
* 获取资源的远端 GitHub raw 地址,如果使用 `DEV_MODE`,则返回本机服务的 URL
Expand Down Expand Up @@ -60,6 +61,8 @@ export class GemBookPluginElement<T = any> extends GemElement<T> {
static caches = new Map<typeof GemBookPluginElement, Map<string, any>>();
static theme = theme;
static icons = icons;
static selfI18n = selfI18n;
static originDocLang = originDocLang;
static mediaQuery = mediaQuery;
static locationStore = locationStore;
static config = new Proxy<Partial<BookConfig>>(
Expand Down
4 changes: 3 additions & 1 deletion packages/gem-book/src/element/helper/i18n.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { I18n } from '@mantou/gem/helper/i18n';

import { SupportLang } from '../../common/config';

const resources = {
en: {
editOnGithub: 'Edit this page on GitHub',
Expand All @@ -13,7 +15,7 @@ const resources = {
footer: '通过 $1<GemBook> 生成',
lastUpdated: '上次更新',
},
};
} satisfies Record<SupportLang, unknown>;

export const originDocLang = document.documentElement.lang;

Expand Down
14 changes: 11 additions & 3 deletions packages/gem-book/src/element/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,15 +143,23 @@ function getLinkRouters(links: NavItemWithLink[], title = '', lang: string, disp
links.forEach((item) => {
const { title: pageTitle, link, userFullPath, originLink, hash } = item;
const routeTitle = `${capitalize(pageTitle)}${pageTitle ? ' - ' : ''}${title}`;

const fetchContent = async (l: string) => await (await fetch(getURL(joinPath(l, originLink), hash))).text();
routes.push({
title: routeTitle,
pattern: link,
async getContent() {
await import('./elements/main');
const content = await (await fetch(getURL(joinPath(lang, originLink), hash))).text();
const fmAndH1Reg = /.*?# .*?(\n|$)+/s;
let content = await fetchContent(lang);
let useLang = lang;
if (originDocLang && !content.replace(fmAndH1Reg, '').trim()) {
content +=
`<gbp-trans-status></gbp-trans-status>` +
(await fetchContent(originDocLang)).replace(fmAndH1Reg, '').trimStart();
useLang = originDocLang;
}
if (bookStore.isDevMode?.()) await new Promise((res) => setTimeout(res, 500));
return html`<gem-book-main role="article" .content=${content}></gem-book-main>`;
return html`<gem-book-main lang=${useLang} role="article" .content=${content}></gem-book-main>`;
},
data: item,
});
Expand Down
42 changes: 42 additions & 0 deletions packages/gem-book/src/plugins/trans-status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { SupportLang } from '../common/config';
import type { GemBookElement } from '../element';

type Status = 'none' | 'partial';

const locales: Record<string, Record<Status, string>> = {
en: {
none: 'This document has not been translated',
partial: 'This document is not translated',
},
zh: {
none: '该文档还未翻译',
partial: '该文档部分未翻译',
},
} satisfies Record<SupportLang, unknown>;

customElements.whenDefined('gem-book').then(({ GemBookPluginElement }: typeof GemBookElement) => {
const { Gem, Utils, selfI18n } = GemBookPluginElement;
const { html, customElement, attribute } = Gem;

@customElement('gbp-trans-status')
class _GbpTransStatusElement extends GemBookPluginElement {
@attribute status: Status;

get #status() {
return this.status || 'none';
}

constructor() {
super({ isLight: true });
}

render() {
const langPkg = locales[GemBookPluginElement.lang || selfI18n.fallbackLanguage];
return html`${Utils.parseMarkdown(
`> [!WARNING]
> ${langPkg[this.#status]}
`,
)}`;
}
}
});

0 comments on commit 7521aa9

Please sign in to comment.