@botiverse/porthole 0.14.8 → 0.14.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/annotate/types.d.ts +33 -2
  3. package/dist/annotate/validate.d.ts +6 -1
  4. package/dist/annotate/validate.js +31 -3
  5. package/dist/bridge/bridge.d.ts +6 -0
  6. package/dist/bridge/bridge.js +5 -0
  7. package/dist/check/page-source.js +1 -1
  8. package/dist/config/capabilities.d.ts +16 -2
  9. package/dist/config/capabilities.js +8 -0
  10. package/dist/conformance/harness-source.js +1 -1
  11. package/dist/find/types.d.ts +83 -0
  12. package/dist/find/types.js +29 -0
  13. package/dist/find/validate.d.ts +17 -0
  14. package/dist/find/validate.js +82 -0
  15. package/dist/guide/guide.js +2 -1
  16. package/dist/host/create-host.js +219 -3
  17. package/dist/host/pass-on.js +3 -2
  18. package/dist/host/types.d.ts +54 -1
  19. package/dist/index.d.ts +5 -3
  20. package/dist/index.js +4 -1
  21. package/dist/react/frame.d.ts +45 -1
  22. package/dist/react/frame.js +107 -3
  23. package/dist/react/view.js +2 -0
  24. package/dist/runtime/contract.d.ts +1 -1
  25. package/dist/runtime/contract.js +1 -1
  26. package/dist/shell/annotate.d.ts +5 -1
  27. package/dist/shell/annotate.js +41 -107
  28. package/dist/shell/document.d.ts +3 -3
  29. package/dist/shell/document.js +5 -3
  30. package/dist/shell/find.d.ts +82 -0
  31. package/dist/shell/find.js +725 -0
  32. package/dist/shell/runtime.js +4 -1
  33. package/dist/shell/text.d.ts +17 -0
  34. package/dist/shell/text.js +140 -0
  35. package/docs/ADOPTING.md +112 -0
  36. package/docs/ARCHITECTURE.md +10 -3
  37. package/docs/DECISIONS.md +284 -1
  38. package/docs/DESIGN.md +48 -2
  39. package/docs/THREAT_MODEL.md +61 -5
  40. package/docs/insertion-entry-points.md +17 -0
  41. package/package.json +1 -1
  42. package/src/annotate/types.ts +43 -4
  43. package/src/annotate/validate.ts +34 -3
  44. package/src/bridge/bridge.ts +7 -0
  45. package/src/config/capabilities.ts +13 -1
  46. package/src/find/types.ts +86 -0
  47. package/src/find/validate.ts +101 -0
  48. package/src/guide/guide.ts +3 -1
  49. package/src/host/create-host.ts +235 -3
  50. package/src/host/pass-on.ts +3 -2
  51. package/src/host/types.ts +55 -1
  52. package/src/index.ts +14 -1
  53. package/src/react/frame.tsx +162 -2
  54. package/src/react/view.tsx +3 -0
  55. package/src/runtime/contract.ts +1 -1
  56. package/src/shell/annotate.ts +42 -107
  57. package/src/shell/document.ts +5 -3
  58. package/src/shell/find.ts +731 -0
  59. package/src/shell/runtime.ts +4 -1
  60. package/src/shell/text.ts +140 -0
package/dist/index.d.ts CHANGED
@@ -46,6 +46,8 @@ export { lintFiles, type FileContents, type FileFinding } from "./check/files.ts
46
46
  export { admitContent, admitFiles, type AdmitFilesResult, answerGuide, checkTool, guideChanges, guideTool, guideTopics, showTool, type AdmitResult, type JsonSchema, type ToolDefinition, } from "./check/tools.ts";
47
47
  export { writeClipboard } from "./host/clipboard.ts";
48
48
  export { httpLocator, LocateError, servedOrOpaque, type HttpLocatorOptions, type ServedMeta, } from "./host/locator.ts";
