Skip to content

Commit

Permalink
[docs] Fix /api client-side routing (#23586)
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed Nov 18, 2020
1 parent 6859c13 commit 75dc225
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 61 deletions.
5 changes: 1 addition & 4 deletions docs/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,6 @@ module.exports = {
},
reactStrictMode: reactMode === 'legacy-strict',
async rewrites() {
return [
{ source: `/:lang(${LANGUAGES.join('|')})?/:rest*`, destination: '/:rest*' },
{ source: '/api/:rest*', destination: '/api-docs/:rest*' },
];
return [{ source: `/:lang(${LANGUAGES.join('|')})?/:rest*`, destination: '/:rest*' }];
},
};
59 changes: 28 additions & 31 deletions docs/scripts/i18n.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable no-console */
import path from 'path';
import fse from 'fs-extra';
import { pageToTitle } from 'docs/src/modules/utils/helpers';
Expand All @@ -7,39 +6,37 @@ import pages from 'docs/src/pages';
const EXCLUDES = ['/api', '/blog'];

async function run() {
try {
const translationsFilename = path.join(__dirname, '../translations/translations.json');
const translationsFile = await fse.readFile(translationsFilename, 'utf8');
const output = JSON.parse(translationsFile);
output.pages = {};

const traverse = (pages2) => {
pages2.forEach((page) => {
if (
(page.pathname !== '/' && page.pathname === '/api-docs') ||
!EXCLUDES.some((exclude) => page.pathname.includes(exclude))
) {
const title = pageToTitle(page);

if (title) {
const pathname = page.subheader || page.pathname;
output.pages[pathname] = title;
}
const translationsFilename = path.join(__dirname, '../translations/translations.json');
const translationsFile = await fse.readFile(translationsFilename, 'utf8');
const output = JSON.parse(translationsFile);
output.pages = {};

const traverse = (pages2) => {
pages2.forEach((page) => {
if (
(page.pathname !== '/' && page.pathname === '/api-docs') ||
!EXCLUDES.some((exclude) => page.pathname.includes(exclude))
) {
const title = pageToTitle(page);

if (title) {
const pathname = page.subheader || page.pathname;
output.pages[pathname] = title;
}
}

if (page.children) {
traverse(page.children);
}
});
};
if (page.children) {
traverse(page.children);
}
});
};

traverse(pages);
traverse(pages);

await fse.writeFile(translationsFilename, `${JSON.stringify(output, null, 2)}\n`);
} catch (err) {
console.log(err);
throw err;
}
await fse.writeFile(translationsFilename, `${JSON.stringify(output, null, 2)}\n`);
}

run();
run().catch((error) => {
console.error(error);
process.exit(1);
});
8 changes: 7 additions & 1 deletion docs/src/modules/components/AppDrawer.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,13 @@ function renderNavItems(options) {
);
}

