Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: The timing of thedoneEach hook call for the cover#2427

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
YiiGuxing wants to merge13 commits intodocsifyjs:develop
base:develop
Choose a base branch
Loading
fromYiiGuxing:feat-cover-lifecycle
Open
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
13 commits
Select commitHold shift + click to select a range
bd5f879
feat: The timing of the `doneEach` hook call for the cover
YiiGuxingMay 13, 2024
bcd1090
Merge branch 'develop' into feat-cover-lifecycle
jhildenbiddleMay 20, 2024
117eb08
Merge branch 'develop' into feat-cover-lifecycle
jhildenbiddleMay 27, 2024
f7666ca
Merge branch 'develop' into feat-cover-lifecycle
YiiGuxingMay 29, 2024
dea1229
test: Add test cases for the `doneEach` hook
YiiGuxingMay 29, 2024
56c922f
style: Fix eslint code style
YiiGuxingMay 29, 2024
b2a9c06
Merge branch 'develop' into feat-cover-lifecycle
Koooooo-7May 29, 2024
a3c3359
Merge branch 'develop' into feat-cover-lifecycle
sy-recordsMay 30, 2024
837d04a
fix(test): fix HTML logging
YiiGuxingMay 30, 2024
ec48f93
feat(test): add dynamic and asynchronous content provision support fo…
YiiGuxingMay 30, 2024
7cc7cdf
feat: cover page supports embedding external files
YiiGuxingMay 30, 2024
0333d96
test: disable logging
YiiGuxingMay 30, 2024
e796604
Merge branch 'develop' into feat-cover-lifecycle
jhildenbiddleJun 5, 2024
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 deletionssrc/core/fetch/index.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionssrc/core/render/index.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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.
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 deletionstest/e2e/embed-files.test.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionstest/e2e/plugins.test.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionstest/helpers/docsify-init.js
View file
Open in desktop
Original file line numberDiff line numberDiff 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 DownExpand 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 DownExpand 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 DownExpand Up@@ -363,13 +363,13 @@ async function docsifyInit(options = {}) {
}

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

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

[8]ページ先頭

©2009-2025 Movatter.jp