Commit 4bc0beed authored by Robert Knight's avatar Robert Knight

Add TextRange.{relativeTo, fromOffsets} methods

parent 7b1f4e21
......@@ -302,6 +302,28 @@ describe('annotator/anchoring/text-range', () => {
});
});
describe('#relativeTo', () => {
it('returns a range with start and end positions relative to the given element', () => {
const parent = document.createElement('div');
const firstChild = document.createElement('span');
firstChild.append('foo');
const secondChild = document.createElement('span');
secondChild.append('bar');
parent.append(firstChild, secondChild);
const textRange = new TextRange(
new TextPosition(firstChild, 0),
new TextPosition(secondChild, 3)
);
const parentRange = textRange.relativeTo(parent);
assert.equal(parentRange.start.element, parent);
assert.equal(parentRange.start.offset, 0);
assert.equal(parentRange.end.element, parent);
assert.equal(parentRange.end.offset, 6);
});
});
describe('fromRange', () => {
it('sets `start` and `end` points of range', () => {
const el = document.createElement('div');
......@@ -325,5 +347,19 @@ describe('annotator/anchoring/text-range', () => {
}, 'Point is not in an element or text node');
});
});
describe('fromOffsets', () => {
it('returns a `TextRange` with correct start and end', () => {
const root = document.createElement('div');
root.append('Some text content');
const textRange = TextRange.fromOffsets(root, 0, 10);
assert.equal(textRange.start.element, root);
assert.equal(textRange.start.offset, 0);
assert.equal(textRange.end.element, root);
assert.equal(textRange.end.offset, 10);
});
});
});
});
......@@ -200,6 +200,19 @@ export class TextRange {
this.end = end;
}
/**
* Return a copy of this range with start and end positions relative to a
* given ancestor. See `TextPosition.relativeTo`.
*
* @param {Element} element
*/
relativeTo(element) {
return new TextRange(
this.start.relativeTo(element),
this.end.relativeTo(element)
);
}
/**
* Resolve the `TextRange` to a DOM range.
*
......@@ -250,4 +263,18 @@ export class TextRange {
const end = TextPosition.fromPoint(range.endContainer, range.endOffset);
return new TextRange(start, end);
}
/**
* Return a `TextRange` from the `start`th to `end`th characters in `root`.
*
* @param {Element} root
* @param {number} start
* @param {number} end
*/
static fromOffsets(root, start, end) {
return new TextRange(
new TextPosition(root, start),
new TextPosition(root, end)
);
}
}
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