Browse Source

fix: Site link auto switch by locale (#42381)

* Revert "Revert "docs: auto trans link" (#42373)"

This reverts commit fa90b25b3e.

* docs: site update link auto switch logic
pull/38174/head
二货爱吃白萝卜 2 years ago
committed by GitHub
parent
commit
3097ec39e1
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      .dumi/rehypeAntd.ts
  2. 49
      .dumi/theme/builtins/LocaleLink/index.tsx
  3. 1
      .prettierrc

6
.dumi/rehypeAntd.ts

@ -1,5 +1,5 @@
import assert from 'assert'; import assert from 'assert';
import { type HastRoot, type UnifiedTransformer, unistUtilVisit } from 'dumi'; import { unistUtilVisit, type HastRoot, type UnifiedTransformer } from 'dumi';
/** /**
* plugin for modify hast tree when docs compiling * plugin for modify hast tree when docs compiling
@ -60,6 +60,10 @@ function rehypeAntd(): UnifiedTransformer<HastRoot> {
if (!node.properties) return; if (!node.properties) return;
node.properties.className ??= []; node.properties.className ??= [];
(node.properties.className as string[]).push('component-api-table'); (node.properties.className as string[]).push('component-api-table');
} else if (node.type === 'element' && (node.tagName === 'Link' || node.tagName === 'a')) {
const { tagName } = node;
node.properties.sourceType = tagName;
node.tagName = 'LocaleLink';
} }
}); });
}; };

49
.dumi/theme/builtins/LocaleLink/index.tsx

@ -0,0 +1,49 @@
import { Link } from 'dumi';
import * as React from 'react';
import useLocale from '../../../hooks/useLocale';
type LinkProps = Parameters<typeof Link>[0];
export interface LocaleLinkProps extends LinkProps {
sourceType: 'a' | 'Link';
children?: React.ReactNode;
}
export default function LocaleLink({ sourceType, to, ...props }: LocaleLinkProps) {
const Component = sourceType === 'a' ? 'a' : Link;
const [, localeType] = useLocale();
const localeTo = React.useMemo(() => {
if (!to || typeof to !== 'string') {
return to;
}
// Auto locale switch
const cells = to.match(/(\/[^#]*)(#.*)?/);
if (cells) {
let path = cells[1].replace(/\/$/, '');
const hash = cells[2] || '';
if (localeType === 'cn' && !path.endsWith('-cn')) {
path = `${path}-cn`;
} else if (localeType === 'en' && path.endsWith('-cn')) {
path = path.replace(/-cn$/, '');
}
return `${path}${hash}`;
}
return to;
}, [to]);
const linkProps: LocaleLinkProps = {
...props,
} as LocaleLinkProps;
if (to) {
linkProps.to = localeTo;
}
return <Component {...linkProps} />;
}

1
.prettierrc

@ -1,5 +1,6 @@
{ {
"singleQuote": true, "singleQuote": true,
"jsxSingleQuote": false,
"trailingComma": "all", "trailingComma": "all",
"printWidth": 100, "printWidth": 100,
"proseWrap": "never", "proseWrap": "never",

Loading…
Cancel
Save