Skip to content

Commit

Permalink
fix(antdsite): fix incorrect path when base is set.
Browse files Browse the repository at this point in the history
  • Loading branch information
wangyi7099 committed Aug 9, 2019
1 parent d73b2ac commit e85e09a
Show file tree
Hide file tree
Showing 19 changed files with 110 additions and 74 deletions.
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
"publish": "lerna publish --conventional-commits",
"build": "yarn build:docs",
"build:docs": "yarn workspace docs build",
"start": "yarn workspace docs start",
"build-with-prefix": "cross-env base=/antdsite yarn build",
"cl": "conventional-changelog -p angular -i CHANGELOG.md -s"
},
"workspaces": [
Expand All @@ -15,6 +17,7 @@
],
"devDependencies": {
"lerna": "^3.11.1",
"conventional-changelog-cli": "2.0.23"
"conventional-changelog-cli": "2.0.23",
"cross-env": "5.2.0"
}
}
1 change: 1 addition & 0 deletions packages/antdsite/gatsby-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ function getPlugin(pluginName) {
}

module.exports = {
pathPrefix: finalConfig.base,
plugins: [
{
resolve: 'gatsby-mdx-fix',
Expand Down
11 changes: 5 additions & 6 deletions packages/antdsite/lib/gatsby/createPages.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ const path = require('path');
function isHome(frontmatter, slug) {
return (
frontmatter.home === true &&
((themeConfig.locales && Object.keys(themeConfig.locales).indexOf(slug) !== -1) ||
slug === webConfig.base)
((themeConfig.locales && Object.keys(themeConfig.locales).indexOf(slug) !== -1) || slug === '/')
);
}

Expand All @@ -34,7 +33,7 @@ module.exports = async ({ graphql, actions }) => {
createRedirect({
fromPath: '/index.html',
redirectInBrowser: true,
toPath: '/',
toPath: webConfig.base
});

const allMdx = await graphql(
Expand Down Expand Up @@ -89,8 +88,8 @@ module.exports = async ({ graphql, actions }) => {
isWebsiteHome,
webConfig,
slug,
maxTocDeep: frontmatter.maxTocDeep || webConfig.themeConfig.maxTocDeep,
},
maxTocDeep: frontmatter.maxTocDeep || webConfig.themeConfig.maxTocDeep
}
});
};

Expand All @@ -102,7 +101,7 @@ module.exports = async ({ graphql, actions }) => {
return createRedirect({
fromPath: path,
redirectInBrowser: true,
toPath: redirects[path],
toPath: redirects[path]
});
});
};
18 changes: 7 additions & 11 deletions packages/antdsite/lib/gatsby/onCreateNode.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const path = require('path');
const fs = require('fs');
const fetch = require('node-fetch');
const himalaya = require('himalaya');
var { themeConfig, base } = require('../util').getFinalConfig();
var { themeConfig } = require('../util').getFinalConfig();