49
- export type { AnnotationControls, DisplayControls, DisplayEvents, FrameBlock, FrameOutcome, DisplayHandle, HostOptions, MountOptions, PortholeHost, } from "./host/types.ts";
50
- export { ANNOTATE_METHODS, ANNOTATION_LIMITS, type AnchorResult, type AnchorState, type AnnotateMode, type AnnotationAnchor, type AnnotationMark, type AnnotationMarkKind, type AnnotationRect, type AnnotationReport, type AnnotationSelector, type CssSelector, type TextPositionSelector, type TextQuoteSelector, } from "./annotate/types.ts";
51
- export { parseAnchor, parseRect, parseReport } from "./annotate/validate.ts";
49
+ export type { AnnotationControls, FindControls, DisplayControls, DisplayEvents, FrameBlock, FrameOutcome, DisplayHandle, HostOptions, MountOptions, PortholeHost, } from "./host/types.ts";
50
+ export { ANNOTATE_METHODS, ANNOTATION_LIMITS, type AnchorResult, type AnchorState, type AnnotateMode, type AnnotationAnchor, type AnnotationMark, type AnnotationMarkKind, type AnnotationRect, type AnnotationReport, type AnnotationScroll, type AnnotationSelector, type CssSelector, type TextPositionSelector, type TextQuoteSelector, } from "./annotate/types.ts";
51
+ export { parseAnchor, parseRect, parseReport, parseScroll } from "./annotate/validate.ts";
52
+ export { FIND_LIMITS, FIND_METHODS, type FindDirection, type FindOptions, type FindReport, type FindResult, } from "./find/types.ts";
53
+ export { parseFindReport, parseFindResult } from "./find/validate.ts";
package/dist/index.js CHANGED
@@ -52,4 +52,7 @@ export { writeClipboard } from "./host/clipboard.js";
52
52
  export { httpLocator, LocateError, servedOrOpaque, } from "./host/locator.js";
53
53
  // Annotations (P053): anchors, what a frame reports, and the host's checks on both.
54
54
  export { ANNOTATE_METHODS, ANNOTATION_LIMITS, } from "./annotate/types.js";
55
- export { parseAnchor, parseRect, parseReport } from "./annotate/validate.js";
55
+ export { parseAnchor, parseRect, parseReport, parseScroll } from "./annotate/validate.js";
56
+ // Find in page (P131): the host's find bar, the frame's matches, and the host's checks on both.
57
+ export { FIND_LIMITS, FIND_METHODS, } from "./find/types.js";
58
+ export { parseFindReport, parseFindResult } from "./find/validate.js";
@@ -2,6 +2,7 @@ import type { PageDeclaration } from "../runtime/declaration.ts";
2
2
  import type { ViewerInfo } from "../runtime/levels.ts";
3
3
  import { type CSSProperties, type ReactElement, type ReactNode, type Ref } from "react";
4
4
  import type { AnnotateMode, AnnotationMark, AnnotationReport } from "../annotate/types.ts";
5
+ import type { FindOptions, FindResult } from "../find/types.ts";
5
6
  import type { CapabilityHandler, CapabilityHandlers, Confirm, ConfirmRequest, Consent, DataCache, Refusal, Show } from "../bridge/types.ts";
6
7
  import { Refused, type RefusalReason } from "../bridge/refusal.ts";
7
8
  import type { CapabilityName } from "../config/capabilities.ts";
@@ -153,7 +154,37 @@ export interface PortholeFrameHandle {
153
154
  * `"annotations"` (the core's call throws; this never does).
154
155
  */
155
156
  clearSelection(): void;
157
+ /**
158
+ * Finds `query` in the frame and highlights it (`find.query`, P131): where the matches stand,
159
+ * or `"unsupported"` (a config without `find`, an older shell, no answer in time, a later
160
+ * query superseded it, or no display running now). The query is kept for the content the frame
161
+ * shows now only: a display made later for the same content (the frame neared the screen again)
162
+ * finds it again and tells `onFindUpdated`; other content (another `content` that doesn't
163
+ * continue it, `document`, `instance`, `config`, `declaration` or `viewer`, a new `generation`)
164
+ * forgets it, and nothing is found there until `find` is called again (clear your find bar
165
+ * then). A query too long, or options that aren't these: `onHostError`, kind `"find"`, and
166
+ * `"unsupported"` (never a rejection). An empty query clears.
167
+ */
168
+ find(query: string, options?: FindOptions): Promise<FindResult | "unsupported">;
169
+ /** Removes the highlights and forgets the query (`find.clear`): the host's find bar closed. */
170
+ clearFind(): void;
171
+ }
172
+ /** What a frame shows, as its handle's query holds it (P131). */
173
+ export interface FindScope {
174
+ /** The config, instance (its version too), declaration, viewer and generation, by value. */
175
+ readonly shows: string;
176
+ readonly document: string | undefined;
177
+ readonly content: string | undefined;
156
178
  }
179
+ /** What the frame shows with these props, for its handle's query (P131). */
180
+ export declare function findScopeOf(props: PortholeFrameProps): FindScope;
181
+ /**
182
+ * Whether a frame showing `now` still shows what a query was asked of (`asked`, P131): the same
183
+ * config, instance, declaration, viewer, generation and document, and the content as it was or
184
+ * continued (more of a streamed page; asked before any content: whatever came). Otherwise the
185
+ * query was the last page's, and a new one is never searched with it.
186
+ */
187
+ export declare function sameFindScope(asked: FindScope, now: FindScope): boolean;
157
188
  export interface PortholeFrameProps {
158
189
  /** A preset's config. Keep it stable (module scope or memoized): a new one remounts the frame. */
159
190
  readonly config: PortholeConfig;
@@ -290,7 +321,8 @@ export interface PortholeFrameProps {
290
321
  } | null;
291
322
  /**
292
323
  * The mark to follow (`annotations.track`, P112, P118): while it moves, `onAnnotation` gets
293
- * `{ type: "tracked", id, rect }` at most once per animation frame, for it alone. `null` (or
324
+ * `{ type: "tracked", id, rect }` at most once per animation frame, for it alone (from a newer
325
+ * shell with its `documentRect` and the document's `scroll`, P132). `null` (or
294
326
  * leaving it out once set) stops. By value: given when it changes, and when the display is made.
295
327
  * Only a shown mark (`annotations`) is followed: another id, or a config without `annotate`, is
296
328
  * `onHostError` (kind `"annotations"`), as the core's call throws. `annotations` without it
@@ -305,6 +337,18 @@ export interface PortholeFrameProps {
305
337
  * (`activated`). The content's word: UI hints, never permissions.
306
338
  */
307
339
  readonly onAnnotation?: (report: AnnotationReport) => void;
340
+ /**
341
+ * The person pressed Cmd+F or Ctrl+F in the frame (`findRequested`, P131): open the host's find
342
+ * bar. Given, it makes the frame's shortcut the host's (`find.takeShortcut(true)`): the
343
+ * browser's own find doesn't open there. The content's word (it can say it, or keep the key):
344
+ * open the bar, nothing more. Where the config declares `find`.
345
+ */
346
+ readonly onFindRequested?: () => void;
347
+ /**
348
+ * The matches of the query shown changed without the host asking (`findUpdated`, P131): the
349
+ * content changed, or a display made later found the handle's query again.
350
+ */
351
+ readonly onFindUpdated?: (result: FindResult) => void;
308
352
  /** Draws the placeholder instead of the default one. */
309
353
  readonly renderPlaceholder?: (props: PlaceholderProps) => ReactNode;
310
354
  readonly className?: string;
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { createContext, useCallback, useContext, useEffect, useEffectEvent, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, } from "react";
3
+ import { blankQuery, checkFindQuery } from "../find/validate.js";
3
4
  import { isRefused, reasonOf, Refused } from "../bridge/refusal.js";
4
5
  import { writeClipboard } from "../host/clipboard.js";
5
6
  import { createHost } from "../host/create-host.js";
@@ -259,6 +260,32 @@ export function PortholeProvider(props) {
259
260
  void writeClipboard(failed.text, globalThis.document).then((copied) => setNotice({ ...failed, copied }));
260
261
  } }))] }));
261
262
  }
263
+ /** What the frame shows with these props, for its handle's query (P131). */
264
+ export function findScopeOf(props) {
265
+ return {
266
+ shows: JSON.stringify([
267
+ props.config,
268
+ props.instance ?? null,
269
+ props.declaration ?? null,
270
+ props.viewer ?? null,
271
+ props.generation ?? 0,
272
+ ]),
273
+ document: props.document,
274
+ content: props.content,
275
+ };
276
+ }
277
+ /**
278
+ * Whether a frame showing `now` still shows what a query was asked of (`asked`, P131): the same
279
+ * config, instance, declaration, viewer, generation and document, and the content as it was or
280
+ * continued (more of a streamed page; asked before any content: whatever came). Otherwise the
281
+ * query was the last page's, and a new one is never searched with it.
282
+ */
283
+ export function sameFindScope(asked, now) {
284
+ return (asked.shows === now.shows &&
285
+ asked.document === now.document &&
286
+ (asked.content === undefined ||
287
+ (now.content !== undefined && now.content.startsWith(asked.content))));
288
+ }
262
289
  const PLACEHOLDER_STYLE = {
263
290
  position: "absolute",
264
291
  inset: 0,
@@ -303,6 +330,18 @@ export function PortholeFrame(props) {
303
330
  useLayoutEffect(() => {
304
331
  own.current = props;
305
332
  });
333
+ // The query the handle last found (P131): a display made after it, for the same content, finds
334
+ // it again.
335
+ const findShown = useRef(null);
336
+ // The query kept for what a display shows (`scope`), else forgotten: null.
337
+ const findFor = useCallback((scope) => {
338
+ const kept = findShown.current;
339
+ if (kept !== null && !sameFindScope(kept.scope, scope)) {
340
+ findShown.current = null;
341
+ return null;
342
+ }
343
+ return kept;
344
+ }, []);
306
345
  useImperativeHandle(handleRef, () => ({
307
346
  clearSelection() {
308
347
  const now = display.current;
@@ -310,6 +349,33 @@ export function PortholeFrame(props) {
310
349
  attempt(() => now.annotations.clearSelection(), own.current);
311
350
  }
312
351
  },
352
+ find(query, options) {
353
+ try {
354
+ checkFindQuery(query, options);
355
+ }
356
+ catch (error) {
357
+ hostFailed(own.current, error, "find");
358
+ return Promise.resolve("unsupported");
359
+ }
360
+ findShown.current = blankQuery(query)
361
+ ? null
362
+ : {
363
+ query,
364
+ caseSensitive: options?.caseSensitive === true,
365
+ scope: findScopeOf(own.current),
366
+ };
367
+ const now = display.current;
368
+ return now === null
369
+ ? Promise.resolve("unsupported")
370
+ : now.find.query(query, options).catch((error) => {
371
+ hostFailed(own.current, error, "find");
372
+ return "unsupported";
373
+ });
374
+ },
375
+ clearFind() {
376
+ findShown.current = null;
377
+ display.current?.find.clear();
378
+ },
313
379
  }), []);
314
380
  useEffect(() => {
315
381
  const element = box.current;
@@ -361,10 +427,10 @@ export function PortholeFrame(props) {
361
427
  : {}),
362
428
  ...(state === "running" ? {} : { minHeight: Math.max(height, PLACEHOLDER_HEIGHT_PX) }),
363
429
  ...props.style,
364
- }, children: state === "running" ? (_jsx(Mount, { frame: props, page: page, running: running, initialHeightPx: height, placeholder: placeholder, run: run }, String(props.generation ?? 0))) : (placeholder({ state, title: props.title, run })) }));
430
+ }, children: state === "running" ? (_jsx(Mount, { frame: props, page: page, running: running, findFor: findFor, initialHeightPx: height, placeholder: placeholder, run: run }, String(props.generation ?? 0))) : (placeholder({ state, title: props.title, run })) }));
365
431
  }
366
432
  /** One running display: created when mounted, torn down when unmounted, fed as props change. */
367
- function Mount({ frame, page, running, initialHeightPx, placeholder, run, }) {
433
+ function Mount({ frame, page, running, findFor, initialHeightPx, placeholder, run, }) {
368
434
  const holder = useRef(null);
369
435
  const handle = useRef(null);
370
436
  // The mark the display follows now, as the core keeps it (P118), and the prop as last seen.
@@ -445,6 +511,12 @@ function Mount({ frame, page, running, initialHeightPx, placeholder, run, }) {
445
511
  case "annotation":
446
512
  frame.onAnnotation?.(detail);
447
513
  return;
514
+ case "findRequested":
515
+ frame.onFindRequested?.();
516
+ return;
517
+ case "findUpdated":
518
+ frame.onFindUpdated?.(detail);
519
+ return;
448
520
  }
449
521
  });
450
522
  useEffect(() => {
@@ -560,6 +632,8 @@ function Mount({ frame, page, running, initialHeightPx, placeholder, run, }) {
560
632
  "focusTaken",
561
633
  "outcome",
562
634
  "annotation",
635
+ "findRequested",
636
+ "findUpdated",
563
637
  "contentError",
564
638
  "hostError",
565
639
  ];
@@ -579,6 +653,22 @@ function Mount({ frame, page, running, initialHeightPx, placeholder, run, }) {
579
653
  following.current = wanted;
580
654
  }, first);
581
655
  }
656
+ // Find (P131): the shortcut is the host's where it listens for it; the handle's query, found
657
+ // again in this display where it shows what the query was asked of (its numbers told as an
658
+ // update: nobody awaits them), else forgotten: another page is never searched with it.
659
+ if (first.onFindRequested !== undefined) {
660
+ display.find.takeShortcut(true);
661
+ }
662
+ const shownQuery = findFor(findScopeOf(first));
663
+ if (shownQuery !== null) {
664
+ void display.find
665
+ .query(shownQuery.query, { caseSensitive: shownQuery.caseSensitive })
666
+ .then((result) => {
667
+ if (result !== "unsupported" && findFor(findScopeOf(latest())) === shownQuery) {
668
+ latest().onFindUpdated?.(result);
669
+ }
670
+ });
671
+ }
582
672
  if (first.content !== undefined) {
583
673
  display.setContent(first.content, { partial: first.partial === true });
584
674
  }
