Skip to content

Commit 295d102

Browse files
committed
feat: add search root element
1 parent 9aa1db5 commit 295d102

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/text-fragment-utils.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,11 +117,14 @@ const parseTextFragmentDirective = (textFragment) => {
117117
* process.
118118
* @param {Document} documentToProcess - document where to extract and mark
119119
* fragments in.
120+
* @param {Element} root - the root element where to extract and mark
121+
* fragments in.
120122
* @return {{text: Element[]}} `<mark>` elements created to highlight the
121123
* text fragments.
122124
*/
123125
export const processFragmentDirectives =
124-
(parsedFragmentDirectives, documentToProcess = document) => {
126+
(parsedFragmentDirectives, documentToProcess = document,
127+
root = document.body) => {
125128
const processedFragmentDirectives = {};
126129
for (const
127130
[fragmentDirectiveType,
@@ -131,7 +134,7 @@ export const processFragmentDirectives =
131134
processedFragmentDirectives[fragmentDirectiveType] =
132135
fragmentDirectivesOfType.map((fragmentDirectiveOfType) => {
133136
const result = processTextFragmentDirective(
134-
fragmentDirectiveOfType, documentToProcess);
137+
fragmentDirectiveOfType, documentToProcess, root);
135138
if (result.length >= 1) {
136139
// Per spec, the first matching text on the page should be
137140
// highlighted when multiple segments match.
@@ -150,6 +153,8 @@ export const processFragmentDirectives =
150153
* @param {TextFragment} textFragment - Text Fragment to highlight.
151154
* @param {Document} documentToProcess - document where to extract and mark
152155
* fragments in.
156+
* @param {Element} root - the root element where to extract and mark
157+
* fragments in.
153158
* @return {Ranges[]} - Zero or more ranges within the document corresponding
154159
* to the fragment. If the fragment corresponds to more than one location
155160
* in the document (i.e., is ambiguous) then the first two matches will be
@@ -158,11 +163,11 @@ export const processFragmentDirectives =
158163
*/
159164

160165
export const processTextFragmentDirective =
161-
(textFragment, documentToProcess = document) => {
166+
(textFragment, documentToProcess = document, root = document.body) => {
162167
const results = [];
163168

164169
const searchRange = documentToProcess.createRange();
165-
searchRange.selectNodeContents(documentToProcess.body);
170+
searchRange.selectNodeContents(root);
166171

167172
while (!searchRange.collapsed && results.length < 2) {
168173
let potentialMatch;

0 commit comments

Comments
 (0)