@remit/web-client 0.0.145 → 0.0.147

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.
@@ -1,12 +1,12 @@
1
1
  /**
2
- * BriefPane — compound component for the daily-brief view (/mail route).
2
+ * BriefPane — compound component for the daily brief.
3
3
  *
4
- * Usage in mail.tsx:
4
+ * Usage in the list layout route:
5
5
  *
6
- * <BriefPane selectedMessageId={...}>
7
- * <AppShellSlotted
6
+ * <BriefPane thread={useBriefThreadPath()}>
7
+ * <MailShell
8
8
  * list={<BriefPane.List />}
9
- * reading={<BriefPane.Reading />}
9
+ * reading={<Outlet />}
10
10
  * />
11
11
  * </BriefPane>
12
12
  *
@@ -14,13 +14,9 @@
14
14
  */
15
15
  import { unifiedThreadOperationsListAllThreadsOptions } from "@remit/api-http-client/@tanstack/react-query.gen.ts";
16
16
  import type { RemitImapThreadMessageResponse } from "@remit/api-http-client/types.gen.ts";
17
- import {
18
- ReadingPaneEmpty,
19
- type SearchResult,
20
- useAppShellLayout,
21
- } from "@remit/ui";
17
+ import { ReadingPaneEmpty, useAppShellLayout } from "@remit/ui";
22
18
  import { useQuery } from "@tanstack/react-query";