@@ -610,12 +700,16 @@ function Mount({ frame, page, running, initialHeightPx, placeholder, run, }) {
610
700
  locate,
611
701
  nonce,
612
702
  running,
703
+ findFor,
613
704
  ]);
614
705
  useEffect(() => {
615
706
  if (content !== undefined) {
616
707
  handle.current?.setContent(content, { partial: partial === true });
617
708
  }
618
- }, [content, partial]);
709
+ // Other content: the handle's query was the last one's, forgotten (the display forgot it too,
710
+ // P131).
711
+ findFor(findScopeOf(latest()));
712
+ }, [content, partial, findFor]);
619
713
  // Annotations follow their props (a new display gets them all when it is made, above).
620
714
  const annotates = config.capabilities.annotate !== undefined;
621
715
  const { annotating } = frame;
@@ -678,6 +772,16 @@ function Mount({ frame, page, running, initialHeightPx, placeholder, run, }) {
678
772
  attempt(() => display.annotations.focus(id), latest());
679
773
  }
680
774
  }, [annotates, focusToken]);
775
+ // The frame's shortcut is the host's while it listens for it (P131).
776
+ const takesFind = frame.onFindRequested !== undefined;
777
+ const [mountTakesFind] = useState(takesFind);
778
+ const findFlipped = useRef(false);
779
+ useEffect(() => {
780
+ if (findFlipped.current || takesFind !== mountTakesFind) {
781
+ findFlipped.current = true;
782
+ handle.current?.find.takeShortcut(takesFind);
783
+ }
784
+ }, [takesFind, mountTakesFind]);
681
785
  // A flip or a restyle after the display was made: its first scheme and values went with it.
682
786
  const [mountScheme] = useState(scheme);
683
787
  const flipped = useRef(false);
