Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Better support for relative links (e.g. download links) for non-markdown files #2300

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
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
3 changes: 3 additions & 0 deletions docs/_assets/anothertest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Another test

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Binary file added docs/_assets/manual.pdf
Binary file not shown.
3 changes: 3 additions & 0 deletions docs/_assets/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
This is text.txt

Hello world!
8 changes: 8 additions & 0 deletions docs/test.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Test

- [test.txt](./_assets/test.txt)
- [anothertest.md](./_assets/anothertest.md)
- [manual.pdf](./_assets/manual.pdf)
- [https://docsify.js.org/quickstart.md](https://docsify.js.org/quickstart.md)
- https://docsify.js.org/quickstart.md

125 changes: 72 additions & 53 deletions src/core/fetch/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable no-unused-vars */
import { getParentPath, stringifyQuery } from '../router/util.js';
import { getParentPath, stringifyQuery, getExtension } from '../router/util.js';
import { noop, isExternal } from '../util/core.js';
import { get } from '../util/ajax.js';

Expand Down Expand Up @@ -84,68 +84,87 @@ export function Fetch(Base) {
_fetch(cb = noop) {
const { query } = this.route;
let { path } = this.route;
const { ext } = this.config;

// Prevent loading remote content via URL hash
// Ex: https://foo.com/#//bar.com/file.md
if (isExternal(path)) {
history.replaceState(null, '', '#');
this.router.normalize();
} else {
const qs = stringifyQuery(query, ['id']);
const { loadNavbar, requestHeaders, loadSidebar } = this.config;
// Abort last request
// Prevent loading remote content via URL hash
// Ex: https://foo.com/#//bar.com/file.md

this._fetchExternal();
} else {
const pathExt = getExtension(path);
const file = this.router.getFile(path);

this.isRemoteUrl = isExternal(file);
// Current page is html
this.isHTML = /\.html$/g.test(file);
if (pathExt && pathExt !== ext && pathExt !== '.html') {
this._fetchNonContent(file);
} else {
this._fetchContent(path, query, file, cb);
}
}
}

// create a handler that should be called if content was fetched successfully
const contentFetched = (text, opt) => {
this._renderMain(
text,
opt,
this._loadSideAndNav(path, qs, loadSidebar, cb)
);
};
_fetchExternal() {
history.replaceState(null, '', '#');
this.router.normalize();
}

// and a handler that is called if content failed to fetch
const contentFailedToFetch = _error => {
this._fetchFallbackPage(path, qs, cb) || this._fetch404(file, qs, cb);
};
_fetchContent(path, query, file, cb) {
const qs = stringifyQuery(query, ['id']);
const { loadNavbar, requestHeaders, loadSidebar } = this.config;
// Abort last request

this.isRemoteUrl = isExternal(file);
// Current page is html
this.isHTML = /\.html$/g.test(file);

// create a handler that should be called if content was fetched successfully
const contentFetched = (text, opt) => {
this._renderMain(
text,
opt,
this._loadSideAndNav(path, qs, loadSidebar, cb)
);
};

// attempt to fetch content from a virtual route, and fallback to fetching the actual file
if (!this.isRemoteUrl) {
this.matchVirtualRoute(path).then(contents => {
if (typeof contents === 'string') {
contentFetched(contents);
} else {
this.#request(file + qs, requestHeaders).then(
contentFetched,
contentFailedToFetch
);
}
});
} else {
// if the requested url is not local, just fetch the file
this.#request(file + qs, requestHeaders).then(
contentFetched,
contentFailedToFetch
);
}
// and a handler that is called if content failed to fetch
const contentFailedToFetch = _error => {
this._fetchFallbackPage(path, qs, cb) || this._fetch404(file, qs, cb);
};

// Load nav
loadNavbar &&
this.#loadNested(
path,
qs,
loadNavbar,
text => this._renderNav(text),
this,
true
);
// attempt to fetch content from a virtual route, and fallback to fetching the actual file
if (!this.isRemoteUrl) {
this.matchVirtualRoute(path).then(contents => {
if (typeof contents === 'string') {
contentFetched(contents);
} else {
this.#request(file + qs, requestHeaders).then(
contentFetched,
contentFailedToFetch
);
}
});
} else {
// if the requested url is not local, just fetch the file
this.#request(file + qs, requestHeaders).then(
contentFetched,
contentFailedToFetch
);
}

// Load nav
loadNavbar &&
this.#loadNested(
path,
qs,
loadNavbar,
text => this._renderNav(text),
this,
true
);
}

_fetchNonContent(file) {
window.location.replace(file);
}

_fetchCover() {
Expand Down
1 change: 1 addition & 0 deletions src/core/render/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ export class Compiler {
origin.code = highlightCodeCompiler({ renderer });
origin.link = linkCompiler({
renderer,
contentBase,
router,
linkTarget,
linkRel,
Expand Down
38 changes: 15 additions & 23 deletions src/core/render/compiler/link.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getAndRemoveConfig } from '../utils.js';
import { isAbsolutePath } from '../../router/util.js';
import { isAbsolutePath, getPath, getParentPath } from '../../router/util.js';

export const linkCompiler = ({
renderer,
Expand All @@ -18,29 +18,21 @@ export const linkCompiler = ({
: '';
title = str;

if (
!isAbsolutePath(href) &&
!compilerClass._matchNotCompileLink(href) &&
!config.ignore
) {
if (href === compilerClass.config.homepage) {
href = 'README';
if (!config.ignore && !compilerClass._matchNotCompileLink(href)) {
if (!isAbsolutePath(href)) {
href = router.toURL(href, null, router.getCurrentPath());
} else {
attrs.push(
href.indexOf('mailto:') === 0 ? '' : `target="${linkTarget}"`
);
attrs.push(
href.indexOf('mailto:') === 0
? ''
: linkRel !== ''
? ` rel="${linkRel}"`
: ''
);
}

href = router.toURL(href, null, router.getCurrentPath());
} else {
if (!isAbsolutePath(href) && href.slice(0, 2) === './') {
href =
document.URL.replace(/\/(?!.*\/).*/, '/').replace('#/./', '') + href;
}
attrs.push(href.indexOf('mailto:') === 0 ? '' : `target="${linkTarget}"`);
attrs.push(
href.indexOf('mailto:') === 0
? ''
: linkRel !== ''
? ` rel="${linkRel}"`
: ''
);
}

if (config.disabled) {
Expand Down
19 changes: 14 additions & 5 deletions src/core/router/history/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
cleanPath,
replaceSlug,
resolvePath,
getExtension,
} from '../util.js';
import { noop } from '../../util/core.js';

Expand Down Expand Up @@ -32,11 +33,19 @@ export class History {
}

#getFileName(path, ext) {
return new RegExp(`\\.(${ext.replace(/^\./, '')}|html)$`, 'g').test(path)
? path
: /\/$/g.test(path)
? `${path}README${ext}`
: `${path}${ext}`;
const pathExt = getExtension(path);
const endsWithSlash = /\/$/g;

let filename;
if (pathExt) {
filename = path;
} else if (endsWithSlash.test(path)) {
filename = `${path}README${ext}`;
} else {
filename = `${path}${ext}`;
}

return filename;
}

getBasePath() {
Expand Down
2 changes: 1 addition & 1 deletion src/core/router/history/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class HashHistory extends History {
// This handles the case where Docsify is served off an
// explicit file path, i.e.`/base/index.html#/blah`. This
// prevents the `/index.html` part of the URI from being
// remove during routing.
// removed during routing.
// See here: https://github.com/docsifyjs/docsify/pull/1372
const basePath = path.endsWith('.html')
? path + '#/' + base
Expand Down
10 changes: 10 additions & 0 deletions src/core/router/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,13 @@ export function getPath(...args) {
export const replaceSlug = cached(path => {
return path.replace('#', '?id=');
});

export function getExtension(path) {
const matched = path.match(/\.\w+$/);

if (!matched) {
return null;
}

return matched[0];
}
42 changes: 42 additions & 0 deletions test/integration/render.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,5 +263,47 @@ describe('render', function () {
`"<p><a href=\\"http://url\\" target=\\"_blank\\" rel=\\"noopener\\" id=\\"someCssID\\">alt text</a></p>"`
);
});

test('relative link with md extension', async function () {
const output = window.marked('[alt text](test.md)');

expect(output).toMatchInlineSnapshot(
`"<p><a href=\\"#/test\\" >alt text</a></p>"`
);
});

test('relative link with md extension starting with "./"', async function () {
const output = window.marked('[alt text](./test.md)');

expect(output).toMatchInlineSnapshot(
`"<p><a href=\\"#/./test\\" >alt text</a></p>"`
);
});

test('relative link with extension other than md', async function () {
const output = window.marked('[alt text](test.txt)');

expect(output).toMatchInlineSnapshot(
`"<p><a href=\\"#/test.txt\\" >alt text</a></p>"`
);
});

test('relative link with extension other than md starting with "./"', async function () {
const output = window.marked('[alt text](./test.txt)');

expect(output).toMatchInlineSnapshot(
`"<p><a href=\\"#/./test.txt\\" >alt text</a></p>"`
);
});

test('absolute link with md extension', async function () {
const output = window.marked(
'[alt text](http://www.example.com/test.md)'
);

expect(output).toMatchInlineSnapshot(
`"<p><a href=\\"http://www.example.com/test.md\\" target=\\"_blank\\" rel=\\"noopener\\">alt text</a></p>"`
);
});
});
});