mirror of
https://github.com/futurepress/epub.js.git
synced 2025-10-03 14:59:18 +02:00
124 lines
2.4 KiB
JavaScript
124 lines
2.4 KiB
JavaScript
import { qs, qsa } from "./core";
|
|
import Url from "./url";
|
|
import Path from "./path";
|
|
|
|
export function replaceBase(doc, section){
|
|
var base;
|
|
var head;
|
|
|
|
if(!doc){
|
|
return;
|
|
}
|
|
|
|
// head = doc.querySelector("head");
|
|
// base = head.querySelector("base");
|
|
head = qs(doc, "head");
|
|
base = qs(head, "base");
|
|
|
|
if(!base) {
|
|
base = doc.createElement("base");
|
|
head.insertBefore(base, head.firstChild);
|
|
}
|
|
|
|
base.setAttribute("href", section.url);
|
|
}
|
|
|
|
export function replaceCanonical(doc, section){
|
|
var head;
|
|
var link;
|
|
var url = section.url; // window.location.origin + window.location.pathname + "?loc=" + encodeURIComponent(section.url);
|
|
|
|
if(!doc){
|
|
return;
|
|
}
|
|
|
|
head = qs(doc, "head");
|
|
link = qs(head, "link[rel='canonical']");
|
|
|
|
if (link) {
|
|
link.setAttribute("href", url);
|
|
} else {
|
|
link = doc.createElement("link");
|
|
link.setAttribute("rel", "canonical");
|
|
link.setAttribute("href", url);
|
|
head.appendChild(link);
|
|
}
|
|
}
|
|
|
|
export function replaceMeta(doc, section){
|
|
var head;
|
|
var meta;
|
|
var id = section.idref;
|
|
if(!doc){
|
|
return;
|
|
}
|
|
|
|
head = qs(doc, "head");
|
|
meta = qs(head, "link[property='dc:identifier']");
|
|
|
|
if (meta) {
|
|
meta.setAttribute("content", id);
|
|
} else {
|
|
meta = doc.createElement("meta");
|
|
meta.setAttribute("property", "dc:identifier");
|
|
meta.setAttribute("content", id);
|
|
head.appendChild(meta);
|
|
}
|
|
}
|
|
|
|
// TODO: move me to Contents
|
|
export function replaceLinks(contents, fn) {
|
|
|
|
var links = contents.querySelectorAll("a[href]");
|
|
|
|
if (!links.length) {
|
|
return;
|
|
}
|
|
|
|
var base = qs(contents.ownerDocument, "base");
|
|
var location = base ? base.getAttribute("href") : undefined;
|
|
var replaceLink = function(link){
|
|
var href = link.getAttribute("href");
|
|
|
|
if(href.indexOf("mailto:") === 0){
|
|
return;
|
|
}
|
|
|
|
var absolute = (href.indexOf("://") > -1);
|
|
var linkUrl = new Url(href, location);
|
|
|
|
if(absolute){
|
|
|
|
link.setAttribute("target", "_blank");
|
|
|
|
}else{
|
|
link.onclick = function(){
|
|
|
|
if(linkUrl && linkUrl.hash) {
|
|
fn(linkUrl.Path.path + linkUrl.hash);
|
|
} else if(linkUrl){
|
|
fn(linkUrl.Path.path);
|
|
} else {
|
|
fn(href);
|
|
}
|
|
|
|
return false;
|
|
};
|
|
}
|
|
}.bind(this);
|
|
|
|
for (var i = 0; i < links.length; i++) {
|
|
replaceLink(links[i]);
|
|
}
|
|
|
|
|
|
}
|
|
|
|
export function substitute(content, urls, replacements) {
|
|
urls.forEach(function(url, i){
|
|
if (url && replacements[i]) {
|
|
content = content.replace(new RegExp(url, "g"), replacements[i]);
|
|
}
|
|
});
|
|
return content;
|
|
}
|