Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,21 @@ window.$docsify = {
};
```

## navbarPreservePath

- Type: `Boolean`
- Default: `false`

If **true**, appends the current document path to navbar links that point to a language root. This makes it possible to switch languages while staying on the corresponding document.

For example, when the current path is `/quickstart`, a navbar link to `/zh-cn/` becomes `/zh-cn/quickstart`.

```js
window.$docsify = {
navbarPreservePath: true,
};
```

## name

- Type: `Boolean|String`
Expand Down
1 change: 1 addition & 0 deletions src/core/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const defaultDocsifyConfig = () => ({
markdown: null,
maxLevel: 6,
mergeNavbar: false,
navbarPreservePath: false,
name: /** @type {boolean | string} */ (''),
nameLink: window.location.pathname,
nativeEmoji: false,
Expand Down
53 changes: 51 additions & 2 deletions src/core/render/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import tinydate from 'tinydate';
import * as dom from '../util/dom.js';
import { getPath, isAbsolutePath } from '../router/util.js';
import { cleanPath, getPath, isAbsolutePath } from '../router/util.js';
import { isMobile } from '../util/env.js';
import { isPrimitive } from '../util/core.js';
import { isExternal, isPrimitive } from '../util/core.js';
import { Compiler } from './compiler.js';
import * as tpl from './tpl.js';
import { prerenderEmbed } from './embed.js';
Expand Down Expand Up @@ -397,10 +397,59 @@ export function Render(Base) {

['.app-nav', '.app-nav-merged'].forEach(selector => {
dom.setHTML(selector, html);
if (this.config.navbarPreservePath) {
this.#appendNavbarPath(selector);
}
this.#addTextAsTitleAttribute(`${selector} a`);
});
}

#appendNavbarPath(selector) {
const nav = dom.find(selector);

if (!nav) {
return;
}

const links = dom.findAll(nav, 'a').reduce((links, link) => {
const anchor = /** @type {HTMLAnchorElement} */ (link);
const href = anchor.getAttribute('href');

if (
!href ||
isExternal(anchor.href) ||
(href.startsWith('#') && !href.startsWith('#/'))
) {
return links;
}

const route = this.router.parse(href);
const path = cleanPath(`/${route.path}`);

if (route.query.id || (path !== '/' && !path.endsWith('/'))) {
return links;
}

links.push({ link: anchor, path, query: route.query });
return links;
}, /** @type {{link: HTMLAnchorElement, path: string, query: Record<string, string>}[]} */ ([]));

const currentPath = cleanPath(`/${this.route.path}`);
const currentRoot = links
.filter(({ path }) => currentPath.startsWith(path))
.sort((a, b) => b.path.length - a.path.length)[0];

if (!currentRoot) {
return;
}

const suffix = currentPath.slice(currentRoot.path.length);

links.forEach(({ link, path, query }) => {
link.setAttribute('href', this.router.toURL(`${path}${suffix}`, query));
});
}

_renderMain(text, opt = {}, next) {
const { response } = this.route;

Expand Down
63 changes: 63 additions & 0 deletions test/integration/docs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,67 @@ describe('Docs Site', function () {
expect(navbarElm).not.toBeNull();
expect(navbarElm.outerHTML).toMatchSnapshot();
});

test('navbar appends the current path to language links when enabled', async () => {
await docsifyInit({
config: {
loadNavbar: '_navbar.md',
navbarPreservePath: true,
},
markdown: {
homepage: '# Hello World',
navbar: `
- [English](/en-us/)
- [简体中文](/zh-cn/)
- [Guide](/guide)
- [Anchor](#section)
- [External](https://example.com/)
`,
},
testURL: `${process.env.TEST_HOST}/docsify-init.html#/en-us/guide/start`,
waitForSelector: '.app-nav > ul',
});

const links = Object.fromEntries(
[...document.querySelectorAll('.app-nav a')].map(link => [
link.textContent,
link.getAttribute('href'),
]),
);

expect(links).toEqual({
English: '#/en-us/guide/start',
简体中文: '#/zh-cn/guide/start',
Guide: '#/guide',
Anchor: '#/en-us/guide/start?id=section',
External: 'https://example.com/',
});
});

test('navbar appends the current path in history mode and merged navbars', async () => {
await docsifyInit({
config: {
loadNavbar: '_navbar.md',
mergeNavbar: true,
navbarPreservePath: true,
routerMode: 'history',
},
markdown: {
homepage: '# Hello World',
navbar: `
- [English](/en-us/)
- [简体中文](/zh-cn/)
`,
},
testURL: `${process.env.TEST_HOST}/en-us/guide/start`,
waitForSelector: '.app-nav-merged > ul',
});

document.querySelectorAll('.app-nav, .app-nav-merged').forEach(nav => {
expect([...nav.querySelectorAll('a')].map(link => link.href)).toEqual([
`${process.env.TEST_HOST}/en-us/guide/start`,
`${process.env.TEST_HOST}/zh-cn/guide/start`,
]);
});
});
});