23
- import { useNavigate, useSearch } from "@tanstack/react-router";
19
+ import { useNavigate } from "@tanstack/react-router";
24
20
  import {
25
21
  createContext,
26
22
  type ReactNode,
@@ -37,32 +33,34 @@ import type { OpenMessageOptions } from "@/components/mail/ThreadListInteraction
37
33
  import { useDeleteMessages } from "@/hooks/useDeleteMessages";
38
34
  import { useToggleReadFor } from "@/hooks/useMarkAsRead";
39
35
  import { type ThreadActions, useThreadActions } from "@/hooks/useThreadActions";
36
+ import { useThreadRow } from "@/hooks/useThreadRow";
40
37
  import {
41
38
  type TriageContext,
42
39
  useTriageContext,
43
40
  useTriageLayer,
44
41
  } from "@/hooks/useTriageLayer";
45
- import {
46
- buildConversationTarget,
47
- type ConversationTarget,
48
- } from "@/lib/conversation-target";
42
+ import type { ConversationTarget } from "@/lib/conversation-target";
49
43
  import { useMailContext } from "@/lib/mail-context";
44
+ import type { BriefThreadPath, BriefThreadTarget } from "@/routing";
50
45
 
51
46
  /* ------------------------------------------------------------------ */
52
47
  /* Context */
53
48
  /* ------------------------------------------------------------------ */
54
49
 
55
50
  interface BriefPaneContextValue {
51
+ /** The row the reader pointed at, which is the one the list highlights. */
56
52
  selectedMessageId: string | undefined;
57
53
  selectedThread: RemitImapThreadMessageResponse | undefined;
58
- /** The conversation to open — the loaded thread, or a tapped "Related" hit. */
54
+ /** The conversation the pane shows, or none when the address names no thread. */
59
55
  conversation: ConversationTarget | undefined;
60
- onSelectMessage: (id: string, options?: OpenMessageOptions) => void;
61
- onSelectSearchResult: (
62
- result: SearchResult,
56
+ onOpenThread: (
57
+ target: BriefThreadTarget,
63
58
  options?: OpenMessageOptions,
64
59
  ) => void;
65
60
  onCloseThread: () => void;
61
+ /** The rows either side of the open one — the phone's swipe gestures. */
62
+ nextThread: BriefThreadTarget | undefined;
63
+ previousThread: BriefThreadTarget | undefined;
66
64
  /**
67
65
  * Toolbar verbs for the open thread, keyed by the thread's own mailbox and
68
66
  * account — the brief spans accounts, so there is no route mailbox to key by.
@@ -71,8 +69,6 @@ interface BriefPaneContextValue {
71
69
  /** Keyboard, multi-select and next/previous, shared with the mailbox view. */
72
70
  triage: TriageContext;
73
71
  onDeleteMessages: (messageIds: string[]) => void;
74
- nextMessageId: string | undefined;
75
- previousMessageId: string | undefined;
76
72
  /**
77
73
  * Deselects the open message when it's the one a mutation just removed
78
74
  * from view — wired into every mutation that can take the open message out
@@ -95,93 +91,79 @@ function useBriefPane(): BriefPaneContextValue {
95
91
  /* ------------------------------------------------------------------ */
96
92
 
97
93
  interface BriefPaneProps {
98
- selectedMessageId: string | undefined;
94
+ /** The open conversation, as the address states it. */
95
+ thread: BriefThreadPath | undefined;
99
96
  children: ReactNode;
100
97
  }
101
98
 
102
- function BriefPaneProvider({ selectedMessageId, children }: BriefPaneProps) {
99
+ function BriefPaneProvider({ thread, children }: BriefPaneProps) {
103
100
  const navigate = useNavigate();
104
101
  const { searchInput } = useMailContext();
105
- const { selectedThreadId, selectedMailboxId } = useSearch({
106
- strict: false,
107
- }) as { selectedThreadId?: string; selectedMailboxId?: string };
102
+ const threadId = thread?.threadId;
103
+ const pointedAtMessageId = thread?.messageId;
108
104
 
109
105
  const { data: threadsData } = useQuery({
110
106
  ...unifiedThreadOperationsListAllThreadsOptions(),
111
107
  staleTime: 60_000,
112
108
  });
109
+ const briefThreads = useMemo(() => threadsData?.items ?? [], [threadsData]);
113
110
 
114
- const selectedThread = useMemo(() => {
115
- if (!selectedMessageId) return undefined;
116
- return threadsData?.items.find((t) => t.messageId === selectedMessageId);
117
- }, [threadsData, selectedMessageId]);
118
-
119
- // A literal hit resolves to a loaded thread; a semantic "Related" hit may not
120
- // be in the capped brief list, so fall back to the thread + mailbox the hit
121
- // carried through the URL.
122
- const conversation = useMemo(
123
- () =>
124
- buildConversationTarget(selectedThread, {
125
- messageId: selectedMessageId,
126
- threadId: selectedThreadId,
127
- mailboxId: selectedMailboxId,
128
- }),
129
- [selectedThread, selectedMessageId, selectedThreadId, selectedMailboxId],
130
- );
131
-
132
- const handleSelectMessage = useCallback(
133
- (id: string, options?: OpenMessageOptions) => {
134
- navigate({
135
- to: "/mail/brief",
136
- search: (prev) => ({
137
- ...prev,
138
- selectedMessageId: id,
139
- selectedThreadId: undefined,
140
- selectedMailboxId: undefined,
141
- }),
142
- replace: options?.replace,
143
- });
144
- },
145
- [navigate],
146
- );
147
-
148
- const handleSelectSearchResult = useCallback(
149
- (result: SearchResult, options?: OpenMessageOptions) => {
111
+ // The row the brief itself lists, preferred because a mutation patches it in
112
+ // place. A thread reached from a cross-folder search hit or a cold address is
113
+ // in no listing here, and answers for itself — which is where
114
+ // `selectedMailboxId` used to come in: the folder a thread is filed in is the
115
+ // thread's own data, so the brief spanning folders costs the URL nothing.
116
+ const listedThread = useMemo(() => {
117
+ if (!threadId) return undefined;
118
+ return (
119
+ briefThreads.find((t) => t.messageId === pointedAtMessageId) ??
120
+ briefThreads.find((t) => t.threadId === threadId)
121
+ );
122
+ }, [briefThreads, threadId, pointedAtMessageId]);
123
+ const ownRow = useThreadRow(threadId, pointedAtMessageId);
124
+ const selectedThread = listedThread ?? ownRow;
125
+
126
+ const selectedMessageId = pointedAtMessageId ?? selectedThread?.messageId;
127
+
128
+ const conversation = useMemo<ConversationTarget | undefined>(() => {
129
+ if (!threadId) return undefined;
130
+ return {
131
+ threadId,
132
+ mailboxId: selectedThread?.mailboxId ?? "",
133
+ subject: selectedThread?.subject,
134
+ messageId: selectedMessageId,
135
+ authenticity: selectedThread?.authenticity,
136
+ };
137
+ }, [threadId, selectedThread, selectedMessageId]);
138
+
139
+ const handleOpenThread = useCallback(
140
+ (target: BriefThreadTarget, options?: OpenMessageOptions) => {
150
141
  navigate({
151
- to: "/mail/brief",
142
+ to: "/mail/brief/$threadId/$messageId",
143
+ params: target,
152
144
  replace: options?.replace,
153
- search: (prev) => ({
154
- ...prev,
155
- // Commit the active query with the selection so the debounced
156
- // q-mirror (`useSearchMirror`) which strips the selection when the query
157
- // goes active is already satisfied and leaves the opened result
158
- // alone. Use the *live* `searchInput`: the row can be tapped before
159
- // the debounce settles, when the committed query is still empty.
160
- q: searchInput || undefined,
161
- selectedMessageId: result.id,
162
- selectedThreadId: result.threadId,
163
- selectedMailboxId: result.mailboxId,
164
- }),
145
+ // Commit the active query with the open so the debounced q-mirror —
146
+ // which walks back up to the list when the query goes active — is
147
+ // already satisfied and leaves the conversation alone. The *live*
148
+ // `searchInput`: a row can be tapped before the debounce settles, when
149
+ // the committed query is still empty.
150
+ search: (prev) => ({ ...prev, q: searchInput || undefined }),
165
151
  });
166
152
  },
167
153
  [navigate, searchInput],
168
154
  );
169
155
 
156
+ const handleCloseThread = useCallback(() => {
157
+ navigate({ to: "/mail/brief", search: (prev) => prev });
158
+ }, [navigate]);
159
+
170
160
  const handleDeselectIfRemoved = useCallback(
171
161
  (removedIds: string[]) => {
172
162
  if (!selectedMessageId) return;
173
163
  if (!removedIds.includes(selectedMessageId)) return;
174
- navigate({
175
- to: "/mail/brief",
176
- search: (prev) => ({
177
- ...prev,
178
- selectedMessageId: undefined,
179
- selectedThreadId: undefined,
180
- selectedMailboxId: undefined,
181
- }),
182
- });
164
+ handleCloseThread();
183
165
  },
184
- [selectedMessageId, navigate],
166
+ [selectedMessageId, handleCloseThread],
185
167
  );
186
168
 
187
169
  const actions = useThreadActions({
@@ -189,24 +171,11 @@ function BriefPaneProvider({ selectedMessageId, children }: BriefPaneProps) {
189
171
  onAfterOptimisticRemove: handleDeselectIfRemoved,
190
172
  });
191
173
 
192
- const handleCloseThread = useCallback(() => {
193
- navigate({
194
- to: "/mail/brief",
195
- search: (prev) => ({
196
- ...prev,
197
- selectedMessageId: undefined,
198
- selectedThreadId: undefined,
199
- selectedMailboxId: undefined,
200
- }),
201
- });
202
- }, [navigate]);
203
-
204
174
  const triage = useTriageContext();
205
175
 
206
176
  // A brief selection spans accounts and mailboxes, so the listings these
207
177
  // patch are resolved from each message's own mailbox — the open thread's is
208
178
  // only the fallback.
209
- const briefThreads = useMemo(() => threadsData?.items ?? [], [threadsData]);
210
179
  const { deleteMessages } = useDeleteMessages({
211
180
  mailboxId: selectedThread?.mailboxId ?? "",
212
181
  messages: briefThreads,
@@ -219,8 +188,8 @@ function BriefPaneProvider({ selectedMessageId, children }: BriefPaneProps) {
219
188
 
220
189
  const focusedThreadId = triage.focusedMessageId;
221
190
  const focusedThread = useMemo(
222
- () => threadsData?.items.find((t) => t.messageId === focusedThreadId),
223
- [threadsData, focusedThreadId],
191
+ () => briefThreads.find((t) => t.messageId === focusedThreadId),
192
+ [briefThreads, focusedThreadId],
224
193
  );
225
194
  const triageTarget = focusedThread ?? selectedThread;
226
195
  const triageActions = useThreadActions({ thread: triageTarget });
@@ -252,18 +221,29 @@ function BriefPaneProvider({ selectedMessageId, children }: BriefPaneProps) {
252
221
  },
253
222
  });
254
223
 
224
+ // The swipe gestures open a whole conversation, so the adjacent row has to
225
+ // name its thread. The brief's own listing is where that is looked up, so a
226
+ // row it does not hold offers no gesture rather than a tap that goes nowhere.
227
+ const adjacentThread = useCallback(
228
+ (messageId: string | undefined): BriefThreadTarget | undefined => {
229
+ if (!messageId) return undefined;
230
+ const row = briefThreads.find((t) => t.messageId === messageId);
231
+ return row ? { threadId: row.threadId, messageId } : undefined;
232
+ },
233
+ [briefThreads],
234
+ );
235
+
255
236
  const ctx: BriefPaneContextValue = {
256
237
  selectedMessageId,
257
238
  selectedThread,
258
239
  conversation,
259
- onSelectMessage: handleSelectMessage,
260
- onSelectSearchResult: handleSelectSearchResult,
240
+ onOpenThread: handleOpenThread,
261
241
  onCloseThread: handleCloseThread,
242
+ nextThread: adjacentThread(nextMessageId),
243
+ previousThread: adjacentThread(previousMessageId),
262
244
  actions,
263
245
  triage,
264
246
  onDeleteMessages: deleteMessages,
265
- nextMessageId,
266
- previousMessageId,
267
247
  handleDeselectIfRemoved,
268
248
  };
269
249
 
@@ -278,21 +258,15 @@ function BriefPaneProvider({ selectedMessageId, children }: BriefPaneProps) {
278
258
  * Daily brief list. Mount in the `list` slot of `AppShellSlotted`.
279
259
  */
280
260
  function BriefList() {
281
- const {
282
- selectedMessageId,
283
- onSelectMessage,
284
- onSelectSearchResult,
285
- triage,
286
- onDeleteMessages,
287
- } = useBriefPane();
261
+ const { selectedMessageId, onOpenThread, triage, onDeleteMessages } =
262
+ useBriefPane();
288
263
  const { accounts } = useMailContext();
289
264
 
290
265
  return (
291
266
  <DailyBrief
292
267
  accounts={accounts}
293
268
  selectedMessageId={selectedMessageId}
294
- onSelectMessage={onSelectMessage}
295
- onSelectSearchResult={onSelectSearchResult}
269
+ onOpenThread={onOpenThread}
296
270
  commandsRef={triage.listCommandsRef}
297
271
  onTriageContextChange={triage.onTriageContextChange}
298
272
  onDeleteMessages={onDeleteMessages}
@@ -386,10 +360,10 @@ function BriefPhone() {
386
360
  const {
387
361
  selectedThread,
388
362
  conversation,
389
- onSelectMessage,
363
+ onOpenThread,
390
364
  onCloseThread,
391
- nextMessageId,
392
- previousMessageId,
365
+ nextThread,
366
+ previousThread,
393
367
  handleDeselectIfRemoved,
394
368
  } = useBriefPane();
395
369
  const { intelligenceOpen, onToggleIntelligence } = useMailContext();
@@ -405,13 +379,9 @@ function BriefPhone() {
405
379
  authenticity={conversation.authenticity}
406
380
  onBack={onCloseThread}
407
381
  onOpenIntelligence={onToggleIntelligence}
408
- onSwipeNext={
409
- nextMessageId ? () => onSelectMessage(nextMessageId) : undefined
410
- }
382
+ onSwipeNext={nextThread ? () => onOpenThread(nextThread) : undefined}
411
383
  onSwipePrevious={
412
- previousMessageId
413
- ? () => onSelectMessage(previousMessageId)
414
- : undefined
384
+ previousThread ? () => onOpenThread(previousThread) : undefined
415
385
  }
416
386
  mobileIntelligenceOpen={intelligenceOpen}
417
387
  />
@@ -105,6 +105,7 @@ import {
105
105
  type SelectionWizardControl,
106
106
  useSelectionWizard,
107
107
  } from "@/lib/wizard-history";
108
+ import type { BriefThreadTarget } from "@/routing";
108
109
  import { LabelApplyTrigger } from "./LabelApplyTrigger";
109
110
  import { MailListHeader, type MailListHeaderProps } from "./MailListHeader";
110
111
  import type { MessageListCommands } from "./MessageList";
@@ -378,14 +379,13 @@ function BriefSelectionChrome({
378
379
  interface DailyBriefProps {
379
380
  accounts: RemitImapAccountResponse[];
380
381
  selectedMessageId?: string;
381
- /** Opens an in-list brief row (resolved by messageId against the loaded list). */
382
- onSelectMessage?: (id: string, options?: OpenMessageOptions) => void;
383
382
  /**
384
- * Opens a search result. A semantic "Related" hit carries its thread + mailbox
385
- * so it opens even when its message isn't in the loaded brief list.
383
+ * Opens a row. Every row the brief renders names its thread, so the row the
384
+ * search widened in from another folder opens by exactly the same route as one
385
+ * from the unified inbox.
386
386
  */
387
- onSelectSearchResult?: (
388
- result: SearchResult,
387
+ onOpenThread?: (
388
+ target: BriefThreadTarget,
389
389
  options?: OpenMessageOptions,
390
390
  ) => void;
391
391
  /** Where the list publishes the commands the keyboard layer drives. */
@@ -398,8 +398,7 @@ interface DailyBriefProps {
398
398
  export function DailyBrief({
399
399
  accounts,
400
400
  selectedMessageId,
401
- onSelectMessage,
402
- onSelectSearchResult,
401
+ onOpenThread,
403
402
  commandsRef,
404
403
  onTriageContextChange,
405
404
  onDeleteMessages,
@@ -618,26 +617,29 @@ export function DailyBrief({
618
617
  );
619
618
 
620
619
  // A committed query puts rows the widened cross-folder search found into the
621
- // body, and those messages are in folders the brief itself never loads. The
622
- // reading pane resolves a bare `selectedMessageId` against the brief's own
623
- // thread list, so such a row opens nothing; it goes through the search path
624
- // instead, which carries the thread and mailbox the conversation is fetched
625
- // by (#635).
620
+ // body, and those messages are in folders the brief itself never loads. They
621
+ // open like any other row: what the address carries is the thread, which
622
+ // every row names, and the conversation is fetched by it (#635).
626
623
  const openRow = useCallback(
627
624
  (id: string, options?: OpenMessageOptions) => {
628
- const row = sq
629
- ? bodyRows.find((candidate) => candidate.id === id)
630
- : undefined;
631
- if (row?.threadId && row.mailboxId && onSelectSearchResult) {
632
- onSelectSearchResult(
633
- rowToSearchResult(row, resultFolderIndex),
634
- options,
635
- );
636
- return;
637
- }
638
- onSelectMessage?.(id, options);
625
+ const threadId = filteredRows.find((row) => row.id === id)?.threadId;
626
+ if (!threadId) return;
627
+ onOpenThread?.({ threadId, messageId: id }, options);
628
+ },
629
+ [filteredRows, onOpenThread],
630
+ );
631
+
632
+ // The two-engine results panel, whose semantic hits are in no list at all —
633
+ // each one carries the thread it belongs to.
634
+ const openResult = useCallback(
635
+ (result: SearchResult) => {
636
+ const threadId =
637
+ result.threadId ??
638
+ filteredRows.find((row) => row.id === result.id)?.threadId;
639
+ if (!threadId) return;
640
+ onOpenThread?.({ threadId, messageId: result.id });
639
641
  },
640
- [sq, bodyRows, resultFolderIndex, onSelectSearchResult, onSelectMessage],
642
+ [filteredRows, onOpenThread],
641
643
  );
642
644
 
643
645
  const accountSources = useMemo<FilterSheetSource[]>(() => {
@@ -903,7 +905,7 @@ export function DailyBrief({
903
905
  searchLoading: isLoading || searchFetching,
904
906
  relatedResults,
905
907
  relatedLoading,
906
- onSelectSearchResult,
908
+ onSelectSearchResult: openResult,
907
909
  // The body already narrows to the committed query
908
910
  // (`matchesBriefSearch` + `matchesSearchTokens` + the server `query`,
909
911
  // above), so a committed search is a selectable list here exactly as
@@ -229,7 +229,7 @@ export function MailSidebarAdapter({
229
229
  return (
230
230
  <NavLink
231
231
  to="/mail/brief"
232
- search={{ q: undefined, selectedMessageId: undefined }}
232
+ search={{ q: undefined }}
233
233
  activeOptions={{ includeSearch: false }}
234
234
  onClick={() => onClick?.()}
235
235
  className={className}
@@ -340,10 +340,7 @@ export function MailSidebarAdapter({
340
340
  const handleSelectSavedSearch = useCallback(
341
341
  (query: string) => {
342
342
  onSearchChange(query);
343
- navigate({
344
- to: "/mail/brief",
345
- search: { q: query, selectedMessageId: undefined },
346
- });
343
+ navigate({ to: "/mail/brief", search: { q: query } });
347
344
  onMailboxSelect?.();
348
345
  },
349
346
  [onSearchChange, navigate, onMailboxSelect],
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Where the search mirror writes, now that the brief's open thread is a path
3
+ * segment (#718).
4
+ *
5
+ * Mirroring `q` used to be one navigation with one destination, because the
6
+ * thread travelled in the query and `...prev` carried it along. It is now two:
7
+ * a query going active closes the reading pane, and that close is the address
8
+ * walking up to the list — while every other write has to keep the address it
9
+ * found, or clearing the search would shut the conversation being read.
10
+ *
11
+ * Driven through a real router over the brief's real route shape, because the
12
+ * whole question is what the router resolves a destination to from a thread
13
+ * route. Reasoning about `to: "."` is not evidence.
14
+ */
15
+
16
+ import assert from "node:assert/strict";
17
+ import { afterEach, describe, it } from "node:test";
18
+ import {
19
+ type AnyRouter,
20
+ createMemoryHistory,
21
+ createRootRoute,
22
+ createRoute,
23
+ createRouter,
24
+ Outlet,
25
+ RouterProvider,
26
+ } from "@tanstack/react-router";
27
+ import { createElement } from "react";
28
+ import { MailContext, type MailContextValue } from "@/lib/mail-context";
29
+ import { mailViewKey } from "@/lib/mail-route";
30
+ import { EMPTY_RESULT_FOLDER_INDEX } from "@/lib/result-folder";
31
+ import { createDomHarness, type DomHarness } from "../test-support/dom";
32
+ import { useSearchMirror } from "./useSearchMirror";
33
+
34
+ let harness: DomHarness | undefined;
35
+
36
+ afterEach(() => {
37
+ harness?.close();
38
+ harness = undefined;
39
+ });
40
+
41
+ // The router reads `self` at construction; the shared jsdom globals stop at
42
+ // `window`.
43
+ (globalThis as { self?: typeof globalThis }).self ??= globalThis;
44
+
45
+ const THREAD_ID = "th-1";
46
+ const MESSAGE_ID = "msg-1";
47
+
48
+ const mailContext = (input: string, committed: string): MailContextValue => ({
49
+ accounts: [],
50
+ mailboxNameIndex: new Map(),
51
+ accountNameIndex: new Map(),
52
+ resultFolderIndex: EMPTY_RESULT_FOLDER_INDEX,
53
+ searchQuery: committed,
54
+ searchInput: input,
55
+ searchViewKey: "/mail/brief",
56
+ onSearchChange: () => {},
57
+ onSearchClear: () => {},
58
+ onSearchClearQuery: () => {},
59
+ intelligenceOpen: false,
60
+ onToggleIntelligence: () => {},
61
+ onSetIntelligenceOpen: () => {},
62
+ });
63
+
64
+ /**
65
+ * The brief's shape: the list is a layout route and the thread and message are
66
+ * segments under it, so a write from the list has a matched child to lose.
67
+ */
68
+ const routerAt = (href: string): AnyRouter => {
69
+ const rootRoute = createRootRoute({ component: Outlet });
70
+ const passthrough = (search: Record<string, unknown>) => search;
71
+ const mailRoute = createRoute({
72
+ getParentRoute: () => rootRoute,
73
+ path: "/mail",
74
+ validateSearch: passthrough,
75
+ component: Outlet,
76
+ });
77
+ const briefRoute = createRoute({
78
+ getParentRoute: () => mailRoute,
79
+ path: "/brief",
80
+ validateSearch: passthrough,
81
+ component: () => {
82
+ useSearchMirror({ to: "/mail/brief" });
83
+ return createElement(Outlet);
84
+ },
85
+ });
86
+ const threadRoute = createRoute({
87
+ getParentRoute: () => briefRoute,
88
+ path: "/$threadId",
89
+ component: Outlet,
90
+ });
91
+ const messageRoute = createRoute({
92
+ getParentRoute: () => threadRoute,
93
+ path: "/$messageId",
94
+ component: () => null,
95
+ });
96
+ const routeTree = rootRoute.addChildren([
97
+ mailRoute.addChildren([
98
+ briefRoute.addChildren([threadRoute.addChildren([messageRoute])]),
99
+ ]),
100
+ ]);
101
+ return createRouter({
102
+ routeTree,
103
+ history: createMemoryHistory({ initialEntries: [href] }),
104
+ }) as unknown as AnyRouter;
105
+ };
106
+
107
+ const mount = async (
108
+ router: AnyRouter,
109
+ input: string,
110
+ committed: string,
111
+ ): Promise<DomHarness> => {
112
+ const created = createDomHarness();
113
+ harness = created;
114
+ await router.load();
115
+ created.renderApp(
116
+ createElement(
117
+ MailContext.Provider,
118
+ { value: mailContext(input, committed) },
119
+ createElement(RouterProvider, { router }),
120
+ ),
121
+ );
122
+ await created.flush();
123
+ await created.wait(20);
124
+ return created;
125
+ };
126
+
127
+ const threadHref = `/mail/brief/${THREAD_ID}/${MESSAGE_ID}`;
128
+
129
+ describe("mirroring a query that goes active", () => {
130
+ it("walks up to the list, so no thread stays matched behind the results", async () => {
131
+ const router = routerAt(threadHref);
132
+ await mount(router, "invoice", "invoice");
133
+
134
+ assert.equal(router.history.location.pathname, "/mail/brief");
135
+ assert.match(router.history.location.search, /q=invoice/);
136
+ });
137
+
138
+ it("closes the pane from a bare thread address too", async () => {
139
+ const router = routerAt(`/mail/brief/${THREAD_ID}`);
140
+ await mount(router, "invoice", "invoice");
141
+
142
+ assert.equal(router.history.location.pathname, "/mail/brief");
143
+ });
144
+
145
+ it("replaces rather than pushes, so Back is not a search step", async () => {
146
+ const router = routerAt(threadHref);
147
+ const before = router.history.length;
148
+ await mount(router, "invoice", "invoice");
149
+
150
+ assert.equal(router.history.length, before);
151
+ });
152
+ });
153
+
154
+ describe("mirroring a cleared query", () => {
155
+ it("keeps the conversation open — dropping the search is not closing it", async () => {
156
+ const router = routerAt(`${threadHref}?q=invoice`);
157
+ await mount(router, "", "");
158
+
159
+ assert.equal(router.history.location.pathname, threadHref);
160
+ assert.equal(router.history.location.search.includes("q="), false);
161
+ });
162
+
163
+ it("leaves the address alone when there is nothing to write", async () => {
164
+ const router = routerAt(`${threadHref}?q=invoice`);
165
+ await mount(router, "invoice", "invoice");
166
+
167
+ assert.equal(router.history.location.pathname, threadHref);
168
+ assert.match(router.history.location.search, /q=invoice/);
169
+ });
170
+
171
+ it("waits for the debounce rather than writing the previous query", async () => {
172
+ const router = routerAt(threadHref);
173
+ await mount(router, "invo", "");
174
+
175
+ assert.equal(router.history.location.pathname, threadHref);
176
+ assert.equal(router.history.location.search.includes("q="), false);
177
+ });
178
+ });
179
+
180
+ /**
181
+ * The other half of why a typed query survives an opened thread: the field
182
+ * re-seeds on a view change, so the view key of the list and of the thread route
183
+ * under it must be equal.
184
+ *
185
+ * Read off the matches the router resolved for a real address, so the ids under
186
+ * test are the ones path segments produce rather than ids written out here.
187
+ */
188
+ describe("the view key of an open brief thread", () => {
189
+ const viewKeyAt = async (href: string): Promise<string> => {
190
+ const router = routerAt(href);
191
+ await router.load();
192
+ return mailViewKey(
193
+ router.state.matches.map((match: { routeId: string }) => ({
194
+ routeId: match.routeId,
195
+ })),
196
+ );
197
+ };
198
+
199
+ it("is the brief's own, thread and message segments alike", async () => {
200
+ const list = await viewKeyAt("/mail/brief");
201
+ assert.notEqual(list, "", "the brief resolves to a view key at all");
202
+ assert.equal(await viewKeyAt(`/mail/brief/${THREAD_ID}`), list);
203
+ assert.equal(await viewKeyAt(threadHref), list);
204
+ });
205
+ });