Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

assistantCitationPosition.ts

35 lines1.3 KB

1import type { AssistantCitationSourceAnchor } from "./assistantTextSelection";
2​
3export function assistantCitationBounds({ viewport, boundary }: AssistantCitationSourceAnchor) {
4 const rect = (boundary ?? viewport).getBoundingClientRect();
5 const view = viewport.ownerDocument.defaultView!;
6 const left = Math.min(view.innerWidth, Math.max(0, rect.left));
7 const top = Math.min(view.innerHeight, Math.max(0, rect.top));
8 return new DOMRect(
9 left,
10 top,
11 Math.max(0, Math.min(view.innerWidth, rect.right) - left),
12 Math.max(0, Math.min(view.innerHeight, rect.bottom) - top),
13 );
15​
16export function assistantCitationAnchorRect(anchor: AssistantCitationSourceAnchor) {
17 const bounds = assistantCitationBounds(anchor);
18 const rect =
19 Array.from(anchor.range.getClientRects()).find(
20 (line) =>
21 line.bottom > bounds.top &&
22 line.top < bounds.bottom &&
23 line.right > bounds.left &&
24 line.left < bounds.right,
25 ) ?? anchor.range.getBoundingClientRect();
26 const source = anchor.source.getBoundingClientRect();
27 const left = Math.max(bounds.left, Math.min(source.left, bounds.right));
28 const right = Math.max(left, Math.min(source.right, bounds.right));
29 return new DOMRect(
30 Math.min(Math.max(rect.right, left), right),
31 Math.min(Math.max(rect.top, bounds.top), bounds.bottom),
32 0,
33 0,
34 );