Skip to content
Open
Show file tree
Hide file tree
Changes from 13 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
37 changes: 23 additions & 14 deletions src/core/fetch/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ export function Fetch(Base) {
}
}

_fetchCover() {
_fetchCover(cb = noop) {
const { coverpage, requestHeaders } = this.config;
const query = this.route.query;
const root = getParentPath(this.route.path);
Expand All @@ -170,17 +170,26 @@ export function Fetch(Base) {
}

const coverOnly = Boolean(path) && this.config.onlyCover;
const next = () => cb(coverOnly);
if (path) {
path = this.router.getFile(root + path);
this.coverIsHTML = /\.html$/g.test(path);
get(path + stringifyQuery(query, ['id']), false, requestHeaders).then(
text => this._renderCover(text, coverOnly),
text => this._renderCover(text, coverOnly, next),
(event, response) => {
this.coverIsHTML = false;
this._renderCover(
`# ${response.status} - ${response.statusText}`,
coverOnly,
next,
);
},
);
} else {
this._renderCover(null, coverOnly);
this._renderCover(null, coverOnly, next);
}

return coverOnly;
} else {
cb(false);
}
}

Expand All @@ -190,16 +199,16 @@ export function Fetch(Base) {
cb();
};

const onlyCover = this._fetchCover();

if (onlyCover) {
done();
} else {
this._fetch(() => {
onNavigate();
this._fetchCover(onlyCover => {
if (onlyCover) {
done();
});
}
} else {
this._fetch(() => {
onNavigate();
done();
});
}
});
}

_fetchFallbackPage(path, qs, cb = noop) {
Expand Down
57 changes: 38 additions & 19 deletions src/core/render/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ export function Render(Base) {
});
}

