Commit 275ea593 authored by Robert Knight's avatar Robert Knight

Handle case where `nodeFromXPath` returns a non-Element result

Handle scenarios flagged by type checking where `nodeFromXPath` may
return `null` or a non-Element node. Previously it could never return
`null` but would throw an exception if the node was not found. In the
new code a check is needed.

The case where `nodeFromXPath` returned a non-Element node would never
happen with XPaths generated by the client but could happen if an
annotation was created via the API with a non-simple XPath.
parent 908c8159
...@@ -380,6 +380,9 @@ export class SerializedRange { ...@@ -380,6 +380,9 @@ export class SerializedRange {
let node; let node;
try { try {
node = nodeFromXPath(this[p], root); node = nodeFromXPath(this[p], root);
if (!node) {
throw new Error('Node not found');
}
} catch (e) { } catch (e) {
throw new RangeError(`Error while finding ${p} node: ${this[p]}: ` + e); throw new RangeError(`Error while finding ${p} node: ${this[p]}: ` + e);
} }
......
...@@ -62,14 +62,14 @@ export function xpathFromNode(node, root) { ...@@ -62,14 +62,14 @@ export function xpathFromNode(node, root) {
} }
/** /**
* Return all text node descendants of `element`. * Return all text node descendants of `parent`.
* *
* @param {Element} element * @param {Node} parent
* @return {Text[]} * @return {Text[]}
*/ */
export function getTextNodes(element) { export function getTextNodes(parent) {
const nodes = []; const nodes = [];
for (let node of Array.from(element.childNodes)) { for (let node of Array.from(parent.childNodes)) {
// We test `nodeType` here rather than using `instanceof` because we have // We test `nodeType` here rather than using `instanceof` because we have
// tests where `node` comes from a different iframe. // tests where `node` comes from a different iframe.
if (node.nodeType === Node.TEXT_NODE) { if (node.nodeType === Node.TEXT_NODE) {
......
...@@ -97,6 +97,7 @@ function evaluateSimpleXPath(xpath, root) { ...@@ -97,6 +97,7 @@ function evaluateSimpleXPath(xpath, root) {
* *
* @param {string} xpath * @param {string} xpath
* @param {Element} [root] * @param {Element} [root]
* @return {Node|null}
*/ */
export function nodeFromXPath(xpath, root = document.body) { export function nodeFromXPath(xpath, root = document.body) {
try { try {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment