support magicbook (external/internal) links generation

This commit is contained in:
jasongao97 2022-10-25 15:26:10 -04:00
parent 5c7313abc0
commit 53b68c1830
3 changed files with 46 additions and 2 deletions

View file

@ -2,7 +2,8 @@
"title": "Nature of Code",
"addPlugins": [
"magicbook-codesplit",
"magicbook-katex"
"magicbook-katex",
"magicbook/plugins/relative-links.js"
],
"destination": "build",
"files": [

View file

@ -0,0 +1,43 @@
const through = require('through2');
const cheerio = require('cheerio');
const Plugin = function (registry) {
registry.after(
'markdown:convert',
'relativelinks:updatehref',
this.removeRelativeLinksPath,
);
};
Plugin.prototype = {
removeRelativeLinksPath: function (config, stream, extras, callback) {
stream = stream.pipe(
through.obj(function (file, _, cb) {
file.$el = file.$el || cheerio.load(file.contents.toString());
let found = false;
file.$el('a').each(function () {
const jel = file.$el(this);
const prefHref = jel.attr('href');
// test if is a valid relative link
if (prefHref && prefHref.indexOf('://') < 0) {
// remove the relative path
jel.attr('href', `#${prefHref.split('#')[1]}`);
found = true;
}
});
if (found) {
file.contents = Buffer.from(file.$el.html());
}
cb(null, file);
}),
);
callback(null, config, stream, extras);
},
};
module.exports = Plugin;

View file

@ -162,7 +162,7 @@ section[data-type="toc"] {
a[href]::after {
content: " (see page " target-counter(attr(href), page) ")";
}
a[href^="http:"]::after {
a[href^="http"]::after {
content: " ("attr(href)")";
}
a[href].index-term-link::after {