text-fragments-ts/src/ index.ts
1088 lines
56 KiB

  1. //////////////////////
  2. /// Text Fragments ///
  3. //////////////////////
  4. // An implementation of (most of) the Text Fragments draft spec.
  5. // See https://wicg.github.io/scroll-to-text-fragment/
  6. // Based on the version of 13 August 2020. <https://raw.githubusercontent.com/WICG/scroll-to-text-fragment/2dcfbd6e272f51e5b250c58076b6d1cc57656fce/index.html>
  7. import {
  8. locale,
  9. isElement,
  10. nextNode,
  11. } from './common.js';
  12. import {
  13. followsInTree,
  14. nodeLength,
  15. nextNodeInShadowIncludingTreeOrder,
  16. isShadowIncludingDescendant,
  17. isShadowIncludingInclusiveAncestor,
  18. substringData,
  19. BoundaryPoint,
  20. } from './whatwg-dom.js';
  21. import {
  22. languageOf,
  23. serializesAsVoid,
  24. isBeingRendered,
  25. } from './whatwg-html.js';
  26. import {
  27. htmlNamespace,
  28. } from './whatwg-infra.js';
  29. type nonEmptyString = string;
  30. type integer = number;
  31. // § 3.3.1. Parsing the fragment directive
  32. // https://wicg.github.io/scroll-to-text-fragment/#fragment-directive-delimiter
  33. // “The fragment directive delimiter is the string ":~:", that is the three consecutive code points U+003A (:), U+007E (~), U+003A (:).”
  34. export const fragmentDirectiveDelimiter = ':~:';
  35. // The function below implements most of the specified amendment to the ‘create and initialize a Document object’ steps. It applies the newly introduced steps on an ‘unmodified’ document. Instead of actually setting the document’s URL and fragment directive, it returns the values they should have obtained.
  36. // XXX Should the new procedure really “replace steps 7 and 8”? Which version of the HTML spec was this written for? In the version of 6 August 2020, steps 4, 5 and 9 seem more related.
  37. export function initializeDocumentFragmentDirective(document: Document): { documentUrl: string, documentFragmentDirective: string | null } {
  38. // We mock the document’s URL and the document’s fragment directive using plain variables.
  39. // As far as I can tell, we cannot access the document’s URL directly — only this serialised version (see <https://dom.spec.whatwg.org/#dom-document-url> as of 29 June 2020).
  40. let documentUrl: string = document.URL;
  41. // “Each document has an associated fragment directive which is either null or an ASCII string holding data used by the UA to process the resource. It is initially null.”
  42. let documentFragmentDirective: string | null = null;
  43. // 7. “Let url be null”
  44. let url: string | null = null;
  45. // XXX What is the idea of the new steps 8 and 9? These could at least use an explanatory note:
  46. // 8. “If request is non-null, then set document’s URL to request’s current URL.”
  47. // XXX should this perhaps be “url” instead of “document’s URL”? Otherwise we ignore the fragment directive completely.
  48. // 9. “Otherwise, set url to response’s URL.”
  49. // XXX should be “navigationParams's response”? Also, note its URL could be null.
  50. // In any case, we deviate from the spec in these steps, to allow testing this implementation without access to the request and response. We just take the document’s URL instead.
  51. url = documentUrl;
  52. // 10. “Let raw fragment be equal to url’s fragment.”
  53. // (as we only have access to the serialised URL, we extract the fragment again)
  54. const rawFragment = url.split('#')[1] ?? null;
  55. // XXX The spec seems to neglect that a URL’s fragment can be null (or is it somehow guaranteed to be non-null?). If it is null, I suppose we should skip the subsequent steps.
  56. if (rawFragment !== null) {
  57. // (a sane implementation would simply use rawFragment.indexOf(…) or rawFragment.split(…) instead the steps below)
  58. // 11. “Let fragmentDirectivePosition be an integer initialized to 0.”
  59. let fragmentDirectivePosition = 0;
  60. // 12. “While the substring of raw fragment starting at position fragmentDirectivePosition does not begin with the fragment directive delimiter and fragmentDirectivePosition does not point past the end of raw fragment:”
  61. while (
  62. !rawFragment.substring(fragmentDirectivePosition).startsWith(fragmentDirectiveDelimiter)
  63. && !(fragmentDirectivePosition >= rawFragment.length)
  64. ) {
  65. // 1. “Increment fragmentDirectivePosition by 1.”
  66. fragmentDirectivePosition += 1;
  67. }
  68. // 13. “If fragmentDirectivePosition does not point past the end of raw fragment:”
  69. if (!(fragmentDirectivePosition >= rawFragment.length)) {
  70. // 1. “Let fragment be the substring of raw fragment starting at 0 of count fragmentDirectivePosition.”
  71. const fragment = rawFragment.substring(0, 0 + fragmentDirectivePosition);
  72. // 2. “Advance fragmentDirectivePosition by the length of fragment directive delimiter.”
  73. fragmentDirectivePosition += fragmentDirectiveDelimiter.length;
  74. // 3. “Let fragment directive be the substring of raw fragment starting at fragmentDirectivePosition.”
  75. const fragmentDirective = rawFragment.substring(fragmentDirectivePosition);
  76. // 4. “Set url’s fragment to fragment.”
  77. // (as we only have access to the serialised URL, we manually replace its fragment part)
  78. url = url.split('#')[0] + (fragment !== null) ? '#' + fragment : '';
  79. // 5. “Set document’s fragment directive to fragment directive. (Note: this is stored on the document but not web-exposed)”
  80. documentFragmentDirective = fragmentDirective;
  81. }
  82. }
  83. // 14. “Set document’s URL to be url.”
  84. documentUrl = url;
  85. // For testing/trying purposes, we return what should now be the document’s URL and fragment directive.
  86. return { documentUrl, documentFragmentDirective };
  87. }
  88. // https://wicg.github.io/scroll-to-text-fragment/#parse-a-text-directive
  89. // “To parse a text directive, on a string textDirectiveString, run these steps:”
  90. export function parseTextDirective(textDirectiveInput: TextDirective): ParsedTextDirective | null { // XXX The spec writes “textDirectiveString” here, but probably meant “text directive input”.
  91. // 1. “Assert: textDirectiveString matches the production TextDirective.” XXX again, this should be “text directive input” (Note the 'TextDirective' subtype of string is intended to express this assertion)
  92. // assert(isTextFragmentDirective(textDirectiveInput));
  93. // 2. “Let textDirectiveString be the substring of text directive input starting at index 5.”
  94. const textDirectiveString = textDirectiveInput.substring(5);
  95. // 3. “Let tokens be a list of strings that is the result of splitting textDirectiveString on commas.”
  96. const tokens = textDirectiveString.split(',');
  97. // 4. “If tokens has size less than 1 or greater than 4, return null.”
  98. if (tokens.length < 1 || tokens.length > 4)
  99. return null;
  100. // 5. “If any of tokens’s items are the empty string, return null.”
  101. if (tokens.some(token => token === ''))
  102. return null;
  103. // 6. “Let retVal be a ParsedTextDirective with each of its items initialized to null.”
  104. const retVal: Partial<ParsedTextDirective> = {
  105. // XXX Initialising textStart to null would conflict with the type definition; hence using Partial<…> instead. Is this temporary type mismatch acceptable in the spec?
  106. textEnd: null,
  107. prefix: null,
  108. suffix: null,
  109. };
  110. // 7. “Let potential prefix be the first item of tokens.”
  111. const potentialPrefix = tokens[0];
  112. // 8. “If the last character of potential prefix is U+002D (-), then:”
  113. if (potentialPrefix.endsWith('-')) {
  114. // 1. “Set retVal’s prefix to the result of removing the last character from potential prefix.
  115. retVal.prefix = decodeURIComponent(potentialPrefix.substring(0, potentialPrefix.length - 1)); // XXX spec forgets “…the percent-decoding of…”
  116. // 2. “Remove the first item of the list tokens.”
  117. tokens.shift();
  118. }
  119. // 9. “Let potential suffix be the last item of tokens, if one exists, null otherwise.”
  120. const potentialSuffix = tokens[tokens.length - 1] ?? null;
  121. // 10. “If potential suffix is non-null and its first character is U+002D (-), then:”
  122. if (potentialSuffix !== null && potentialSuffix.startsWith('-')) {
  123. // 1. “Set retVal’s suffix to the result of removing the first character from potential suffix.”
  124. retVal.suffix = decodeURIComponent(potentialSuffix.substring(1)); // XXX spec forgets “…the percent-decoding of…”
  125. // 2. “Remove the last item of the list tokens.”
  126. tokens.pop();
  127. }
  128. // 11. “If tokens has size not equal to 1 nor 2 then return null.”
  129. if (tokens.length !== 1 && tokens.length !== 2)
  130. return null;
  131. // 12. “Set retVal’s textStart be the first item of tokens.”
  132. retVal.textStart = decodeURIComponent(tokens[0]); // XXX spec forgets “…the percent-decoding of…”
  133. // 13. “If tokens has size 2, then set retVal’s textEnd be the last item of tokens.”
  134. if (tokens.length === 2)
  135. retVal.textEnd = decodeURIComponent(tokens[tokens.length - 1]); // XXX spec forgets “…the percent-decoding of…”
  136. // 14. “Return retVal.”
  137. return retVal as ParsedTextDirective;
  138. }
  139. // https://wicg.github.io/scroll-to-text-fragment/#parsedtextdirective
  140. // “A ParsedTextDirective is a struct that consists of four strings: textStart, textEnd, prefix, and suffix. textStart is required to be non-null. The other three items may be set to null, indicating they weren’t provided. The empty string is not a valid value for any of these items.”
  141. export interface ParsedTextDirective {
  142. textStart: nonEmptyString;
  143. textEnd: nonEmptyString | null;
  144. prefix: nonEmptyString | null;
  145. suffix: nonEmptyString | null;
  146. };
  147. // § 3.3.2. Fragment directive grammar
  148. // https://wicg.github.io/scroll-to-text-fragment/#valid-fragment-directive
  149. // “A valid fragment directive is a sequence of characters that appears in the fragment directive that matches the production:”
  150. export type ValidFragmentDirective = string; // could be `unique string`, when (if) TypeScript will support that.
  151. export function isValidFragmentDirective(input: string | null): input is ValidFragmentDirective {
  152. // TODO (use PEG.js?)
  153. return true; // TEMP
  154. }
  155. // https://wicg.github.io/scroll-to-text-fragment/#text-fragment-directive
  156. // “The text fragment directive is one such fragment directive that enables specifying a piece of text on the page, that matches the production:”
  157. export type TextDirective = string; // could be `unique string`, when (if) TypeScript will support that.
  158. export function isTextFragmentDirective(input: string): input is TextDirective {
  159. // TODO (use PEG.js?)
  160. return input.startsWith('text='); // TEMP
  161. }
  162. // § 3.5. Navigating to a Text Fragment
  163. // https://wicg.github.io/scroll-to-text-fragment/#navigating-to-text-fragment
  164. // This implements the amended version of step 3 of the HTML spec’s “scroll to the fragment” steps: <https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier>
  165. export function scrollToTheFragment(indicatedPart: [Element, Range | null]): void {
  166. // (note that step 1 and 2 are irrelevant if the indicated part is an Element/Range, which we require here)
  167. // “Replace step 3.1 of the scroll to the fragment algorithm with the following:”
  168. // 3. “Otherwise:”
  169. // XXX this line above seems superfluous (and possibly confusing).
  170. // 1. (new) “Let target, range be the element and range that is the indicated part of the document.”
  171. const [target, range] = indicatedPart;
  172. // 2. (from original) “Set the Document's target element to target.”
  173. // TODO Perhaps we could fake this by applying any stylesheet rules for :target to target?
  174. // “Replace step 3.3 of the scroll to the fragment algorithm with the following:”
  175. // 3. (new) “Get the policy value for force-load-at-top in the Document. If the result is true, abort these steps.”
  176. // TODO (but this would require access to HTTP headers)
  177. // 4. (new) “If range is non-null:”
  178. if (range !== null) {
  179. // 1. “If the UA supports scrolling of text fragments on navigation, invoke Scroll range into view, with containingElement target, behavior set to "auto", block set to "center", and inline set to "nearest".”
  180. // XXX …and “with range range”?
  181. scrollRangeIntoView(range, target, { behavior: 'auto', block: 'center', inline: 'nearest' });
  182. }
  183. // 5. (new) “Otherwise:”
  184. else {
  185. // 1. (equals original step 3.3) “Scroll target into view, with behavior set to "auto", block set to "start", and inline set to "nearest".”
  186. scrollElementIntoView(target, 'auto', 'start', 'nearest');
  187. }
  188. }
  189. // “Add the following steps to the beginning of the processing model for the indicated part of the document:”
  190. // This function only implements the newly introduced steps. To help testing it out, its required inputs have to be passed as arguments, and the resulting indicated part (if any), is returned, along with the list of ranges (if any).
  191. export function indicatedPartOfTheDocument_beginning(
  192. { document, documentFragmentDirective, documentAllowTextFragmentDirective }:
  193. { document: Document, documentFragmentDirective: string | null, documentAllowTextFragmentDirective: boolean }
  194. ): { documentIndicatedPart: [Element, Range] | undefined, ranges?: Range[] } {
  195. let documentIndicatedPart: [Element, Range] | undefined = undefined;
  196. // 1. “Let fragment directive string be the document’s fragment directive.”
  197. const fragmentDirectiveString = documentFragmentDirective;
  198. // 2. “If the document’s allowTextFragmentDirective flag is true then:”
  199. if (documentAllowTextFragmentDirective === true) {
  200. // 1. “Let ranges be a list that is the result of running the process a fragment directive steps with fragment directive string and the document.”
  201. let ranges = processFragmentDirective(fragmentDirectiveString, document);
  202. // 2. “If ranges is non-empty, then:”
  203. if (ranges.length > 0) {
  204. // 1. “Let range be the first item of ranges.”
  205. const range = ranges[0];
  206. // 2. “Let node be the first common ancestor of range’s start node and start node.”
  207. // XXX This looks silly. Was “start node and end node” meant here?
  208. let node = firstCommonAncestor(range.startContainer, range.startContainer);
  209. // 3. “While node is not an element, set node to node’s parent.”
  210. // XXX Could loop forever! Or is it guaranteed that node has an element as ancestor? This may be a valid but fragile assumption.
  211. while (!isElement(node))
  212. node = node.parentNode as Node;
  213. // 4. “The indicated part of the document is node and range; return.”
  214. documentIndicatedPart = [node, range];
  215. // return;
  216. return { documentIndicatedPart, ranges }; // To allow testing it out.
  217. }
  218. }
  219. return { documentIndicatedPart };
  220. }
  221. // https://wicg.github.io/scroll-to-text-fragment/#first-common-ancestor
  222. // To find the first common ancestor of two nodes nodeA and nodeB, follow these steps:
  223. export function firstCommonAncestor(nodeA: Node, nodeB: Node): Node | never {
  224. // 1. “Let commonAncestor be nodeA.”
  225. let commonAncestor = nodeA;
  226. // 2. “While commonAncestor is not a shadow-including inclusive ancestor of nodeB, let commonAncestor be commonAncestor’s shadow-including parent.”
  227. // XXX If the nodes are not part of the same tree, this becomes an infinite loop! Should be “While commonAncestor is not null and …”
  228. while (!isShadowIncludingInclusiveAncestor(commonAncestor, /* of */ nodeB))
  229. commonAncestor = shadowIncludingParent(commonAncestor) as Node;
  230. // 3. “Return commonAncestor.”
  231. return commonAncestor;
  232. }
  233. // To find the shadow-including parent of node follow these steps:
  234. export function shadowIncludingParent(node: Node): Node | null {
  235. // 1. “If node is a shadow root, return node’s host.”
  236. if (node instanceof ShadowRoot)
  237. return node.host;
  238. // 2. “Otherwise, return node’s parent.”
  239. return node.parentNode;
  240. }
  241. // § 3.5.1. Scroll a DOMRect into view
  242. // https://wicg.github.io/scroll-to-text-fragment/#scroll-a-domrect-into-view
  243. // “Move the scroll an element into view algorithm’s steps 3-14 into a new algorithm scroll a DOMRect into view, with input DOMRect bounding box, ScrollIntoViewOptions dictionary options, and element startingElement.”
  244. // “Also move the recursive behavior described at the top of the scroll an element into view algorithm to the scroll a DOMRect into view algorithm: "run these steps for each ancestor element or viewport of startingElement that establishes a scrolling box scrolling box, in order of innermost to outermost scrolling box".”
  245. export function scrollDomRectIntoView(boundingBox: DOMRect, options: ScrollIntoViewOptions, startingElement: Element): void {
  246. // TODO Create/borrow a complete implementation.
  247. // TEMP assume the window is the only scrolling box, block=vertical and inline=horizontal, …
  248. function applyScrollLogicalPosition({
  249. position,
  250. boundingBoxRelativeEdgeBegin,
  251. boundingBoxRelativeEdgeEnd,
  252. boundingBoxSize,
  253. scrollBoxAbsoluteEdgeBegin,
  254. scrollBoxSize,
  255. }: {
  256. position: ScrollLogicalPosition,
  257. boundingBoxRelativeEdgeBegin: number,
  258. boundingBoxRelativeEdgeEnd: number,
  259. boundingBoxSize: number,
  260. scrollBoxAbsoluteEdgeBegin: number,
  261. scrollBoxSize: number,
  262. }): number | undefined {
  263. const boundingBoxAbsoluteEdgeBegin = scrollBoxAbsoluteEdgeBegin + boundingBoxRelativeEdgeBegin;
  264. const boundingBoxAbsoluteEdgeEnd = boundingBoxAbsoluteEdgeBegin + boundingBoxSize;
  265. boundingBoxRelativeEdgeEnd -= scrollBoxSize; // measure relative to scroll box’s end, not start.
  266. switch (position) {
  267. case 'start':
  268. return boundingBoxAbsoluteEdgeBegin;
  269. case 'end':
  270. return boundingBoxAbsoluteEdgeEnd - scrollBoxSize;
  271. case 'center':
  272. return boundingBoxAbsoluteEdgeBegin + boundingBoxSize / 2 - scrollBoxSize / 2;
  273. case 'nearest':
  274. const fitsInView = boundingBoxSize < scrollBoxSize; // XXX CSSWG spec seems to forget the case in which the sizes are equal. Here we interpret “greater than” as “greater than or equal to”.
  275. if (boundingBoxRelativeEdgeBegin < 0 && boundingBoxRelativeEdgeEnd > 0)
  276. return undefined;
  277. else if (boundingBoxRelativeEdgeBegin < 0 && fitsInView || boundingBoxRelativeEdgeEnd > 0 && !fitsInView)
  278. return boundingBoxAbsoluteEdgeBegin;
  279. else if (boundingBoxRelativeEdgeBegin < 0 && !fitsInView || boundingBoxRelativeEdgeEnd > 0 && fitsInView)
  280. return boundingBoxAbsoluteEdgeEnd - scrollBoxSize;
  281. }
  282. return undefined;
  283. }
  284. const top = applyScrollLogicalPosition({
  285. position: options.block ?? 'start', // presuming same default as for Element.scrollIntoView
  286. boundingBoxRelativeEdgeBegin: boundingBox.top,
  287. boundingBoxRelativeEdgeEnd: boundingBox.bottom,
  288. scrollBoxAbsoluteEdgeBegin: window.scrollY,
  289. boundingBoxSize: boundingBox.height,
  290. scrollBoxSize: document.documentElement.clientHeight,
  291. });
  292. const left = applyScrollLogicalPosition({
  293. position: options.inline ?? 'nearest', // presuming same default as for Element.scrollIntoView
  294. boundingBoxRelativeEdgeBegin: boundingBox.left,
  295. boundingBoxRelativeEdgeEnd: boundingBox.right,
  296. boundingBoxSize: boundingBox.width,
  297. scrollBoxAbsoluteEdgeBegin: window.scrollX,
  298. scrollBoxSize: document.documentElement.clientWidth,
  299. });
  300. window.scroll({ top, left, behavior: options.behavior });
  301. }
  302. // “Replace steps 3-14 of the scroll an element into view algorithm with a call to scroll a DOMRect into view:”
  303. // (note the recursive behaviour is already removed due to the lines above)
  304. // Basing on the <https://drafts.csswg.org/cssom-view-1/#scroll-an-element-into-view> version of 20 February 2020
  305. export function scrollElementIntoView(element: Element, behavior: ScrollBehavior, block: ScrollLogicalPosition, inline: ScrollLogicalPosition) {
  306. // 1. (from original) “If the Document associated with element is not same origin with the Document associated with the element or viewport associated with box, terminate these steps.”
  307. // TODO (if this makes sense here at all?)
  308. // 2. (from original) “Let element bounding border box be the box that the return value of invoking getBoundingClientRect() on element represents.”
  309. const elementBoundingBorderBox = element.getBoundingClientRect();
  310. // 3. (new) “Perform scroll a DOMRect into view given element bounding border box, options and element.”
  311. // XXX There is no “options” defined; presumably that should be { behavior, block, inline }.
  312. scrollDomRectIntoView(elementBoundingBorderBox, { behavior, block, inline }, element);
  313. }
  314. // https://wicg.github.io/scroll-to-text-fragment/#scroll-a-range-into-view
  315. // “Define a new algorithm scroll a Range into view, with input range range, element containingElement, and a ScrollIntoViewOptions dictionary options:”
  316. export function scrollRangeIntoView(range: Range, containingElement: Element, options: ScrollIntoViewOptions): void {
  317. // 1. “Let bounding rect be the DOMRect that is the return value of invoking getBoundingClientRect() on range.”
  318. const boundingRect = range.getBoundingClientRect();
  319. // 2. “Perform scroll a DOMRect into view given bounding rect, options, and containingElement.”
  320. scrollDomRectIntoView(boundingRect, options, containingElement);
  321. }
  322. // § 3.5.2 Finding Ranges in a Document
  323. // https://wicg.github.io/scroll-to-text-fragment/#process-a-fragment-directive
  324. export function processFragmentDirective(fragmentDirectiveInput: string | null, document: Document): Range[] {
  325. // 1. “If fragment directive input is not a valid fragment directive, then return an empty list.”
  326. if (!isValidFragmentDirective(fragmentDirectiveInput)) {
  327. return [];
  328. }
  329. // 2. “Let directives be a list of strings that is the result of strictly splitting the string fragment directive input on "&".”
  330. const directives = fragmentDirectiveInput.split('&');
  331. // 3. “Let ranges be a list of ranges, initially empty.”
  332. const ranges = [];
  333. // 4. “For each string directive of directives:”
  334. for (const directive of directives) {
  335. // 1. “If directive does not match the production TextDirective, then continue.”
  336. if (!isTextFragmentDirective(directive))
  337. continue;
  338. // 2. “Let parsedValues be the result of running the parse a text directive steps on directive.”
  339. const parsedValues = parseTextDirective(directive);
  340. // 3. “If parsedValues is null then continue.”
  341. if (parsedValues === null)
  342. continue;
  343. // 4. “If the result of running find a range from a text directive given parsedValues and document is non-null, then append it to ranges.”
  344. const range = findRangeFromTextDirective(parsedValues, document);
  345. if (range !== null)
  346. ranges.push(range);
  347. }
  348. // 5. “Return ranges.”
  349. return ranges;
  350. }
  351. // https://wicg.github.io/scroll-to-text-fragment/#find-a-range-from-a-text-directive
  352. // “To find a range from a text directive, given a ParsedTextDirective parsedValues and Document document, run the following steps:”
  353. export function findRangeFromTextDirective(parsedValues: ParsedTextDirective, document: Document): Range | null {
  354. // 1. “Let searchRange be a range with start (document, 0) and end (document, document’s length)”
  355. const searchRange = document.createRange();
  356. searchRange.setStart(document, 0);
  357. searchRange.setEnd(document, document.childNodes.length);
  358. // 2. “While searchRange is not collapsed:”
  359. while (!searchRange.collapsed) {
  360. // 1. “Let potentialMatch be null.”
  361. let potentialMatch = null;
  362. // 2. “If parsedValues’s prefix is not null:”
  363. if (parsedValues.prefix !== null) {
  364. // 1. “Let prefixMatch be the the result of running the find a string in range steps given parsedValues’s prefix and searchRange”.
  365. const prefixMatch = findStringInRange(parsedValues.prefix, searchRange);
  366. // 2. “If prefixMatch is null, return null.”
  367. if (prefixMatch === null)
  368. return null;
  369. // 3. “Set searchRange’s start to the first boundary point after prefixMatch’s start”
  370. // XXX I suppose we can be certain a next boundary point always exist in this case; can we proof this?
  371. searchRange.setStart(...firstBoundaryPointAfter(getStart(prefixMatch)) as BoundaryPoint);
  372. // 4. “Let matchRange be a range whose start is prefixMatch’s end and end is searchRange’s end.”
  373. const matchRange = document.createRange();
  374. matchRange.setStart(...getEnd(prefixMatch));
  375. matchRange.setEnd(...getEnd(searchRange));
  376. // 5. “Advance matchRange’s start to the next non-whitespace position.”
  377. advanceRangeStartToNextNonWhitespacePosition(matchRange);
  378. // 6. “If matchRange is collapsed return null.”
  379. if (matchRange.collapsed)
  380. return null;
  381. // 7. “Assert: matchRange’s start node is a Text node.”
  382. // assert(matchRange.startContainer.nodeType === Node.TEXT_NODE);
  383. // 8. “Set potentialMatch to the result of running the find a string in range steps given parsedValues’s textStart and matchRange.”
  384. potentialMatch = findStringInRange(parsedValues.textStart, matchRange);
  385. // 9. “If potentialMatch is null, return null.”
  386. if (potentialMatch === null)
  387. return null;
  388. // 10. “If potentialMatch’s start is not matchRange’s start, then and continue.” XXX then ~~and~~ continue
  389. if (!samePoint(getStart(potentialMatch), getStart(matchRange)))
  390. continue;
  391. // 11. “If parsedValues’s textEnd item is non-null, then:”
  392. // XXX This block of steps could be deduplicated by factoring it out of the if/else.
  393. if (parsedValues.textEnd !== null) {
  394. // 1. “Let textEndRange be a range whose start is potentialMatch’s end and whose end is searchRange’s end.”
  395. const textEndRange = document.createRange();
  396. textEndRange.setStart(...getEnd(potentialMatch));
  397. textEndRange.setEnd(...getEnd(searchRange));
  398. // 2. “Let textEndMatch be the result of running the find a string in range steps given parsedValue’s textEnd and textEndRange.”
  399. const textEndMatch = findStringInRange(parsedValues.textEnd, textEndRange);
  400. // 3. “If textEndMatch is null then return null.”
  401. if (textEndMatch === null)
  402. return null;
  403. // 4. “Set potentialMatch’s end to textEndMatch’s end.”
  404. potentialMatch.setEnd(...getEnd(textEndMatch));
  405. }
  406. }
  407. // 3. “Otherwise:”
  408. else {
  409. // 1. “Set potentialMatch to the result of running the find a string in range steps given parsedValues’s textStart and searchRange.”
  410. potentialMatch = findStringInRange(parsedValues.textStart, searchRange);
  411. // 2. “If potentialMatch is null, return null.”
  412. if (potentialMatch === null)
  413. return null;
  414. // 3. “Set searchRange’s start to the first boundary point after potentialMatch’s start”
  415. // XXX I suppose we can be certain a next boundary point always exist in this case; can we proof this?
  416. searchRange.setStart(...firstBoundaryPointAfter(getStart(potentialMatch)) as BoundaryPoint);
  417. // 4. “If parsedValues’s textEnd item is non-null, then:”
  418. // XXX This block of steps could be deduplicated by factoring it out of the if/else.
  419. if (parsedValues.textEnd !== null) {
  420. // 1. “Let textEndRange be a range whose start is potentialMatch’s end and whose end is searchRange’s end.”
  421. const textEndRange = document.createRange();
  422. textEndRange.setStart(...getEnd(potentialMatch));
  423. textEndRange.setEnd(...getEnd(searchRange));
  424. // 2. “Let textEndMatch be the result of running the find a string in range steps given parsedValue’s textEnd and textEndRange.”
  425. const textEndMatch = findStringInRange(parsedValues.textEnd, textEndRange);
  426. // 3. “If textEndMatch is null then return null.”
  427. if (textEndMatch === null)
  428. return null;
  429. // 4. “Set potentialMatch’s end to textEndMatch’s end.”
  430. potentialMatch.setEnd(...getEnd(textEndMatch));
  431. }
  432. }
  433. // 4. “Assert: potentialMatch is non-null, not collapsed and represents a range exactly containing an instance of matching text.” XXX the last assertion sounds rather vague.
  434. // assert(
  435. // potentialMatch !== null
  436. // && !potentialMatch.collapsed
  437. // && new RegExp('^' + escapeRegExp(textStart) + '.*' + escapeRegExp(textEnd) + '$').test(potentialMatch.toString()) // …or something similar?
  438. // );
  439. // 5. “If parsedValues’s suffix is null, return potentialMatch.”
  440. if (parsedValues.suffix === null)
  441. return potentialMatch;
  442. // 6. “Let suffixRange be a range with start equal to potentialMatch’s end and end equal to searchRange’s end.”
  443. const suffixRange = document.createRange();
  444. suffixRange.setStart(...getEnd(potentialMatch));
  445. suffixRange.setEnd(...getEnd(searchRange));
  446. // 7. “Advance suffixRange’s start to the next non-whitespace position.”
  447. advanceRangeStartToNextNonWhitespacePosition(suffixRange);
  448. // 8. “Let suffixMatch be result of running the find a string in range steps given parsedValues’s suffix and suffixRange.”
  449. const suffixMatch = findStringInRange(parsedValues.suffix, suffixRange);
  450. // 9. “If suffixMatch is null then return null.”
  451. if (suffixMatch === null)
  452. return null;
  453. // 10. “If suffixMatch’s start is suffixRange’s start, return potentialMatch.”
  454. if (samePoint(getStart(suffixMatch), getStart(suffixRange)))
  455. return potentialMatch;
  456. }
  457. // XXX Not in spec; by intention or accident?
  458. return null;
  459. }
  460. // https://wicg.github.io/scroll-to-text-fragment/#next-non-whitespace-position
  461. // “To advance a range range’s start to the next non-whitespace position follow the steps:”
  462. export function advanceRangeStartToNextNonWhitespacePosition(range: Range) {
  463. // 1. “While range is not collapsed:”
  464. while (!range.collapsed) {
  465. // 1. “Let node be range’s start node.”
  466. const node = range.startContainer;
  467. // 2. “Let offset be range’s start offset.”
  468. const offset = range.startOffset;
  469. // 3. “If node is part of a non-searchable subtree then:”
  470. if (partOfNonSearchableSubtree(node)) {
  471. // 1. “Set range’s start node to the next node, in shadow-including tree order, that isn’t a shadow-including descendant of node.”
  472. range.setStart(
  473. nextNodeInShadowIncludingTreeOrderThatIsNotAShadowIncludingDescendantOf(node) as Node, // XXX Can we be sure there is a next node? Asserting it here.
  474. 0, // XXX presumably we should set the offset to zero?
  475. );
  476. // 2. “Continue.”
  477. continue;
  478. }
  479. // 4. “If node is not a visible text node:”
  480. if (!isVisibleTextNode(node)) {
  481. // 1. “Set range’s start node to the next node, in shadow-including tree order.”
  482. range.setStart(
  483. nextNodeInShadowIncludingTreeOrder(node) as Node, // XXX Can we be sure there is a next node? Asserting it here.
  484. 0, // XXX presumably we should set the offset to zero?
  485. );
  486. // 2. “Continue.”
  487. continue;
  488. }
  489. // 5. “If the substring data of node at offset offset and count 6 is equal to the string "&nbsp;" then:” XXX Why only "&nbsp;", and not e.g. "&thinspace;" or others? Is there no existing spec for whitespace that can be used here?
  490. if (substringData(node as CharacterData, offset, 6) === '&nbsp;') { // XXX Is node guaranteed to be CharacterData? Not clear in spec.
  491. // 1. “Add 6 to range’s start offset.”
  492. range.setStart(range.startContainer, range.startOffset + 6);
  493. }
  494. // 6. “Otherwise, if the substring data of node at offset offset and count 5 is equal to the string "&nbsp" then:”
  495. else if (substringData(node as CharacterData, offset, 5) === '&nbsp') { // XXX Is node guaranteed to be CharacterData? Not clear in spec.
  496. // 1. “Add 5 to range’s start offset.”
  497. range.setStart(range.startContainer, range.startOffset + 5);
  498. }
  499. // 7. “Otherwise”
  500. else {
  501. // 1. “Let cp be the code point at the offset index in node’s data.”
  502. const cp = (node as CharacterData).data.codePointAt(offset) as number; // TODO verify if this is correct. We use the index to count code *units*, but we read the code *point*, which smells fishy but may be correct.
  503. // 2. “If cp does not have the White_Space property set, return.”
  504. if (!hasWhiteSpaceProperty(cp)) return;
  505. // 3. “Add 1 to range’s start offset.”
  506. range.setStart(range.startContainer, range.startOffset + 1);
  507. }
  508. // 8. “If range’s start offset is equal to node’s length, set range’s start node to the next node in shadow-including tree order.”
  509. if (range.startOffset === nodeLength(node)) {
  510. range.setStart(
  511. nextNodeInShadowIncludingTreeOrder(node) as Node, // XXX Can we be sure there is a next node? Asserting it here.
  512. 0, // XXX presumably we should set the offset to zero?
  513. );
  514. }
  515. }
  516. }
  517. // https://wicg.github.io/scroll-to-text-fragment/#find-a-string-in-range
  518. // To find a string in range for a string query in a given range range, run these steps:
  519. export function findStringInRange(query: string, searchRange: Range): Range | null { // XXX The spec calls it 'range' here, but 'searchRange' afterwards.
  520. // 1. “While searchRange is not collapsed:”
  521. while (!searchRange.collapsed) {
  522. // 1. “Let curNode be searchRange’s start node.”
  523. let curNode: Node | null = searchRange.startContainer;
  524. // 2. “If curNode is part of a non-searchable subtree:”
  525. if (partOfNonSearchableSubtree(curNode)) {
  526. // 1. “Set searchRange’s start node to the next node, in shadow-including tree order, that isn’t a shadow-including descendant of curNode”
  527. searchRange.setStart(
  528. nextNodeInShadowIncludingTreeOrderThatIsNotAShadowIncludingDescendantOf(curNode) as Node, // XXX Can we be sure there is a next node? Asserting it here.
  529. 0, // XXX presumably we should set the offset to zero?
  530. );
  531. // 2. “Continue.”
  532. continue;
  533. }
  534. // 3. “If curNode is not a visible text node:”
  535. if (!isVisibleTextNode(curNode)) {
  536. // 1. “Set searchRange’s start node to the next node, in shadow-including tree order.”
  537. // searchRange.setStart(
  538. // nextNodeInShadowIncludingTreeOrder(curNode) as Node, // XXX Can we be sure there is a next node? Asserting it here.
  539. // 0, // XXX presumably we should set the offset to zero?
  540. // );
  541. // XXX The above fails if nextNode is a doctype (see <https://dom.spec.whatwg.org/#concept-range-bp-set> as of 29 June 2020)
  542. // Take the next node that is not a doctype.
  543. curNode = nextNodeInShadowIncludingTreeOrder(curNode);
  544. while (curNode && curNode.nodeType === Node.DOCUMENT_TYPE_NODE)
  545. curNode = nextNodeInShadowIncludingTreeOrder(curNode);
  546. searchRange.setStart(
  547. curNode as Node, // XXX Can we be sure there is a next node? Asserting it here.
  548. 0, // XXX presumably we should set the offset to zero?
  549. );
  550. // 2. “Continue.”
  551. continue;
  552. }
  553. // 4. “Otherwise:” XXX unnecessary due to the 'continue' (and confusing after two 'if's, should the latter be 'else if'?)
  554. else {
  555. // 1. “Let blockAncestor be the nearest block ancestor of curNode.”
  556. const blockAncestor = nearestBlockAncestorOf(curNode);
  557. // 2. “Let textNodeList be a list of Text nodes, initially empty.”
  558. const textNodeList: Text[] = [];
  559. // 3. “While curNode is a shadow-including descendant of blockAncestor and it does not follow searchRange’s end node:”
  560. while (
  561. curNode && isShadowIncludingDescendant(curNode, /* of */ blockAncestor)
  562. // XXX “it does not follow searchRange’s end node” seems mistaken: *every* node follows Document, which is usually the end node…
  563. // && !followsInTree(curNode, searchRange.endContainer)
  564. // XXX …so we check instead whether curNode starts after searchRange.
  565. && searchRange.comparePoint(curNode, 0) !== 1
  566. ) {
  567. // 1. “If curNode has block-level display then break.”
  568. if (hasBlockLevelDisplay(curNode)) {
  569. break;
  570. }
  571. // 2. “If curNode is search invisible:”
  572. if (isSearchInvisible(curNode)) {
  573. // 1. “Set curNode to the next node in shadow-including tree order whose ancestor is not curNode.”
  574. // XXX Is this a *shadow-including* ancestor? Presumably yes, but making it explicit may be better.
  575. // XXX Two other places in the spec use the equivalent phrasing “that isn’t a shadow-including descendant of”. Best to then use the same phrasing here (or vice versa, but “whose ancestor” seems slightly less clear as it suggests there is only one ancestor).
  576. curNode = nextNodeInShadowIncludingTreeOrderThatIsNotAShadowIncludingDescendantOf(curNode);
  577. // 2. “Continue.”
  578. continue;
  579. }
  580. // 3. “If curNode is a visible text node then append it to textNodeList.”
  581. if (isVisibleTextNode(curNode)) {
  582. textNodeList.push(curNode);
  583. }
  584. // 4. “Set curNode to the next node in shadow-including tree order.”
  585. curNode = nextNodeInShadowIncludingTreeOrder(curNode);
  586. }
  587. // 4. “Run the find a range from a node list steps given query, searchRange, and textNodeList, as input. If the resulting range is not null, then return it.”
  588. const resultingRange = findARangeFromANodeList(query, searchRange, textNodeList);
  589. if (resultingRange !== null) {
  590. return resultingRange;
  591. }
  592. // XXX curNode may be null (if we reach the end of tree).
  593. if (curNode === null)
  594. break;
  595. // 5. “Assert: curNode follows searchRange’s start node.”
  596. // assert(followsInTree(curNode, searchRange.startContainer))
  597. // 6. “Set searchRange’s start to the boundary point (curNode, 0).”
  598. searchRange.setStart(curNode, 0);
  599. }
  600. }
  601. // 2. “Return null.”
  602. return null;
  603. }
  604. // https://wicg.github.io/scroll-to-text-fragment/#search-invisible
  605. // “A node is search invisible…”
  606. export function isSearchInvisible(node: Node): boolean {
  607. // “…if it is in the HTML namespace and meets any of the following conditions:”
  608. // XXX Namespace for nodes is inapplicable/deprecated? Presuming this was meant: “…if it is an element in the HTML namespace…”
  609. if (isElement(node) && node.namespaceURI === htmlNamespace) {
  610. // 1. “The computed value of its display property is none.”
  611. if (getComputedStyle(node).display === 'none')
  612. return true;
  613. // 2. “If the node serializes as void.”
  614. if (serializesAsVoid(node))
  615. return true;
  616. // 3. “Is any of the following types: HTMLIFrameElement, HTMLImageElement, HTMLMeterElement, HTMLObjectElement, HTMLProgressElement, HTMLStyleElement, HTMLScriptElement, HTMLVideoElement, HTMLAudioElement”
  617. if (['iframe', 'image', 'meter', 'object', 'progress', 'style', 'script', 'video', 'audio'].includes(node.localName)) // TODO verify: is this correct? Do class names and localName map one-to-one? (hopefully yes, as the term ‘element type’ seems used for both concepts)
  618. return true;
  619. // 4. “Is a select element whose multiple content attribute is absent.”
  620. if (node.localName === 'select' && !node.hasAttribute('multiple'))
  621. return true;
  622. }
  623. return false;
  624. }
  625. // https://wicg.github.io/scroll-to-text-fragment/#non-searchable-subtree
  626. // “A node is part of a non-searchable subtree if it is or has an ancestor that is search invisible.”
  627. export function partOfNonSearchableSubtree(node: Node): boolean {
  628. let curNode: Node | null = node;
  629. while (curNode) {
  630. if (isSearchInvisible(curNode))
  631. return true;
  632. curNode = curNode.parentNode; // XXX I would expect this to be “shadow-including ancestor”.
  633. // curNode = shadowIncludingParent(curNode);
  634. }
  635. return false;
  636. }
  637. // https://wicg.github.io/scroll-to-text-fragment/#visible-text-node
  638. // “A node is a visible text node if it is a Text node, the computed value of its visibility property is visible, and it is being rendered.”
  639. export type VisibleTextNode = Text; // could be `unique Text`, when (if) TypeScript will support that.
  640. export function isVisibleTextNode(node: Node): node is VisibleTextNode {
  641. if (node.nodeType !== Node.TEXT_NODE)
  642. return false;
  643. // XXX How are “the computed value of its visibility property” and “being rendered” defined for non-element nodes? Using the text node’s parent element instead!
  644. if (
  645. node.parentElement
  646. && getComputedStyle(node.parentElement).visibility === 'visible'
  647. && isBeingRendered(node.parentElement)
  648. )
  649. return true;
  650. return false;
  651. }
  652. // https://wicg.github.io/scroll-to-text-fragment/#has-block-level-display
  653. // “A node has block-level display if the computed value of its display property is any of block, table, flow-root, grid, flex, list-item.”
  654. export function hasBlockLevelDisplay(node: Node): boolean {
  655. // XXX How is “the computed value of its display property” defined for non-element nodes? Assuming here it only applies to elements!
  656. return (
  657. isElement(node)
  658. && ['block', 'table', 'flow-root', 'grid', 'flex', 'list-item'].includes(getComputedStyle(node).display)
  659. );
  660. }
  661. // https://wicg.github.io/scroll-to-text-fragment/#nearest-block-ancestor
  662. // “To find the nearest block ancestor of a node follow the steps:”
  663. export function nearestBlockAncestorOf(node: Node): Node {
  664. // 1. “While node is non-null”
  665. // XXX We replace node with a new variable curNode for walking up the tree, as we will still need a non-null node in step 2 (and also it needs the type Node | null).
  666. let curNode: Node | null = node;
  667. while (curNode !== null) {
  668. // 1. “If node is not a Text node and it has block-level display then return node.”
  669. if (curNode.nodeType !== Node.TEXT_NODE && hasBlockLevelDisplay(curNode))
  670. return curNode;
  671. // 2. “Otherwise, set node to node’s parent.”
  672. else
  673. curNode = curNode.parentNode;
  674. }
  675. // 2. “Return node’s node document's document element.”
  676. // XXX In the spec, node would be null now! Hence the need for introducing curNode.
  677. return (node.ownerDocument ?? node as Document).documentElement;
  678. }
  679. // https://wicg.github.io/scroll-to-text-fragment/#find-a-range-from-a-node-list
  680. // “To find a range from a node list given a search string queryString, a range searchRange, and a list of nodes nodes, follow the steps”
  681. export function findARangeFromANodeList(queryString: string, searchRange: Range, nodes: Text[]): Range | null {
  682. // 1. “Assert: each item in nodes is a Text node.”
  683. // XXX Could this not just be asserted through the parameter type, like is done in “get boundary point at index”? Applying this already.
  684. // assert(nodes.every(node => node.nodeType === Node.TEXT_NODE));
  685. // 2. “Let searchBuffer be the concatenation of the data of each item in in nodes.”
  686. // XXX typo: “in in nodes”
  687. const searchBuffer = nodes.map(node => node.data).join('');
  688. // 3. “Let searchStart be 0.”
  689. let searchStart = 0;
  690. // 4. “If the first item in nodes is searchRange’s start node then set searchStart to searchRange’s start offset.”
  691. if (nodes[0] === searchRange.startContainer)
  692. searchStart = searchRange.startOffset;
  693. // 5. “Let start and end be boundary points, initially null.”
  694. let start: BoundaryPoint | null = null;
  695. let end: BoundaryPoint | null = null;
  696. // 6. “Let matchIndex be null.”
  697. let matchIndex = null;
  698. // 7. “While matchIndex is null”
  699. while (matchIndex === null) {
  700. // 1. “Let matchIndex be an integer set to the index of the first instance of queryString in searchBuffer, starting at searchStart. The string search must be performed using a base character comparison, or the primary level, as defined in [UTS10].”
  701. // XXX “Let matchIndex be an integer” sounds like a redeclaration; presumably a mistake?
  702. // TODO implement base character comparison (i.e. ignoring accents, etc.)
  703. // XXX It would be helpful to have more specific guidance than merely a link to UTS10 <https://www.unicode.org/reports/tr10/tr10-43.html>
  704. matchIndex = searchBuffer.toLowerCase().indexOf(queryString.toLowerCase(), searchStart); // TEMP case-insensitive string match will have to suffice for now.
  705. // XXX If queryString does not appear in searchString, I suppose we should return.
  706. if (matchIndex === -1)
  707. return null;
  708. // 2. “Let endIx be matchIndex + queryString’s length.”
  709. const endIx = matchIndex + queryString.length;
  710. // 3. “Set start be the boundary point result of get boundary point at index matchIndex run over nodes with isEnd false.”
  711. // XXX typo: “Set start be”
  712. start = getBoundaryPointAtIndex(matchIndex, nodes, false) as BoundaryPoint;
  713. // 4. “Set end be the boundary point result of get boundary point at index endIx run over nodes with isEnd true.”
  714. // XXX typo: “Set end be”
  715. end = getBoundaryPointAtIndex(endIx, nodes, true) as BoundaryPoint;
  716. // XXX Assert start and end are non-null? (should be correct, as matchIndex and endIx are both less than the search text’s length)
  717. // 5. “If the substring of searchBuffer starting at matchIndex and of length queryString’s length is not word bounded, given the language from each of start and end’s nodes as the startLocale and endLocale:”
  718. if (!isWordBounded(searchBuffer, matchIndex, queryString.length, languageOf(start[0]), languageOf(end[0]))) {
  719. // 1. “Let searchStart be matchIndex + 1.”
  720. // XXX “Let … be” should be “Set … to”?
  721. searchStart = matchIndex + 1;
  722. // 2. “Set matchIndex to null.”
  723. matchIndex = null;
  724. }
  725. }
  726. // 8. “Let endInset be 0.”
  727. let endInset = 0;
  728. // 9. “If the last item in nodes is searchRange’s end node then set endInset to (searchRange’s end node's length − searchRange’s end offset)”
  729. if (nodes[nodes.length - 1] === searchRange.endContainer)
  730. endInset = (searchRange.endContainer as Text).length - searchRange.endOffset;
  731. // 10. “If matchIndex + queryString’s length is greater than or equal to searchBuffer’s length − endInset return null.”
  732. // XXX This comparison should be strictly greater than: a boundary point can be right after the last character.
  733. if (matchIndex + queryString.length > searchBuffer.length - endInset)
  734. return null;
  735. // 11. “Assert: start and end are non-null, valid boundary points in searchRange.”
  736. // assert(start !== null && end !== null && searchRange.comparePoint(...start) === 0 && searchRange.comparePoint(...end) === 0);
  737. start = start as BoundaryPoint;
  738. end = end as BoundaryPoint;
  739. // 12. “Return a range with start start and end end.”
  740. const result = document.createRange();
  741. result.setStart(...start);
  742. result.setEnd(...end);
  743. return result;
  744. }
  745. // https://wicg.github.io/scroll-to-text-fragment/#get-boundary-point-at-index
  746. // “To get boundary point at index, given an integer index, list of Text nodes nodes, and a boolean isEnd, follow these steps:”
  747. export function getBoundaryPointAtIndex(index: integer, nodes: Text[], isEnd: boolean): BoundaryPoint | null {
  748. // 1. “Let counted be 0.”
  749. let counted = 0;
  750. // 2. “For each curNode of nodes:”
  751. for (const curNode of nodes) {
  752. // 1. “Let nodeEnd be counted + curNode’s length.”
  753. let nodeEnd = counted + curNode.length;
  754. // 2. “If isEnd is true, add 1 to nodeEnd.”
  755. if (isEnd)
  756. nodeEnd += 1;
  757. // 3. “If nodeEnd is greater than index then:”
  758. if (nodeEnd > index) {
  759. // 1. “Return the boundary point (curNode, index − counted).”
  760. return [curNode, index - counted];
  761. }
  762. // 4. “Increment counted by curNode’s length.”
  763. counted += curNode.length;
  764. }
  765. // 3. “Return null.”
  766. return null;
  767. }
  768. // § 3.5.3 Word Boundaries
  769. // https://wicg.github.io/scroll-to-text-fragment/#word-bounded
  770. // “To determine if a substring of a larger string is word bounded, given a string text, an integer startPosition, number count, and locales startLocale and endLocale, follow these steps:”
  771. // “startLocale and endLocale must be a valid [BCP47] language tag, or the empty string. An empty string indicates that the primary language is unknown.” <https://tools.ietf.org/html/bcp47>
  772. // XXX Is this, or should this be a step? (should locale strings be validated?)
  773. export function isWordBounded(text: string, startPosition: integer, count: number, startLocale: locale, endLocale: locale): boolean {
  774. // 1. “Using locale startLocale, let left bound be the last word boundary in text that precedes startPositionth code point of text.”
  775. // XXX It seems that “startPositionth” involves zero-based indexing; is that considered self-evident?
  776. const leftBound = nearestWordBoundary(text, startPosition, 'before', startLocale);
  777. // “A string will always contain at least 2 word boundaries before the first code point and after the last code point of the string.
  778. // XXX Is this really true, even for a string with only white space? Or an empty string?
  779. // XXX typo: missing a colon before “before”
  780. // 2. “If the first code point of text following left bound is not at position startPosition return false.”
  781. if (leftBound !== startPosition) // We should be able to assume leftBound is not inside a multi-unit code point.
  782. return false;
  783. // 3. “Let endPosition be (startPosition + count − 1).”
  784. const endPosition = startPosition + count - 1;
  785. // 4. “Using locale endLocale, let right bound be the first word boundary in text after the endPositionth code point.”
  786. // XXX It seems that “endPositionth” involves zero-based indexing; is that considered self-evident?
  787. const rightBound = nearestWordBoundary(text, endPosition, 'after', endLocale);
  788. // 5. “If the first code point of text preceding right bound is not at position endPosition return false.”
  789. if (rightBound - 1 !== endPosition) // TEMP (TODO figure this out)
  790. return false;
  791. // 6. “Return true.”
  792. return true;
  793. }
  794. // https://wicg.github.io/scroll-to-text-fragment/#feature-detectability
  795. // § 3.8. Feature Detectability
  796. // “For feature detectability, we propose adding a new FragmentDirective interface that is exposed via document.fragmentDirective if the UA supports the feature.
  797. // [Exposed=Document]
  798. // interface FragmentDirective {
  799. // };
  800. // We amend the Document interface to include a fragmentDirective property:
  801. // partial interface Document {
  802. // [SameObject] readonly attribute FragmentDirective fragmentDirective;
  803. // };”
  804. export interface FragmentDirective {
  805. };
  806. // TODO Can and should we modify the Document interface?
  807. export function browserSupportsTextFragments(): boolean {
  808. return (
  809. 'fragmentDirective' in Document
  810. // Also check in window.location, which was in the spec until & including the version of 12 August 2020. See commit <https://github.com/WICG/scroll-to-text-fragment/commit/2dcfbd6e272f51e5b250c58076b6d1cc57656fce>.
  811. || 'fragmentDirective' in window.location
  812. );
  813. }
  814. //////////////////////////////////////
  815. /// Simple helpers for readability ///
  816. //////////////////////////////////////
  817. function getStart(range: Range): BoundaryPoint {
  818. return [range.startContainer, range.startOffset];
  819. }
  820. function getEnd(range: Range): BoundaryPoint {
  821. return [range.endContainer, range.endOffset];
  822. }
  823. function samePoint(point1: BoundaryPoint, point2: BoundaryPoint): boolean {
  824. return point1[0] === point2[0] && point1[1] === point2[1];
  825. }
  826. function nextNodeInShadowIncludingTreeOrderThatIsNotAShadowIncludingDescendantOf(node: Node): Node | null {
  827. let curNode: Node | null = nextNodeInShadowIncludingTreeOrder(node);
  828. while (curNode && isShadowIncludingDescendant(curNode, node)) {
  829. curNode = nextNodeInShadowIncludingTreeOrder(curNode);
  830. }
  831. return curNode;
  832. }
  833. ///////////
  834. // Other //
  835. ///////////
  836. function hasWhiteSpaceProperty(codePoint: number): boolean {
  837. // Soon to be widely supported in browsers. <https://caniuse.com/#feat=mdn-javascript_builtins_regexp_property_escapes>
  838. // return !!String.fromCodePoint(codePoint).match(/\p{White_Space}/u);
  839. // The list below takes the values from <https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt> version of 2019-11-27
  840. const whitespaceCodePoints = [
  841. 0x0009, 0x000A, 0x000B, 0x000C, 0x000D,
  842. 0x0085, 0x2028, 0x2029, 0x0020, 0x3000,
  843. 0x1680, 0x2000, 0x2001, 0x2002, 0x2003,
  844. 0x2004, 0x2005, 0x2006, 0x2008, 0x2009,
  845. 0x200A, 0x205F, 0x00A0, 0x2007, 0x202F,
  846. ];
  847. return whitespaceCodePoints.includes(codePoint);
  848. }
  849. // XXX Is this supposed to be self-evident, or should these steps perhaps be included in the spec?
  850. function firstBoundaryPointAfter([node, offset]: BoundaryPoint): BoundaryPoint | null {
  851. if (offset < nodeLength(node)) { // (note that N children/characters makes for N+1 boundary points)
  852. return [node, offset + 1];
  853. } else {
  854. const next = nextNode(node);
  855. if (next !== null)
  856. return [next, 0];
  857. else
  858. return null;
  859. }
  860. }
  861. // XXX Is this supposed to be self-evident, or should these steps perhaps be included in the spec?
  862. function nearestWordBoundary(text: string, position: integer, direction: 'before' | 'after', locale: locale): integer {
  863. // From <https://wicg.github.io/scroll-to-text-fragment/#word-bounded>:
  864. // “A word boundary is defined in [UAX29] in Unicode Text Segmentation §Word_Boundaries. Unicode Text Segmentation §Default_Word_Boundaries defines a default set of what constitutes a word boundary, but as the specification mentions, a more sophisticated algorithm should be used based on the locale.”
  865. // TODO Look into the referenced unicode spec.
  866. // TEMP Just use regular expression’s word boundaries, whitespace, and the string’s start and end.
  867. const allBoundaries = [...text.matchAll(/^|\b|\s|$/g)].map(match => match.index as integer);
  868. if (direction === 'before') {
  869. // Find the last match before position. Sure to exist because we also match the start of the string.
  870. allBoundaries.reverse();
  871. return allBoundaries.find(boundaryPosition => boundaryPosition <= position) as number;
  872. } else {
  873. // Find the first match after position. Sure to exist because we also match the end of the string.
  874. return allBoundaries.find(boundaryPosition => boundaryPosition > position) as number;
  875. }
  876. }