Skip to content

Commit

Permalink
EPUB: Potentially prevent invalid annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
AbeJellinek committed Dec 6, 2024
1 parent 9e52c4d commit 4aa2885
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
22 changes: 20 additions & 2 deletions src/dom/common/dom-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,12 @@ abstract class DOMView<State extends DOMViewState, Data> {

protected abstract _updateViewStats(): void;

protected _getContainingRoot(node: Node): HTMLElement | null {
return this._iframeDocument.body.contains(node)
? this._iframeDocument.body
: null;
}

// ***
// Utilities - called in appropriate event handlers
// ***
Expand Down Expand Up @@ -912,8 +918,12 @@ abstract class DOMView<State extends DOMViewState, Data> {
return;
}
if (annotation.type === 'note') {
let root = this._getContainingRoot(oldRange.startContainer);
if (!root) {
throw new Error('Annotation is outside of root?');
}
let walker = this._iframeDocument.createTreeWalker(
this._iframeDocument.body,
root,
NodeFilter.SHOW_ELEMENT,
node => (isBlock(node as Element) && !node.contains(oldRange!.startContainer)
? NodeFilter.FILTER_ACCEPT
Expand All @@ -930,7 +940,15 @@ abstract class DOMView<State extends DOMViewState, Data> {
walker.previousNode();
}
newRange.selectNode(walker.currentNode);
this._setAnnotationRange(annotation, newRange);
try {
this._setAnnotationRange(annotation, newRange);
}
catch (e) {
// Reached the end of the section (EPUB)
// TODO: Allow movement between sections
event.preventDefault();
return;
}
this._options.onUpdateAnnotations([annotation]);
this._navigateToSelector(annotation.position, {
block: 'center',
Expand Down
5 changes: 5 additions & 0 deletions src/dom/epub/epub-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,11 @@ class EPUBView extends DOMView<EPUBViewState, EPUBViewData> {
};
}

protected override _getContainingRoot(node: Node) {
return this._sectionRenderers.find(r => r.container.contains(node))?.container
?? null;
}

private _upsertAnnotation(annotation: NewAnnotation<WADMAnnotation>) {
let existingAnnotation = this._annotations.find(
existingAnnotation => existingAnnotation.text === annotation!.text
Expand Down

0 comments on commit 4aa2885

Please sign in to comment.