@@ -129,6 +129,8 @@ function InstanceView(props) {
129
129
  const shown = useRef(null);
130
130
  useImperativeHandle(ref, () => ({
131
131
  clearSelection: () => shown.current?.clearSelection(),
132
+ find: (query, options) => shown.current?.find(query, options) ?? Promise.resolve("unsupported"),
133
+ clearFind: () => shown.current?.clearFind(),
132
134
  }), []);
133
135
  const [failed, setFailed] = useState(null);
134
136
  const [generation, setGeneration] = useState(0);
@@ -152,7 +152,7 @@ export declare function runtimeCapability(name: RuntimeCapabilityName): RuntimeC
152
152
  export declare const RUNTIME_HOST_FUNCTIONS: readonly CapabilityName[];
153
153
  /**
154
154
  * Where a host function sits in the runtime: its capability and the methods it serves. Null for
155
- * the shell's own (`resize`, `reportError`, `annotate`), which content never calls by name.
155
+ * the shell's own (`resize`, `reportError`, `annotate`, `find`), which content never calls by name.
156
156
  */
157
157
  export declare function familyOf(serves: CapabilityName): {
158
158
  readonly name: RuntimeCapabilityName;
@@ -112,7 +112,7 @@ export const RUNTIME_HOST_FUNCTIONS = [
112
112
  ];
113
113
  /**
114
114
  * Where a host function sits in the runtime: its capability and the methods it serves. Null for
115
- * the shell's own (`resize`, `reportError`, `annotate`), which content never calls by name.
115
+ * the shell's own (`resize`, `reportError`, `annotate`, `find`), which content never calls by name.
116
116
  */
117
117
  export function familyOf(serves) {
118
118
  for (const name of RUNTIME_CAPABILITY_NAMES) {
@@ -30,7 +30,11 @@ export declare const MARKER_HIT: string;
30
30
  * bubble with no number, and has a marker with or without a count;
31
31
  * - following: while a mark has a marker, once a scroll, a resize or a change of the content
32
32
  * settles, the marks that moved since the host was last told are reported, at most once a
33
- * second, so the host's own UI beside a mark can follow.
33
+ * second, so the host's own UI beside a mark can follow;
34
+ * - places in the document (P132): each result's box also in the document's coordinates
35
+ * (`documentRect`), with how far the document was scrolled as it was read (`scroll`), and the
36
+ * followed mark's (`tracked`) too, so a host places marks scrolled out of the frame, and keeps
37
+ * them placed as the document scrolls, from one report and the followed mark's scroll.
34
38
  *
35
39
  * It shares the realm with the content, which can interfere with all of it: the host takes its
36
40
  * reports as UI hints only.
@@ -1,3 +1,4 @@
1
+ import { TEXT_INDEX } from "./text.js";
1
2
  /**
2
3
  * Which marker a press on the shell's layer is for (P119), spliced into the runtime: the index of
3
4
  * `count` boxes (`boxAt(i)`, the markers' own boxes in the viewport, the last drawn on top), or -1.
@@ -54,7 +55,11 @@ export const MARKER_HIT = String.raw `(count, boxAt, x, y, touch) => {
54
55
  * bubble with no number, and has a marker with or without a count;
55
56
  * - following: while a mark has a marker, once a scroll, a resize or a change of the content
56
57
  * settles, the marks that moved since the host was last told are reported, at most once a
57
- * second, so the host's own UI beside a mark can follow.
58
+ * second, so the host's own UI beside a mark can follow;
59
+ * - places in the document (P132): each result's box also in the document's coordinates
60
+ * (`documentRect`), with how far the document was scrolled as it was read (`scroll`), and the
61
+ * followed mark's (`tracked`) too, so a host places marks scrolled out of the frame, and keeps
62
+ * them placed as the document scrolls, from one report and the followed mark's scroll.
58
63
  *
59
64
  * It shares the realm with the content, which can interfere with all of it: the host takes its
60
65
  * reports as UI hints only.
@@ -106,101 +111,7 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
106
111
  const squash = (text) => String(text).replace(/\s+/g, " ").trim();
107
112
  const box = (rect) => ({ x: rect.left, y: rect.top, width: rect.width, height: rect.height });
108
113
 
109
- // The document's text: the body's text nodes in order, without scripts, styles, templates.
110
- const SKIPPED = { script: 1, style: 1, noscript: 1, template: 1 };
111
- const textIndex = () => {
112
- const nodes = [];
113
- const starts = [];
114
- const at = new Map();
115
- let text = "";
116
- const body = document.body;
117
- if (body) {
118
- const walker = createTreeWalker.call(document, body, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
119
- acceptNode: (node) => (node.nodeType === 1 ? (SKIPPED[node.localName] ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_SKIP) : NodeFilter.FILTER_ACCEPT),
120
- });
121
- for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
122
- at.set(node, nodes.length);
123
- nodes.push(node);
124
- starts.push(text.length);
125
- text += node.nodeValue;
126
- }
127
- }
128
- return { nodes, starts, at, text };
129
- };
130
- // A boundary point as an offset into the text: in a text node, where it is; elsewhere, the
131
- // first text at or after it.
132
- const offsetOf = (index, container, offset) => {
133
- if (container.nodeType === 3 && index.at.has(container)) {
134
- return index.starts[index.at.get(container)] + Math.min(offset, container.nodeValue.length);
135
- }
136
- const point = createRange.call(document);
137
- try {
138
- point.setStart(container, offset);
139
- } catch (_) {
140
- return index.text.length;
141
- }
142
- point.collapse(true);
143
- let low = 0;
144
- let high = index.nodes.length;
145
- while (low < high) {
146
- const middle = (low + high) >> 1;
147
- if (point.comparePoint(index.nodes[middle], 0) >= 0) {
148
- high = middle;
149
- } else {
150
- low = middle + 1;
151
- }
152
- }
153
- return low < index.nodes.length ? index.starts[low] : index.text.length;
154
- };
155
- const pointAt = (index, at, end) => {
156
- let low = 0;
157
- let high = index.nodes.length - 1;
158
- let found = -1;
159
- while (low <= high) {
160
- const middle = (low + high) >> 1;
161
- if (index.starts[middle] <= at) {
162
- found = middle;
163
- low = middle + 1;
164
- } else {
165
- high = middle - 1;
166
- }
167
- }
168
- if (found === -1) {
169
- return null;
170
- }
171
- let node = index.nodes[found];
172
- let offset = at - index.starts[found];
173
- if (end) {
174
- // An end at a node's very start belongs to the text before it.
175
- while (offset === 0 && found > 0) {
176
- found -= 1;
177
- node = index.nodes[found];
178
- offset = node.nodeValue.length;
179
- }
180
- } else {
181
- while (offset >= node.nodeValue.length && found + 1 < index.nodes.length) {
182
- found += 1;
183
- node = index.nodes[found];
184
- offset = 0;
185
- }
186
- }
187
- return { node, offset: Math.min(offset, node.nodeValue.length) };
188
- };
189
- const rangeAt = (index, start, end) => {
190
- const from = pointAt(index, start, false);
191
- const to = pointAt(index, end, true);
192
- if (from === null || to === null) {
193
- return null;
194
- }
195
- const range = createRange.call(document);
196
- try {
197
- range.setStart(from.node, from.offset);
198
- range.setEnd(to.node, to.offset);
199
- } catch (_) {
200
- return null;
201
- }
202
- return range;
203
- };
114
+ ${TEXT_INDEX}
204
115
  const spanOf = (index, node) => {
205
116
  const range = createRange.call(document);
206
117
  range.selectNodeContents(node);
@@ -397,6 +308,19 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
397
308
  return null;
398
309
  };
399
310
  const rectOf = (found) => (found.range ? rangeRect.call(found.range) : elementRect.call(found.element));
311
+ // How far the document is scrolled (P132): the top left of its root's box from the
312
+ // viewport's, negated, read with the DOM's own getBoundingClientRect (taken before content
313
+ // runs), never window.scrollY, which the content can replace. 0 - n: no -0 for a top at 0.
314
+ const scrollOf = () => {
315
+ const root = document.documentElement;
316
+ if (!root) {
317
+ return { x: 0, y: 0 };
318
+ }
319
+ const rect = elementRect.call(root);
320
+ return { x: 0 - rect.left, y: 0 - rect.top };
321
+ };
322
+ // A box in the viewport, in the document (P132): where it is as the document scrolls.
323
+ const inDocument = (rect, scroll) => ({ x: rect.x + scroll.x, y: rect.y + scroll.y, width: rect.width, height: rect.height });
400
324
 
401
325
  // The shell's own layer, over the content: marks, the outline of what would be picked.
402
326
  let layer = null;
@@ -890,7 +814,10 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
890
814
  if (apart(trackedBox, rect) && now - trackedAt >= 16) {
891
815
  trackedBox = rect;
892
816
  trackedAt = now;
893
- tell(M.tracked, { id: tracking, rect });
817
+ // Its box moves as the document scrolls, inside the frame or not: each one tells the
818
+ // host the scroll, for every mark it places by its place in the document (P132).
819
+ const scroll = scrollOf();
820
+ tell(M.tracked, { id: tracking, rect, documentRect: inDocument(rect, scroll), scroll });
894
821
  }
895
822
  }
896
823
  trackFrame = nextFrame(trackTick);
@@ -934,12 +861,15 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
934
861
  placed.forEach((each, at) => orders.set(each.mark, at));
935
862
  return orders;
936
863
  };
937
- const resultOf = (mark, orders) => {
864
+ // A mark's result: its box in the viewport, and in the document (P132) by scroll, the
865
+ // report's one reading of it.
866
+ const resultOf = (mark, orders, scroll) => {
938
867
  if (mark.found === null) {
939
868
  return { id: mark.id, state: "orphaned" };
940
869
  }
941
870
  const order = (orders || ordersOf()).get(mark);
942
- return Object.assign({ id: mark.id, state: "attached", rect: box(rectOf(mark.found)) }, order === undefined ? {} : { order });
871
+ const rect = box(rectOf(mark.found));
872
+ return Object.assign({ id: mark.id, state: "attached", rect, documentRect: inDocument(rect, scroll) }, order === undefined ? {} : { order });
943
873
  };
944
874
  // Two boxes more than 0.5 px apart on any side (or one of them unknown).
945
875
  const apart = (a, b) => !a || !b || Math.abs(a.x - b.x) > 0.5 || Math.abs(a.y - b.y) > 0.5 || Math.abs(a.width - b.width) > 0.5 || Math.abs(a.height - b.height) > 0.5;
@@ -951,17 +881,18 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
951
881
  }
952
882
  return result.state === "attached" && (apart(told.rect, result.rect) || told.order !== result.order);
953
883
  };
954
- const report = (pairs) => {
884
+ // With the scroll the results' document boxes were read at (P132).
885
+ const report = (pairs, scroll) => {
955
886
  if (pairs.length > 0) {
956
887
  for (const pair of pairs) {
957
888
  pair.mark.told = pair.result;
958
889
  }
959
- tell(M.anchored, { results: pairs.map((pair) => pair.result) });
890
+ tell(M.anchored, { results: pairs.map((pair) => pair.result), scroll });
960
891
  }
961
892
  };
962
- const resultsOf = (only) => {
893
+ const resultsOf = (only, scroll) => {
963
894
  const orders = ordersOf();
964
- return marks.map((mark) => ({ mark, result: resultOf(mark, orders) })).filter((pair) => !only || moved(pair.mark, pair.result));
895
+ return marks.map((mark) => ({ mark, result: resultOf(mark, orders, scroll) })).filter((pair) => !only || moved(pair.mark, pair.result));
965
896
  };
966
897
  // Finds every mark again; tells the host every result (after show, or when a state changed),
967
898
  // only the marks that moved (once the content is quiet), or nothing.
@@ -983,7 +914,8 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
983
914
  mark.state = state;
984
915
  }
985
916
  if (all || changed) {
986
- report(resultsOf(false));
917
+ const scroll = scrollOf();
918
+ report(resultsOf(false, scroll), scroll);
987
919
  } else if (quiet) {
988
920
  follow();
989
921
  }
@@ -1068,9 +1000,10 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
1068
1000
  const sendFollow = () => {
1069
1001
  let sent = 0;
1070
1002
  if (marks.length > 0 && !settling() && counted()) {
1071
- const pairs = resultsOf(true);
1003
+ const scroll = scrollOf();
1004
+ const pairs = resultsOf(true, scroll);
1072
1005
  if (pairs.length > 0) {
1073
- report(pairs);
1006
+ report(pairs, scroll);
1074
1007
  sent += 1;
1075
1008
  }
1076
1009
  }
@@ -1134,7 +1067,8 @@ export const ANNOTATE_RUNTIME = String.raw `if (declared("annotate")) {
1134
1067
  setTimeout(redraw, 1850);
1135
1068
  }
1136
1069
  draw();
1137
- report([{ mark, result: resultOf(mark) }]);
1070
+ const scroll = scrollOf();
1071
+ report([{ mark, result: resultOf(mark, null, scroll) }], scroll);
1138
1072
  };
1139
1073
 
1140
1074
  // A marker's click (P104). The layer takes no pointer but on its markers, so a press whose
@@ -62,9 +62,9 @@ export interface ShellDocumentOptions {
62
62
  * A given `document` travels in the runtime's plan, as data.
63
63
  */
64
64
  /**
65
- * The shell's runtime for a plan, before its plan goes in: annotations where declared, 0.6's
66
- * globals (the legacy path, P085) for what the config declares, and the capability runtime where
67
- * the config has one.
65
+ * The shell's runtime for a plan, before its plan goes in: annotations and find in page (P131)
66
+ * where declared, 0.6's globals (the legacy path, P085) for what the config declares, and the
67
+ * capability runtime where the config has one.
68
68
  */
69
69
  export declare function composedRuntime(plan: ShellPlan): string;
70
70
  export declare function shellDocument(plan: ShellPlan, csp: string, options: ShellDocumentOptions): string;
@@ -1,5 +1,6 @@
1
1
  import { hostOriginProblem } from "../isolation/served.js";
2
2
  import { ANNOTATE_RUNTIME } from "./annotate.js";
3
+ import { FIND_RUNTIME } from "./find.js";
3
4
  import { LEGACY_GLOBALS_RUNTIME } from "./legacy.js";
4
5
  import { SHELL_RUNTIME } from "./runtime.js";
5
6
  import { USE_RUNTIME } from "./use.js";
@@ -65,12 +66,13 @@ body {
65
66
  * A given `document` travels in the runtime's plan, as data.
66
67
  */
67
68
  /**
68
- * The shell's runtime for a plan, before its plan goes in: annotations where declared, 0.6's
69
- * globals (the legacy path, P085) for what the config declares, and the capability runtime where
70
- * the config has one.
69
+ * The shell's runtime for a plan, before its plan goes in: annotations and find in page (P131)
70
+ * where declared, 0.6's globals (the legacy path, P085) for what the config declares, and the
71
+ * capability runtime where the config has one.
71
72
  */
72
73
  export function composedRuntime(plan) {
73
74
  return SHELL_RUNTIME.replace("__ANNOTATE__", () => plan.capabilities.annotate === undefined ? "" : ANNOTATE_RUNTIME)
75
+ .replace("__FIND__", () => (plan.capabilities.find === undefined ? "" : FIND_RUNTIME))
74
76
  .replace("__LEGACY__", () => LEGACY_GLOBALS_RUNTIME)
75
77
  .replace("__RUNTIME__", () => (plan.runtime === undefined ? "" : USE_RUNTIME));
76
78
  }