Open History to see the last commit
1import type {
2 OrchestrationThreadSearchMatch,
3 OrchestrationV2SearchThreadResult,
4 ScopedThreadRef,
5} from "@t3tools/contracts";
6import { scopedThreadKey } from "@t3tools/client-runtime/environment";
7import {
8 findSearchTokenRanges,
9 messagePhrase,
10 messageSearchTokens,
11} from "@t3tools/shared/paletteSearch";
12import { create } from "zustand";
13import type { ThreadFindPositionReader, ThreadFindStart } from "./threadFind";
14
15export interface ThreadFindLocalSelection {
16 readonly base: OrchestrationV2SearchThreadResult;
17 readonly baseNavigationId: number;
18 readonly activeIndex: number;
19 readonly match: NonNullable<OrchestrationV2SearchThreadResult["match"]>;
20 readonly navigationId: number;
21}
22
23/** Find is open in at most one thread: the one the chat view shows. */
24export interface ThreadFindState {
25 readonly threadKey: string | null;
26 readonly query: string;
27 readonly offset: number;
28 readonly start: ThreadFindStart | undefined;
29 readonly focusRequestId: number;
30 readonly navigationId: number;
31 readonly requestId: number;
32 readonly localSelection: ThreadFindLocalSelection | null;
33}
34
35export const CLOSED_THREAD_FIND: ThreadFindState = {
36 threadKey: null,
37 query: "",
38 offset: 0,
39 start: undefined,
40 focusRequestId: 0,
41 navigationId: 0,
42 requestId: 0,
43 localSelection: null,
44};
45
46export const useThreadFindStore = create<ThreadFindState>(() => CLOSED_THREAD_FIND);
47
48/** What find needs from the timeline that shows a thread. */
49interface ThreadFindTimeline {
50 readonly threadKey: string;
51 readonly readPosition: ThreadFindPositionReader;
52}
53
54let attachedTimeline: ThreadFindTimeline | null = null;
55
56function timelineFor(threadKey: string): ThreadFindTimeline | null {
57 return attachedTimeline?.threadKey === threadKey ? attachedTimeline : null;
58}
59
60/** Attaches the timeline showing a thread; returns the detach. */
61export function attachThreadFindTimeline(timeline: ThreadFindTimeline): () => void {
62 attachedTimeline = timeline;
63 return () => {
64 if (attachedTimeline === timeline) attachedTimeline = null;
65 };
66}
67
68function readThreadFindPosition(threadKey: string, query: string): ThreadFindStart | undefined {
69 return timelineFor(threadKey)?.readPosition(query);
70}
71
72/** Opens find, or refocuses it and restarts its search from the viewport when already open. */
73export function openThreadFind(threadKey: string): void {
74 const previous = useThreadFindStore.getState();
75 const current = previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND;
76 const query = current.query.trim();
77 const start = query ? readThreadFindPosition(threadKey, query) : undefined;
78 useThreadFindStore.setState({
79 ...current,
80 threadKey,
81 focusRequestId: previous.focusRequestId + 1,
82 ...(query
83 ? {
84 start,
85 offset: 0,
86 localSelection: null,
87 navigationId: current.navigationId + 1,
88 requestId: current.navigationId + 1,
89 }
90 : {}),
91 });
92}
93
94export interface PendingThreadFind {
95 readonly query: string;
96 /** Where find starts, such as the message a palette result came from. */
97 readonly start?: ThreadFindStart;
98}
99
100/**
101 * Opens find on `query` in the thread, such as at the message a search result
102 * came from. The thread's view shows it once it is on screen.
103 */
104export function openThreadFindOnQuery(threadKey: string, find: PendingThreadFind): void {
105 const previous = useThreadFindStore.getState();
106 useThreadFindStore.setState({
107 ...(previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND),
108 threadKey,
109 query: find.query,
110 offset: 0,
111 start: find.start,
112 localSelection: null,
113 focusRequestId: previous.focusRequestId + 1,
114 navigationId: previous.navigationId + 1,
115 requestId: previous.navigationId + 1,
116 });
117}
118
119export function setThreadFindQuery(threadKey: string, query: string): void {
120 const start = readThreadFindPosition(threadKey, query.trim());
121 useThreadFindStore.setState((previous) => ({
122 query,
123 offset: 0,
124 start,
125 localSelection: null,
126 navigationId: previous.navigationId + 1,
127 requestId: previous.navigationId + 1,
128 }));
129}
130
131export function closeThreadFind(): void {
132 useThreadFindStore.setState(CLOSED_THREAD_FIND);
133}
134
135/**
136 * Find belongs to the thread it was opened in: a route showing anything else
137 * closes it. Settings and Usage draw over the thread, so they keep it.
138 */
139export function retainThreadFindForRoute(route: {
140 readonly modalPage: boolean;
141 readonly threadRef: ScopedThreadRef | null;
142}): void {
143 if (route.modalPage) return;
144 const { threadKey } = useThreadFindStore.getState();
145 const shownKey = route.threadRef ? scopedThreadKey(route.threadRef) : null;
146 if (threadKey !== null && threadKey !== shownKey) closeThreadFind();
147}
148
149/** Whether find is open in `thread`, as long as find is available there. */
150export function useThreadFindOpen(thread: ScopedThreadRef | null, enabled: boolean): boolean {
151 const openThreadKey = useThreadFindStore((state) => state.threadKey);
152 return enabled && thread !== null && openThreadKey === scopedThreadKey(thread);
153}
154
155/**
156 * The find a message search result opens, at the matched message: the whole
157 * query when the snippet holds it as typed ("vp run dev"), else its longest
158 * word, as the most telling ("sidebar" in "fix sidebar"), written as the
159 * snippet writes it ("Café" for "cafe", since find matches accents).
160 */
161export function findForMessageMatch(
162 match: Pick<OrchestrationThreadSearchMatch, "snippet" | "messageId">,
163 query: string,
164): PendingThreadFind {
165 const start = match.messageId ? { start: { entryId: match.messageId, occurrence: 0 } } : {};
166 // Apostrophes are straight in the query; straightening keeps offsets.
167 const together = messagePhrase(query)?.exec(match.snippet.replace(/[\u2018\u2019]/g, "'"));
168 if (together) {
169 return {
170 query: match.snippet.slice(together.index, together.index + together[0].length),
171 ...start,
172 };
173 }
174 const word =
175 messageSearchTokens(query).long.reduce(
176 (longest, token) => (token.length > longest.length ? token : longest),
177 "",
178 ) || query;
179 const ranges = findSearchTokenRanges(match.snippet, word);
180 // A whole word first, as search ranked it: "Café", not "Cafe" in "Cafeteria".
181 const shown =
182 ranges.find((range) => !/[\p{L}\p{N}]/u.test(match.snippet[range.end] ?? "")) ?? ranges[0];
183 return { query: shown ? match.snippet.slice(shown.start, shown.end) : word, ...start };
184}