// // 获取用户的头像列表
const getAvatarList = async filename => {
Expand All @@ -15,7 +15,7 @@ const getAvatarList = async filename => {
}/`;
const url = `${sourcePath}${filename}/list`;
const html = await fetch(url, {
timeout: 10000,
timeout: 10000
}).then(res => res.text(), () => null);
if (!html) return [];

Expand All @@ -31,7 +31,7 @@ const getAvatarList = async filename => {
return {
href,
text,
src,
src
};
}
return null;
Expand All @@ -40,10 +40,6 @@ const getAvatarList = async filename => {
return data;
};

function withBase(_path) {
return (base + _path).replace(/\/\//g, '/');
}

function normalizeSlug(slug) {
if (!slug.startsWith('/')) {
slug = '/' + slug;
Expand All @@ -68,29 +64,29 @@ module.exports = exports.onCreateNode = async ({ node, actions, getNode }) => {
createNodeField({
node,
name: `modifiedTime`,
value: mtime,
value: mtime
});

slug = normalizeSlug(`${relativePath.replace(/(readme)?\.mdx?/i, '')}`);

createNodeField({
node,
name: 'slug',
value: withBase(slug),
value: slug
});

createNodeField({
node,
name: 'path',
value: mdFilePath,
value: mdFilePath
});

if (themeConfig.showAvatarList) {
const html = await getAvatarList(mdFilePath);
createNodeField({
node,
name: 'avatarList',
value: html,
value: html
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import GitHubButton from 'react-github-button-fix-iebug';
import { Button } from 'antd';
import { Link } from 'gatsby';
import { PageContext } from 'antdsite';
import * as utils from '../utils';

function Banner(props) {
return (
Expand All @@ -19,7 +20,13 @@ function Banner(props) {
<div className="banner-wrapper">
{(frontmatter.heroImage || currentLocaleWebConfig.logo) && (
<div className="banner-logo">
<img src={frontmatter.heroImage || currentLocaleWebConfig.logo} alt="Hero" />
<img
src={utils.withBasePath(
frontmatter.heroImage || currentLocaleWebConfig.logo,
currentLocaleWebConfig.base
)}
alt="Hero"
/>
</div>
)}
<div className="banner-title-wrapper">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export default class LeftMenu extends React.PureComponent<MenuPros, MenuState> {
const menuChild = (
<Menu
ref="menu"
inlineIndent={16}
inlineIndent={40}
className="aside-container"
mode="inline"
openKeys={openKeys}
Expand Down
56 changes: 30 additions & 26 deletions packages/antdsite/src/default-theme/components/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,12 @@ import { IAllMdxData, Edges, IGraphqlFrontmatterData, Toc, PageEdge } from '../.

export function getCurrentLoacle(webConfig: any, slug: string) {
const locales = webConfig.themeConfig.locales;
const base = webConfig.base;

function nomalizeSlug(_path: string) {
return (base + _path).replace(/\/\//g, '/');
}

if (!locales) return false;

let targetLocale = '/';

for (let path in locales) {
if (path != targetLocale && slug.startsWith(nomalizeSlug(path))) {
if (path != targetLocale && slug.startsWith(path)) {
targetLocale = path;
}
}
Expand All @@ -32,7 +26,7 @@ export function getcurrentLocaleConfigBySlug(
if (!targetLocale) {
return {
localte: '/',
currentLocaleWebConfig: webConfig,
currentLocaleWebConfig: webConfig
};
}

Expand All @@ -43,9 +37,9 @@ export function getcurrentLocaleConfigBySlug(
...webConfig.locales[targetLocale],
themeConfig: {
...webConfig.themeConfig,
...webConfig.themeConfig.locales[targetLocale],
},
},
...webConfig.themeConfig.locales[targetLocale]
}
}
};
}

Expand Down Expand Up @@ -98,29 +92,41 @@ export function resolvePage(pages: Edges, rawPath: string, base: string): PageIn
if (normalize(node.fields.slug) === path) {
return Object.assign(
{
children: [],
children: []
},
node.frontmatter,
{
title: getPageTitle(node),
title: getPageTitle(node)
},
node.fields,
{ toc: node.tableOfContents }
);
}
}

console.error(`[Gatsby-Theme-AntdSite] No matching page found for sidebar item "${rawPath}"`);
console.error(`[AntdSite] No matching page found for sidebar item "${rawPath}"`);
return {
children: [],
title: rawPath,
slug: rawPath,
toc: {
items: [],
},
items: []
}
};
}

export function withBasePath(path: string, base: string) {
if (!base.endsWith('/')) {
base += '/';
}

if (path.startsWith('/')) {
path = path.slice(1);
}

return base + path;
}

function resolvePath(relative: string, base: string, append: string = '') {
const firstChar = relative.charAt(0);
if (firstChar === '/') {
Expand Down Expand Up @@ -163,6 +169,7 @@ export function resolvePathWithBase(path: string, base: string) {
if (base.endsWith('/')) {
base = base.slice(0, base.length - 1);
}

if (!path.startsWith('/')) {
path = '/' + path;
}
Expand All @@ -177,10 +184,8 @@ export interface PageInfo extends IGraphqlFrontmatterData {
toc?: Toc;
}

function resolvePageSidebar(config: any, path: string, base: string, edges: Edges): PageInfo[] {
return config
? config.map((item: any) => resolveItem(item, edges, resolvePathWithBase(path, base), 1))
: [];
function resolvePageSidebar(config: any, path: string, edges: Edges): PageInfo[] {
return config ? config.map((item: any) => resolveItem(item, edges, path, 1)) : [];
}

export function resolveSidebarItems(
Expand All @@ -196,19 +201,18 @@ export function resolveSidebarItems(
const { currentLocaleWebConfig } = getcurrentLocaleConfigBySlug(webConfig, currentSlug);

const pageSidebarConfig = currentLocaleWebConfig.themeConfig.sidebar;
const { base } = currentLocaleWebConfig;

let currentPageSidebarItems: PageInfo[] = [];
let allPagesSidebarItems: PageInfo[] = [];

if (!pageSidebarConfig) {
return {
currentPageSidebarItems,
allPagesSidebarItems,
allPagesSidebarItems
};
} else {
allPagesSidebarItems = Object.keys(pageSidebarConfig).reduce((pre, cur) => {
const resolvedConfig = resolvePageSidebar(pageSidebarConfig[cur], cur, base, edges);
const resolvedConfig = resolvePageSidebar(pageSidebarConfig[cur], cur, edges);

if (currentSlug.startsWith(cur)) {
currentPageSidebarItems = resolvedConfig;
Expand All @@ -219,7 +223,7 @@ export function resolveSidebarItems(

return {
currentPageSidebarItems,
allPagesSidebarItems,
allPagesSidebarItems
};
}
}
Expand All @@ -229,7 +233,7 @@ function resolveItem(item: any, pages: Edges, base: string, nestedLevel: number)
return resolvePage(pages, item, base);
} else if (Array.isArray(item)) {
return Object.assign(resolvePage(pages, item[0], base), {
title: item[1],
title: item[1]
});
} else {
if (nestedLevel > 2) {
Expand All @@ -242,7 +246,7 @@ function resolveItem(item: any, pages: Edges, base: string, nestedLevel: number)
return {
title: item.title,
children: children.map((child: any) => resolveItem(child, pages, base, nestedLevel + 1)),
collapsable: item.collapsable !== false,
collapsable: item.collapsable !== false
};
}
}
14 changes: 7 additions & 7 deletions packages/antdsite/src/default-theme/layout/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class Header extends React.Component<HeaderProps, HeaderState> {
state: HeaderState = {
inputValue: undefined,
menuVisible: false,
menuMode: 'horizontal',
menuMode: 'horizontal'
};

static contextType = PageContext;
Expand Down Expand Up @@ -49,13 +49,13 @@ class Header extends React.Component<HeaderProps, HeaderState> {

handleShowMenu = () => {
this.setState({
menuVisible: true,
menuVisible: true
});
};

onMenuVisibleChange = (visible: boolean) => {
this.setState({
menuVisible: visible,
menuVisible: visible
});
};

Expand Down Expand Up @@ -94,7 +94,7 @@ class Header extends React.Component<HeaderProps, HeaderState> {
const { webConfig, slug, allPagesSidebarItems } = this.context;
let currentLocate = utils.getCurrentLoacle(webConfig, slug);
let {
currentLocaleWebConfig: { themeConfig, title, base, logo },
currentLocaleWebConfig: { themeConfig, title, base, logo }
} = utils.getcurrentLocaleConfigBySlug(webConfig, slug);
const { locales } = webConfig.themeConfig;

Expand All @@ -109,7 +109,7 @@ class Header extends React.Component<HeaderProps, HeaderState> {
{nav.map((item: any, index: number) => {
return this.renderNav(item, index);
})}
</Menu>,
</Menu>
];

const chooseLanguage = currentLocate ? (
Expand Down Expand Up @@ -144,8 +144,8 @@ class Header extends React.Component<HeaderProps, HeaderState> {
) : null}
<Row>
<Col xxl={4} xl={5} lg={8} md={8} sm={24} xs={24}>
<Link id="site-logo" to={utils.resolvePathWithBase(currentLocate || '/', base)}>
{logo && <img src={logo} alt={title} />}
<Link id="site-logo" to={currentLocate || base}>
{logo && <img src={utils.withBasePath(logo, base)} alt={title + '-logo'} />}
<span className="left-top-title">{title}</span>
</Link>
</Col>
Expand Down
2 changes: 1 addition & 1 deletion packages/antdsite/src/templates/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export default function Template(props: {
const { body } = props.data.mdx.code;

return (
<MDXProvider components={{ ...antd }}>
<MDXProvider components={{ ...antd, ...{ PageCustomer: PageContext.Consumer } }}>
<PageContext.Provider
value={{
...pageContext,
Expand Down
Loading

0 comments on commit e85e09a

Please sign in to comment.