Skip to content

Commit

Permalink
Display and recover from errors within EPUB sections
Browse files Browse the repository at this point in the history
  • Loading branch information
AbeJellinek committed Feb 5, 2024
1 parent d9f4e64 commit bcb3aba
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
5 changes: 5 additions & 0 deletions src/dom/epub/lib/sanitize-and-render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ export async function sanitizeAndRender(xhtml: string, options: {

let doc = container.ownerDocument;
let sectionDoc = new DOMParser().parseFromString(xhtml, 'application/xhtml+xml');

if (sectionDoc.getElementsByTagName('parsererror').length) {
throw new Error('Invalid XHTML');
}

let walker = doc.createTreeWalker(sectionDoc, NodeFilter.SHOW_ELEMENT);
let toRemove = [];

Expand Down
24 changes: 21 additions & 3 deletions src/dom/epub/section-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,30 @@ class SectionView {
}
if (!this.section.url) {
console.error('Section has no URL', this.section);
this.body = this._document.createElement('div');
this._displayError('Missing content');
return;
}
let xhtml = await this.section.render(requestFn);
this.body = await sanitizeAndRender(xhtml,
{ container: this.container, styleScoper: this._styleScoper });

try {
this.body = await sanitizeAndRender(xhtml,
{ container: this.container, styleScoper: this._styleScoper });
}
catch (e) {
console.error('Error rendering section ' + this.section.index + ' (' + this.section.href + ')', e);
this._displayError('Invalid content');
}
}

private _displayError(message: string) {
let errorDiv = this._document.createElement('div');
errorDiv.style.color = 'red';
errorDiv.style.fontSize = '1.5em';
errorDiv.style.fontWeight = 'bold';
errorDiv.style.textAlign = 'center';
errorDiv.append(`[Section ${this.section.index}: ${message}]`);
this.container.replaceChildren(errorDiv);
this.body = errorDiv;
}

/**
Expand Down

0 comments on commit bcb3aba

Please sign in to comment.