Skip to content

Commit

Permalink
fix: code block demos conflict in different locale (#1796)
Browse files Browse the repository at this point in the history
* fix: code block demos conflict in different locale

* test: update transformer test case
  • Loading branch information
PeachScript authored Jul 30, 2023
1 parent 8b8ca50 commit 72780d6
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 23 deletions.
1 change: 1 addition & 0 deletions src/features/compile/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export default (api: IApi) => {
extraRemarkPlugins: api.config.extraRemarkPlugins,
extraRehypePlugins: api.config.extraRehypePlugins,
routes: api.appData.routes,
locales: api.config.locales,
pkg: api.pkg,
};

Expand Down
10 changes: 9 additions & 1 deletion src/loaders/markdown/transformer/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,15 @@ for (let casePath of cases) {
techStacks: [new FakeTechStack()],
cwd: path.dirname(fileAbsPath),
fileAbsPath: fileAbsPath,
resolve: { codeBlockMode: 'active', atomDirs: [], docDirs: [] },
resolve: {
codeBlockMode: 'active',
atomDirs: [],
docDirs: [],
forceKebabCaseRouting: true,
},
locales: [],
routes: {},
pkg: {},
alias: {
'@': __dirname,
},
Expand Down
15 changes: 14 additions & 1 deletion src/loaders/markdown/transformer/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { IParsedBlockAsset } from '@/assetParsers/block';
import type { IRouteMeta } from '@/client/theme-api/types';
import type { ILocalesConfig, IRouteMeta } from '@/client/theme-api/types';
import { VERSION_2_DEPRECATE_SOFT_BREAKS } from '@/constants';
import type { IApi, IDumiConfig, IDumiTechStack } from '@/types';
import enhancedResolve from 'enhanced-resolve';
Expand Down Expand Up @@ -66,6 +66,7 @@ export interface IMdTransformerOptions {
extraRemarkPlugins?: IDumiConfig['extraRemarkPlugins'];
extraRehypePlugins?: IDumiConfig['extraRehypePlugins'];
routes: Record<string, IRoute>;
locales: ILocalesConfig;
pkg: IApi['pkg'];
}

Expand Down Expand Up @@ -103,6 +104,7 @@ function applyUnifiedPlugin(opts: {
}

export default async (raw: string, opts: IMdTransformerOptions) => {
let fileLocaleLessPath = opts.fileAbsPath;
const { unified } = await import('unified');
const { default: remarkParse } = await import('remark-parse');
const { default: remarkFrontmatter } = await import('remark-frontmatter');
Expand All @@ -119,6 +121,14 @@ export default async (raw: string, opts: IMdTransformerOptions) => {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
alias: opts.alias,
});
const fileLocale = opts.locales.find((locale) =>
opts.fileAbsPath.endsWith(`.${locale.id}.md`),
)?.id;

// generate locale-less file abs path, for generate code id and atom id
if (fileLocale) {
fileLocaleLessPath = opts.fileAbsPath.replace(`.${fileLocale}.md`, '.md');
}

const processor = unified()
.use(remarkParse)
Expand All @@ -127,6 +137,7 @@ export default async (raw: string, opts: IMdTransformerOptions) => {
.use(remarkMeta, {
cwd: opts.cwd,
fileAbsPath: opts.fileAbsPath,
fileLocaleLessPath,
resolve: opts.resolve,
})
.use(remarkDirective)
Expand Down Expand Up @@ -160,6 +171,8 @@ export default async (raw: string, opts: IMdTransformerOptions) => {
techStacks: opts.techStacks,
cwd: opts.cwd,
fileAbsPath: opts.fileAbsPath,
fileLocaleLessPath,
fileLocale,
resolve: opts.resolve,
resolver,
})
Expand Down
26 changes: 18 additions & 8 deletions src/loaders/markdown/transformer/rehypeDemo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import parseBlockAsset from '@/assetParsers/block';
import type { IDumiDemoProps } from '@/client/theme-api/DumiDemo';
import { getRoutePathFromFsPath } from '@/utils';
import { getTabKeyFromFile, isTabRouteFile } from '@/features/tabs';
import { getFileIdFromFsPath } from '@/utils';
import type { sync } from 'enhanced-resolve';
import type { Element, Root } from 'hast';
import path from 'path';
Expand Down Expand Up @@ -30,7 +31,11 @@ export const DUMI_DEMO_GRID_TAG = 'DumiDemoGrid';
type IRehypeDemoOptions = Pick<
IMdTransformerOptions,
'techStacks' | 'cwd' | 'fileAbsPath' | 'resolve'
> & { resolver: typeof sync };
> & {
resolver: typeof sync;
fileLocaleLessPath: string;
fileLocale?: string;
};

/**
* get language for code element
Expand Down Expand Up @@ -71,9 +76,7 @@ function getCodeId(
atomId?: string,
) {
// Foo, or docs-guide, or docs-guide-faq
const prefix =
atomId ||
getRoutePathFromFsPath(path.relative(cwd, fileAbsPath)).replace(/\//g, '-');
const prefix = atomId || getFileIdFromFsPath(path.relative(cwd, fileAbsPath));

return [prefix.toLowerCase(), 'demo', localId.toLowerCase()]
.filter(Boolean)
Expand Down Expand Up @@ -269,7 +272,7 @@ export default function rehypeDemo(

parseOpts.id = getCodeId(
opts.cwd,
opts.fileAbsPath,
opts.fileLocaleLessPath,
localId,
vFile.data.frontmatter!.atomId,
);
Expand All @@ -283,13 +286,20 @@ export default function rehypeDemo(
path.relative(opts.cwd, parseOpts.fileAbsPath),
);
} else {
const tabKey = isTabRouteFile(opts.fileAbsPath)
? getTabKeyFromFile(opts.fileAbsPath)
: '';
const localId = [tabKey, opts.fileLocale, String(index++)]
.filter(Boolean)
.join('-');

// pass a fake entry point for code block demo
// and pass the real code via `entryPointCode` option
parseOpts.fileAbsPath = opts.fileAbsPath.replace('.md', '.tsx');
parseOpts.id = getCodeId(
opts.cwd,
opts.fileAbsPath,
String(index++),
opts.fileLocaleLessPath,
localId,
vFile.data.frontmatter!.atomId,
);
component = techStack.transformCode(codeValue, {
Expand Down
17 changes: 9 additions & 8 deletions src/loaders/markdown/transformer/remarkMeta.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { getTabKeyFromFile, isTabRouteFile } from '@/features/tabs';
import {
getHostForTabRouteFile,
getTabKeyFromFile,
isTabRouteFile,
} from '@/features/tabs';
import fs from 'fs';
import yaml from 'js-yaml';
import type { Root } from 'mdast';
Expand All @@ -21,12 +25,9 @@ let toString: typeof import('mdast-util-to-string').toString;
* guess atom id from filename
*/
function getGuessAtomId(opts: IRemarkMetaOpts) {
const parsed = path.parse(opts.fileAbsPath);
// strip modifier from markdown filename, such as $tab-xx, zh-CN & etc.
const clearFileName = parsed.name.replace(
/(?:\.$tab-[^.]+)?(?:\.[^.]+)?(\.[^.]+)$/,
'$1',
);
const parsed = path.parse(opts.fileLocaleLessPath);
// strip modifier from markdown filename, such as $tab-xx
const clearFileName = getHostForTabRouteFile(parsed.name);
// find same name component file
const atomFile = ['.tsx', '.jsx']
.map((ext) => path.join(parsed.dir, `${clearFileName}${ext}`))
Expand All @@ -52,7 +53,7 @@ function getGuessAtomId(opts: IRemarkMetaOpts) {
type IRemarkMetaOpts = Pick<
IMdTransformerOptions,
'cwd' | 'fileAbsPath' | 'resolve'
>;
> & { fileLocaleLessPath: string };

export default function remarkMeta(opts: IRemarkMetaOpts): Transformer<Root> {
return (tree, vFile) => {
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ interface IDumiExtendsConfig {
extraRemarkPlugins?: (string | Function | [string | Function, object])[];
extraRehypePlugins?: (string | Function | [string | Function, object])[];
}
export type IDumiConfig = IUmiConfig & IDumiExtendsConfig;
export type IDumiConfig = Omit<IUmiConfig, 'locales'> & IDumiExtendsConfig;

export type IDumiUserConfig = Subset<Omit<IDumiConfig, 'locales'>> & {
locales?:
Expand Down
6 changes: 2 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@ import { lodash, logger, winPath } from 'umi/plugin-utils';
/**
* get route path from file-system path
*/
export function getRoutePathFromFsPath(fsPath: string) {
return lodash.kebabCase(
winPath(fsPath).replace(/((\/|^)index(\.[a-zA-Z-]+)?)?\.\w+$/g, ''),
);
export function getFileIdFromFsPath(fsPath: string) {
return lodash.kebabCase(winPath(fsPath).replace(/((\/|^)index)?\.\w+$/g, ''));
}

/**
Expand Down

0 comments on commit 72780d6

Please sign in to comment.