_renderCover(text, coverOnly) {
_renderCover(text, coverOnly, next) {
const el = dom.getNode('.cover');

dom.toggleClass(
Expand All @@ -392,37 +392,56 @@ export function Render(Base) {
);
if (!text) {
dom.toggleClass(el, 'remove', 'show');
next();
return;
}

dom.toggleClass(el, 'add', 'show');

let html = this.coverIsHTML ? text : this.compiler.cover(text);
const callback = html => {
const m = html
.trim()
.match('<p><img.*?data-origin="(.*?)"[^a]+alt="(.*?)">([^<]*?)</p>$');

const m = html
.trim()
.match('<p><img.*?data-origin="(.*?)"[^a]+alt="(.*?)">([^<]*?)</p>$');
if (m) {
if (m[2] === 'color') {
el.style.background = m[1] + (m[3] || '');
} else {
let path = m[1];

if (m) {
if (m[2] === 'color') {
el.style.background = m[1] + (m[3] || '');
} else {
let path = m[1];
dom.toggleClass(el, 'add', 'has-mask');
if (!isAbsolutePath(m[1])) {
path = getPath(this.router.getBasePath(), m[1]);
}

dom.toggleClass(el, 'add', 'has-mask');
if (!isAbsolutePath(m[1])) {
path = getPath(this.router.getBasePath(), m[1]);
el.style.backgroundImage = `url(${path})`;
el.style.backgroundSize = 'cover';
el.style.backgroundPosition = 'center center';
}

el.style.backgroundImage = `url(${path})`;
el.style.backgroundSize = 'cover';
el.style.backgroundPosition = 'center center';
html = html.replace(m[0], '');
}

html = html.replace(m[0], '');
}
this._renderTo('.cover-main', html);
next();
};

this._renderTo('.cover-main', html);
// TODO: Call the 'beforeEach' and 'afterEach' hooks.
// However, when the cover and the home page are on the same page,
// the 'beforeEach' and 'afterEach' hooks are called multiple times.
// It is difficult to determine the target of the hook within the
// hook functions. We might need to make some changes.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@YiiGuxing I think we should update the hooks in a backwards compatible way, such that the hook can somehow see which content it is called for. For example it can see string values like "cover", "sidebar", etc. The default (right now no sort of value to determine the target of the hook) would work the same as before for anyone who hasn't updated their plugin code.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ultimate result should be, that all markdown files are handled the same, regardless where in the app they are rendered (cover, sidebar, nav, etc) but any plugin can easily decide which to handle.

Something like

hook.doneEach((section) => {
  if (section === 'cover') {
    // run logic after cover rendered
  } else if (section === 'sidebar') {
    // run logic after sidebar rendered
  } else if (section === 'nav') {
    // run logic after nav bar rendered
  } else if (section === 'main') {
    // run logic after main content rendered (new way)
  } else {
    // run logic after main content rendered (old way, fallback)
  }
})

or similar.

if (this.coverIsHTML) {
callback(text);
} else {
prerenderEmbed(
{
compiler: this.compiler,
raw: text,
},
tokens => callback(this.compiler.cover(tokens)),
);
}
}

_updateRender() {
Expand Down
33 changes: 33 additions & 0 deletions test/e2e/embed-files.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import docsifyInit from '../helpers/docsify-init.js';
import { test, expect } from './fixtures/docsify-init-fixture.js';

test.describe('Embed files', () => {
const routes = {
'fragment.md': '## Fragment',
};

test('embed into homepage', async ({ page }) => {
await docsifyInit({
routes,
markdown: {
homepage: "# Hello World\n\n[fragment](fragment.md ':include')",
},
// _logHTML: {},
});

await expect(page.locator('#main')).toContainText('Fragment');
});

test('embed into cover', async ({ page }) => {
await docsifyInit({
routes,
markdown: {
homepage: '# Hello World',
coverpage: "# Cover\n\n[fragment](fragment.md ':include')",
},
// _logHTML: {},
});

await expect(page.locator('.cover-main')).toContainText('Fragment');
});
});
68 changes: 68 additions & 0 deletions test/e2e/plugins.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,74 @@ test.describe('Plugins', () => {
});
});

test.describe('doneEach()', () => {
test('callback after cover loads', async ({ page }) => {
const consoleMessages = [];

page.on('console', msg => consoleMessages.push(msg.text()));

await docsifyInit({
config: {
plugins: [
function (hook) {
hook.doneEach(() => {
const homepageTitle = document.querySelector('#homepage-title');
const coverTitle = document.querySelector('#cover-title');
console.log(homepageTitle?.textContent);
console.log(coverTitle?.textContent);
});
},
],
},
markdown: {
homepage: '# Hello World :id=homepage-title',
coverpage: () => {
return new Promise(resolve => {
setTimeout(() => resolve('# Cover Page :id=cover-title'), 500);
});
},
},
// _logHTML: {},
});

await expect(consoleMessages).toEqual(['Hello World', 'Cover Page']);
});

test('only cover', async ({ page }) => {
const consoleMessages = [];

page.on('console', msg => consoleMessages.push(msg.text()));

await docsifyInit({
config: {
onlyCover: true,
plugins: [
function (hook) {
hook.doneEach(() => {
const homepageTitle = document.querySelector('#homepage-title');
const coverTitle = document.querySelector('#cover-title');
console.log(homepageTitle?.textContent);
console.log(coverTitle?.textContent);
});
},
],
},
markdown: {
homepage: '# Hello World :id=homepage-title',
coverpage: () => {
return new Promise(resolve => {
setTimeout(() => resolve('# Cover Page :id=cover-title'), 500);
});
},
},
waitForSelector: '.cover-main > *:first-child',
// _logHTML: {},
});

await expect(consoleMessages).toEqual(['undefined', 'Cover Page']);
});
});

test.describe('route data accessible to plugins', () => {
let routeData = null;

Expand Down
60 changes: 30 additions & 30 deletions test/helpers/docsify-init.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ const docsifyURL = '/dist/docsify.js'; // Playwright
* @param {Function|Object} [options.config] docsify configuration (merged with default)
* @param {String} [options.html] HTML content to use for docsify `index.html` page
* @param {Object} [options.markdown] Docsify markdown content
* @param {String} [options.markdown.coverpage] coverpage markdown
* @param {String} [options.markdown.homepage] homepage markdown
* @param {String} [options.markdown.navbar] navbar markdown
* @param {String} [options.markdown.sidebar] sidebar markdown
* @param {Object} [options.routes] custom routes defined as `{ pathOrGlob: responseText }`
* @param {String|(()=>Promise<String>|String)} [options.markdown.coverpage] coverpage markdown
* @param {String|(()=>Promise<String>|String)} [options.markdown.homepage] homepage markdown
* @param {String|(()=>Promise<String>|String)} [options.markdown.navbar] navbar markdown
* @param {String|(()=>Promise<String>|String)} [options.markdown.sidebar] sidebar markdown
* @param {Record<String,String|(()=>Promise<String>|String)>} [options.routes] custom routes defined as `{ pathOrGlob: response }`
* @param {String} [options.script] JS to inject via <script> tag
* @param {String|String[]} [options.scriptURLs] External JS to inject via <script src="..."> tag(s)
* @param {String} [options.style] CSS to inject via <style> tag
Expand Down Expand Up @@ -114,7 +114,7 @@ async function docsifyInit(options = {}) {
...options.markdown,
})
.filter(([key, markdown]) => key && markdown)
.map(([key, markdown]) => [key, stripIndent`${markdown}`]),
.map(([key, markdown]) => [key, markdown]),
);
},
get routes() {
Expand All @@ -132,13 +132,12 @@ async function docsifyInit(options = {}) {
...options.routes,
})
// Remove items with falsey responseText
.filter(([url, responseText]) => url && responseText)
.map(([url, responseText]) => [
.filter(([url, response]) => url && response)
.map(([url, response]) => [
// Convert relative to absolute URL
new URL(url, settings.config.basePath || process.env.TEST_HOST)
.href,
// Strip indentation from responseText
stripIndent`${responseText}`,
response,
]),
);

Expand Down Expand Up @@ -173,29 +172,30 @@ async function docsifyInit(options = {}) {
mock.setup();
}

for (let [urlGlob, response] of Object.entries(settings.routes)) {
for (const [urlGlob, response] of Object.entries(settings.routes)) {
const fileExtension = (urlGlob.match(reFileExtentionFromURL) || [])[1];
const contentType = contentTypes[fileExtension];

if (typeof response === 'string') {
response = {
status: 200,
body: response,
};
}

// Specifying contentType required for Webkit
response.contentType = response.contentType || contentType || '';
const responseBody = async () => {
if (typeof response === 'string') {
return stripIndent`${response}`;
} else {
return stripIndent`${await response()}`;
}
};

if (isJSDOM) {
mock.get(urlGlob, (req, res) => {
return res
.status(response.status)
.body(settings.routes[urlGlob])
.header('Content-Type', contentType);
mock.get(urlGlob, async (req, res) => {
const body = await responseBody();
return res.status(200).body(body).header('Content-Type', contentType);
});
} else {
await page.route(urlGlob, route => route.fulfill(response));
await page.route(urlGlob, async route => {
return route.fulfill({
status: 200,
body: await responseBody(),
contentType: contentType || '',
});
});
}
}

Expand Down Expand Up @@ -363,13 +363,13 @@ async function docsifyInit(options = {}) {
}

if (htmlArr.length) {
htmlArr.forEach(html => {
for (let html of htmlArr) {
if (settings._logHTML.format !== false) {
html = prettier.format(html, { parser: 'html' });
html = await prettier.format(html, { parser: 'html' });
}

console.log(html);
});
}
} else {
console.warn(`docsify-init(): unable to match selector '${selector}'`);
}
Expand Down