Skip to content

Commit

Permalink
Snapshot: Normalize annotation whitespace
Browse files Browse the repository at this point in the history
Range#toString() preserves whitespace from the HTML verbatim, which is
not what we want.

https://forums.zotero.org/discussion/115473/z7-beta-unexpected-newlines-in-sep-snapshot-annotations
  • Loading branch information
AbeJellinek committed Aug 20, 2024
1 parent d571b1c commit f21f040
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/dom/common/lib/range.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,18 @@ export function getPageRects(range: Range): DOMRectList {
}
return rects;
}

export function getInnerText(range: Range): string {
let doc = range.commonAncestorContainer.ownerDocument;
if (!doc) {
return range.toString();
}

// We need to actually insert the wrapper into the DOM to get a white-space-normalized innerText
let wrapper = doc.createElement('div');
wrapper.append(range.cloneContents());
doc.body.append(wrapper);
let innerText = wrapper.innerText;
wrapper.remove();
return innerText;
}
3 changes: 2 additions & 1 deletion src/dom/snapshot/snapshot-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
OutlineItem
} from "../../common/types";
import {
getInnerText,
getStartElement
} from "../common/lib/range";
import {
Expand Down Expand Up @@ -182,7 +183,7 @@ class SnapshotView extends DOMView<SnapshotViewState, SnapshotViewData> {
if (range.collapsed) {
return null;
}
let text = type == 'highlight' || type == 'underline' ? range.toString().trim() : undefined;
let text = type == 'highlight' || type == 'underline' ? getInnerText(range).trim() : undefined;
// If this annotation type wants text, but we didn't get any, abort
if (text === '') {
return null;
Expand Down

0 comments on commit f21f040

Please sign in to comment.