function reduceChildRoutes({ onClose, activePage, items, page, depth, t }) {
/**
* @param {object} context
* @param {import('docs/src/pages').MuiPage} context.page
*/
function reduceChildRoutes(context) {
const { onClose, activePage, items, depth, t } = context;
let { page } = context;
if (page.displayNav === false) {
return items;
}
Expand Down
23 changes: 16 additions & 7 deletions docs/src/modules/components/Link.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,24 @@ function Link(props) {
const {
activeClassName = 'active',
className: classNameProps,
href: routerHref,
href,
innerRef,
naked,
role: roleProp,
as: asProp = href,
...other
} = props;

// apply nextjs rewrites
const href = routerHref.replace(/\/api-docs\/(.*)/, '/api/$1');

const router = useRouter();

const userLanguage = useUserLanguage();
const className = clsx(classNameProps, {
[activeClassName]: router.pathname === routerHref && activeClassName,
[activeClassName]: router.pathname === href && activeClassName,
});

let linkAs = asProp;
if (userLanguage !== 'en' && href.indexOf('/') === 0 && href.indexOf('/blog') !== 0) {
other.as = `/${userLanguage}${href}`;
linkAs = `/${userLanguage}${linkAs}`;
}

// catch role passed from ButtonBase. This is definitely a link
Expand All @@ -63,11 +62,21 @@ function Link(props) {
}

if (naked) {
return <NextComposed className={className} href={href} ref={innerRef} role={role} {...other} />;
return (
<NextComposed
as={linkAs}
className={className}
href={href}
ref={innerRef}
role={role}
{...other}
/>
);
}

return (
<MuiLink
as={linkAs}
component={NextComposed}
className={className}
href={href}
Expand Down
13 changes: 4 additions & 9 deletions docs/src/modules/components/PageContext.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import * as React from 'react';

// The default value is never and should never be used.
// It's here to improve DX by enabling autocompletion for editors supporting TypeScript.
const PageContext = React.createContext({
activePage: {
pathname: '',
},
pages: [],
versions: [],
});
/**
* @type {React.Context<{ activePage: { pathname: string }, pages: Array<import('docs/src/pages').MuiPage>, versions: unknown[] }>}
*/
const PageContext = React.createContext();

if (process.env.NODE_ENV !== 'production') {
PageContext.displayName = 'PageContext';
Expand Down
18 changes: 15 additions & 3 deletions docs/src/modules/utils/find.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,21 @@ function findComponents(directory, components = []) {
const jsRegex = /\.js$/;
const blackList = ['/.eslintrc', '/_document', '/_app'];

// Returns the Next.js pages available in a nested format.
// The output is in the next.js format.
// Each pathname is a route you can navigate to.
/**
* @typedef {object} NextJSPage
* @property {string} pathname
* @property {NextJSPage[]} [children]
*/

/**
* Returns the Next.js pages available in a nested format.
* The output is in the next.js format.
* Each pathname is a route you can navigate to.
* @param {{ front: true }} [options]
* @param {string} [directory]
* @param {NextJSPage[]} pages
* @returns {NextJSPage[]}
*/
function findPages(
options = {},
directory = path.resolve(__dirname, '../../../pages'),
Expand Down
30 changes: 25 additions & 5 deletions docs/src/pages.js → docs/src/pages.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
import findPages from /* preval */ 'docs/src/modules/utils/findPages';

const pages = [
export interface MuiPage {
pathname: string;
children?: MuiPage[];
disableDrawer?: boolean;
displayNav?: boolean;
/**
* Props spread to the Link component
*/
linkProps?: Record<string, unknown>;
subheader?: string;
/**
* Overrides the default page title.
*/
title?: string;
}

const pages: MuiPage[] = [
{
pathname: '/getting-started',
children: [
Expand Down Expand Up @@ -168,11 +184,15 @@ const pages = [
title: 'Component API',
pathname: '/api-docs',
children: [
...findPages[0].children,
...findPages[0].children!,
...[{ pathname: '/api-docs/data-grid' }, { pathname: '/api-docs/x-grid' }],
].sort((a, b) =>
a.pathname.replace('/api-docs/', '').localeCompare(b.pathname.replace('/api-docs/', '')),
),
]
.sort((a, b) =>
a.pathname.replace('/api-docs/', '').localeCompare(b.pathname.replace('/api-docs/', '')),
)
.map((page) => {
return { ...page, linkProps: { as: page.pathname.replace(/^\/api-docs/, '/api') } };
}),
},
{
pathname: '/system',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"docs:icons": "yarn workspace docs icons",
"docs:size-why": "cross-env DOCS_STATS_ENABLED=true yarn docs:build",
"docs:start": "yarn workspace docs start",
"docs:i18n": "cross-env BABEL_ENV=test babel-node ./docs/scripts/i18n.js",
"docs:i18n": "cross-env BABEL_ENV=test babel-node --extensions \".tsx,.ts,.js\" ./docs/scripts/i18n.js",
"docs:typescript": "yarn docs:typescript:formatted --watch",
"docs:typescript:check": "yarn workspace docs typescript",
"docs:typescript:formatted": "cross-env BABEL_ENV=test babel-node --extensions \".tsx,.ts,.js\" ./docs/scripts/formattedTSDemos",
Expand Down

0 comments on commit 75dc225

Please sign in to comment.