Skip to content

Commit

Permalink
fix: Site link auto switch by locale (ant-design#42381)
Browse files Browse the repository at this point in the history
* Revert "Revert "docs: auto trans link" (ant-design#42373)"

This reverts commit fa90b25.

* docs: site update link auto switch logic
  • Loading branch information
zombieJ authored May 16, 2023
1 parent 78c8146 commit 3097ec3
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
6 changes: 5 additions & 1 deletion .dumi/rehypeAntd.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
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
Expand Down Expand Up @@ -60,6 +60,10 @@ function rehypeAntd(): UnifiedTransformer<HastRoot> {
if (!node.properties) return;
node.properties.className ??= [];
(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';
}
});
};
Expand Down
49 changes: 49 additions & 0 deletions .dumi/theme/builtins/LocaleLink/index.tsx
Original file line number Diff line number Diff line change
@@ -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 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"singleQuote": true,
"jsxSingleQuote": false,
"trailingComma": "all",
"printWidth": 100,
"proseWrap": "never",
Expand Down

0 comments on commit 3097ec3

Please sign in to comment.