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

threadFind.ts

50 lines2.0 KB

1import type { OrchestrationV2SearchThreadInput, RunId } from "@t3tools/contracts";
2​
3export type ThreadFindStart = NonNullable<OrchestrationV2SearchThreadInput["start"]>;
4export type ThreadFindPositionReader = (query: string) => ThreadFindStart | undefined;
5​
6export interface ThreadFindMatch {
7 readonly entryId: string;
8 readonly runId: RunId | null;
9 readonly occurrence: number;
11​
12function clampThreadFindIndex(index: number, total: number): number {
13 if (total <= 0 || !Number.isFinite(index) || index < 0) return 0;
14 return Math.min(Math.trunc(index), total - 1);
16​
17export function stepThreadFindIndex(index: number, total: number, delta: number): number {
18 if (total <= 0) return 0;
19 const clamped = clampThreadFindIndex(index, total);
20 return (((clamped + delta) % total) + total) % total;
22​
23export function formatThreadFindCount(index: number, total: number): string {
24 return total <= 0 ? "0/0" : `${clampThreadFindIndex(index, total) + 1}/${total}`;
26​
27export interface ThreadFindAnnouncement {
28 readonly navigationId: number;
29 readonly text: string;
30 /** The label shows the outcome of `navigationId`: a count, a search or a failure. */
31 readonly settled: boolean;
32 /** "Searching…" or a failure: spoken, but a later count for the same navigation is too. */
33 readonly provisional: boolean;
35​
36/**
37 * What the find counter's live region says: the settled outcome of each
38 * user search or step, once. Background refreshes during streaming keep the
39 * navigation, so they stay silent. A new query passes through "Searching…",
40 * so its count is spoken even when it equals the last one.
41 */
42export function nextThreadFindAnnouncement(
43 previous: ThreadFindAnnouncement | null,
44 next: ThreadFindAnnouncement,
45): ThreadFindAnnouncement {
46 if (!next.settled) return previous ?? { ...next, text: "" };
47 if (previous?.navigationId !== next.navigationId) return next;
48 if (previous.settled && !previous.provisional) return previous;
49 return previous.text === next.text ? previous : next;