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

threadFindStore.ts

210 lines7.5 KB

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