doccupine 0.0.140 → 0.0.142

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.
Files changed (145) hide show
  1. package/README.md +14 -7
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +191 -0
  4. package/dist/index.d.ts +3 -7
  5. package/dist/index.js +5 -1894
  6. package/dist/lib/config-manager.d.ts +1 -0
  7. package/dist/lib/config-manager.js +63 -3
  8. package/dist/lib/generated-artifacts.d.ts +26 -0
  9. package/dist/lib/generated-artifacts.js +147 -0
  10. package/dist/lib/layout.js +30 -30
  11. package/dist/lib/metadata.js +58 -30
  12. package/dist/lib/openapi-types.d.ts +2 -2
  13. package/dist/lib/openapi.d.ts +6 -3
  14. package/dist/lib/openapi.js +330 -50
  15. package/dist/lib/output-safety.d.ts +15 -0
  16. package/dist/lib/output-safety.js +428 -0
  17. package/dist/lib/structures.js +11 -0
  18. package/dist/lib/utils.d.ts +10 -5
  19. package/dist/lib/utils.js +108 -5
  20. package/dist/mdx-to-nextjs-generator.d.ts +166 -0
  21. package/dist/mdx-to-nextjs-generator.js +2229 -0
  22. package/dist/templates/app/api/gate/route.d.ts +1 -1
  23. package/dist/templates/app/api/gate/route.js +18 -6
  24. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  25. package/dist/templates/app/api/mcp/route.js +181 -111
  26. package/dist/templates/app/api/playground/route.d.ts +1 -1
  27. package/dist/templates/app/api/playground/route.js +45 -13
  28. package/dist/templates/app/api/rag/route.d.ts +1 -1
  29. package/dist/templates/app/api/rag/route.js +72 -20
  30. package/dist/templates/app/api/search/route.d.ts +1 -1
  31. package/dist/templates/app/api/search/route.js +5 -0
  32. package/dist/templates/app/robots.d.ts +1 -1
  33. package/dist/templates/app/robots.js +1 -26
  34. package/dist/templates/app/theme.d.ts +1 -1
  35. package/dist/templates/app/theme.js +31 -19
  36. package/dist/templates/components/Chat.d.ts +1 -1
  37. package/dist/templates/components/Chat.js +342 -34
  38. package/dist/templates/components/SearchDocs.d.ts +1 -1
  39. package/dist/templates/components/SearchDocs.js +63 -11
  40. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  41. package/dist/templates/components/SearchModalContent.js +191 -49
  42. package/dist/templates/components/SideBar.d.ts +1 -1
  43. package/dist/templates/components/SideBar.js +8 -2
  44. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  45. package/dist/templates/components/layout/Accordion.js +26 -3
  46. package/dist/templates/components/layout/Badge.d.ts +1 -1
  47. package/dist/templates/components/layout/Badge.js +1 -1
  48. package/dist/templates/components/layout/Button.d.ts +1 -1
  49. package/dist/templates/components/layout/Button.js +4 -4
  50. package/dist/templates/components/layout/Callout.d.ts +1 -1
  51. package/dist/templates/components/layout/Callout.js +6 -6
  52. package/dist/templates/components/layout/Card.d.ts +1 -1
  53. package/dist/templates/components/layout/Card.js +9 -4
  54. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  55. package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
  56. package/dist/templates/components/layout/Code.d.ts +1 -1
  57. package/dist/templates/components/layout/Code.js +5 -5
  58. package/dist/templates/components/layout/CopyButton.d.ts +1 -1
  59. package/dist/templates/components/layout/CopyButton.js +1 -1
  60. package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
  61. package/dist/templates/components/layout/DemoTheme.js +8 -28
  62. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  63. package/dist/templates/components/layout/DocsComponents.js +57 -6
  64. package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
  65. package/dist/templates/components/layout/GlobalStyles.js +15 -9
  66. package/dist/templates/components/layout/Prompt.d.ts +1 -1
  67. package/dist/templates/components/layout/Prompt.js +4 -7
  68. package/dist/templates/components/layout/Steps.d.ts +1 -1
  69. package/dist/templates/components/layout/Steps.js +7 -1
  70. package/dist/templates/components/layout/Tabs.d.ts +1 -1
  71. package/dist/templates/components/layout/Tabs.js +108 -19
  72. package/dist/templates/env.example.d.ts +1 -1
  73. package/dist/templates/env.example.js +11 -0
  74. package/dist/templates/eslint.config.d.ts +1 -1
  75. package/dist/templates/eslint.config.js +20 -0
  76. package/dist/templates/gitignore.d.ts +1 -1
  77. package/dist/templates/gitignore.js +4 -3
  78. package/dist/templates/lib/access.d.ts +1 -0
  79. package/dist/templates/lib/access.js +41 -0
  80. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  81. package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
  82. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  83. package/dist/templates/mdx/api-playground.mdx.js +5 -3
  84. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/authentication.mdx.js +5 -3
  86. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/commands.mdx.js +20 -6
  88. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/components.mdx.js +3 -0
  90. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
  92. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  93. package/dist/templates/mdx/globals.mdx.js +14 -11
  94. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
  96. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
  98. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
  100. package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
  101. package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
  102. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
  104. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  105. package/dist/templates/mdx/platform/index.mdx.js +1 -0
  106. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  107. package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
  108. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
  110. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
  112. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  113. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
  114. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/sections.mdx.js +4 -0
  116. package/dist/templates/mdx/space.mdx.d.ts +1 -0
  117. package/dist/templates/mdx/space.mdx.js +125 -0
  118. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/tabs.mdx.js +4 -0
  120. package/dist/templates/next.config.js +20 -8
  121. package/dist/templates/package.js +3 -3
  122. package/dist/templates/prettierignore.d.ts +1 -1
  123. package/dist/templates/prettierignore.js +1 -0
  124. package/dist/templates/proxy.js +47 -19
  125. package/dist/templates/scripts/build-docs-index.d.ts +1 -1
  126. package/dist/templates/scripts/build-docs-index.js +1 -0
  127. package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
  128. package/dist/templates/services/mcp/docsContentStub.js +1 -0
  129. package/dist/templates/services/mcp/server.d.ts +1 -1
  130. package/dist/templates/services/mcp/server.js +140 -83
  131. package/dist/templates/services/mcp/tools.d.ts +1 -1
  132. package/dist/templates/services/mcp/tools.js +65 -137
  133. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
  134. package/dist/templates/utils/playgroundAllowlist.js +13 -4
  135. package/dist/templates/utils/rateLimit.d.ts +1 -1
  136. package/dist/templates/utils/rateLimit.js +40 -3
  137. package/dist/templates/utils/requestBody.d.ts +1 -0
  138. package/dist/templates/utils/requestBody.js +56 -0
  139. package/dist/templates/utils/ssrfGuard.d.ts +1 -1
  140. package/dist/templates/utils/ssrfGuard.js +138 -33
  141. package/package.json +13 -5
  142. package/dist/lib/mdxToMarkdown.d.ts +0 -1
  143. package/dist/lib/mdxToMarkdown.js +0 -134
  144. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
  145. package/dist/templates/mdx/image-and-embeds.mdx.js +0 -118
@@ -5,8 +5,10 @@ import React, {
5
5
  useCallback,
6
6
  useContext,
7
7
  useEffect,
8
+ useLayoutEffect,
8
9
  useRef,
9
10
  useState,
11
+ useSyncExternalStore,
10
12
  } from "react";
11
13
  import styled, { css, keyframes } from "styled-components";
12
14
  import { Button, IconButton } from "cherry-styled-components";
@@ -16,7 +18,7 @@ import rehypeHighlight from "rehype-highlight";
16
18
  import { MDXRemote, MDXRemoteSerializeResult } from "next-mdx-remote";
17
19
  import { serialize } from "next-mdx-remote/serialize";
18
20
  import Link from "next/link";
19
- import { mq, Theme } from "@/app/theme";
21
+ import { mq, theme, Theme } from "@/app/theme";
20
22
  import { Callout } from "@/components/layout/Callout";
21
23
  import { useLockBodyScroll } from "@/components/LockBodyScroll";
22
24
  import { useMDXComponents as getMDXComponents } from "@/components/MDXComponents";
@@ -31,6 +33,26 @@ import {
31
33
 
32
34
  const mdxComponents = getMDXComponents({});
33
35
 
36
+ const MOBILE_CHAT_QUERY = \`(max-width: \${theme.breakpoints.lg - 1}px)\`;
37
+
38
+ function subscribeToMobileChat(callback: () => void) {
39
+ const mediaQuery = window.matchMedia(MOBILE_CHAT_QUERY);
40
+ mediaQuery.addEventListener("change", callback);
41
+ return () => mediaQuery.removeEventListener("change", callback);
42
+ }
43
+
44
+ function getMobileChatSnapshot() {
45
+ return window.matchMedia(MOBILE_CHAT_QUERY).matches;
46
+ }
47
+
48
+ function useIsMobileChat() {
49
+ return useSyncExternalStore(
50
+ subscribeToMobileChat,
51
+ getMobileChatSnapshot,
52
+ () => false,
53
+ );
54
+ }
55
+
34
56
  const styledText = css<{ theme: Theme }>\`
35
57
  font-size: \${({ theme }) => theme.fontSizes.text.xs};
36
58
  line-height: \${({ theme }) => theme.lineHeights.text.xs};
@@ -41,6 +63,27 @@ const styledText = css<{ theme: Theme }>\`
41
63
  }
42
64
  \`;
43
65
 
66
+ const StyledChatSurface = styled.div<{ $isVisible: boolean }>\`
67
+ position: fixed;
68
+ inset: 0;
69
+ z-index: 1000;
70
+ pointer-events: none;
71
+
72
+ & > * {
73
+ pointer-events: auto;
74
+ }
75
+
76
+ \${({ $isVisible }) =>
77
+ !$isVisible &&
78
+ css\`
79
+ visibility: hidden;
80
+
81
+ & > * {
82
+ pointer-events: none;
83
+ }
84
+ \`}
85
+ \`;
86
+
44
87
  const StyledChat = styled.div<{ theme: Theme; $isVisible: boolean }>\`
45
88
  margin: 0;
46
89
  position: fixed;
@@ -52,11 +95,17 @@ const StyledChat = styled.div<{ theme: Theme; $isVisible: boolean }>\`
52
95
  overflow-x: hidden;
53
96
  z-index: 1000;
54
97
  padding: 0 20px;
55
- transition: all 0.3s ease;
98
+ /* See StyledChatForm: visibility snaps open and is delayed on close, so the
99
+ panel is focusable as soon as it opens. */
100
+ transition:
101
+ transform 0.3s ease,
102
+ opacity 0.3s ease,
103
+ visibility 0s linear 0s;
56
104
  transform: translateX(0);
57
105
  background: \${({ theme }) => theme.colors.light};
58
106
  -webkit-overflow-scrolling: touch;
59
107
  opacity: 1;
108
+ visibility: visible;
60
109
 
61
110
  &::-webkit-scrollbar {
62
111
  display: none;
@@ -67,8 +116,14 @@ const StyledChat = styled.div<{ theme: Theme; $isVisible: boolean }>\`
67
116
  css\`
68
117
  transform: translateX(100%);
69
118
  opacity: 0;
119
+ visibility: hidden;
120
+ transition-delay: 0s, 0s, 0.3s;
70
121
  \`}
71
122
 
123
+ @media (prefers-reduced-motion: reduce) {
124
+ transition: none;
125
+ }
126
+
72
127
  \${mq("lg")} {
73
128
  width: ${CHAT_WIDTH}px;
74
129
  border-left: solid 1px \${({ theme }) => theme.colors.grayLight};
@@ -360,9 +415,17 @@ const StyledChatForm = styled.form<{ theme: Theme; $isVisible: boolean }>\`
360
415
  z-index: 1000;
361
416
  width: 100%;
362
417
  border-top: solid 1px \${({ theme }) => theme.colors.grayLight};
363
- transition: all 0.3s ease;
418
+ /* visibility is animatable, so transitioning "all" keeps this hidden for the
419
+ whole slide-in - long enough for the focus() that follows opening to be a
420
+ silent no-op. Snap it on open (transition-delay below) and delay it on
421
+ close so the slide-out stays visible while it animates. */
422
+ transition:
423
+ transform 0.3s ease,
424
+ opacity 0.3s ease,
425
+ visibility 0s linear 0.3s;
364
426
  transform: translateX(100%);
365
427
  opacity: 0;
428
+ visibility: hidden;
366
429
 
367
430
  \${mq("lg")} {
368
431
  width: ${CHAT_WIDTH}px;
@@ -374,8 +437,14 @@ const StyledChatForm = styled.form<{ theme: Theme; $isVisible: boolean }>\`
374
437
  css\`
375
438
  opacity: 1;
376
439
  transform: translateX(0);
440
+ visibility: visible;
441
+ transition-delay: 0s;
377
442
  \`}
378
443
 
444
+ @media (prefers-reduced-motion: reduce) {
445
+ transition: none;
446
+ }
447
+
379
448
  & .loading {
380
449
  animation: \${loadingAnimation} 1s linear infinite;
381
450
  }
@@ -792,23 +861,158 @@ function Chat() {
792
861
  resetChat,
793
862
  chatInputRef,
794
863
  } = useContext(ChatContext);
795
- const endRef = useRef<HTMLDivElement | null>(null);
864
+ const chatSurfaceRef = useRef<HTMLDivElement | null>(null);
865
+ const chatScrollRef = useRef<HTMLDivElement | null>(null);
866
+ const scrollFrameRef = useRef<number | null>(null);
867
+ const shouldAutoScrollRef = useRef(true);
868
+ const loadingRef = useRef(loading);
869
+ const isMobileChat = useIsMobileChat();
870
+ const isMobileModal = isOpen && isMobileChat;
796
871
 
797
872
  useLockBodyScroll(isOpen);
798
873
 
799
874
  useEffect(() => {
800
- endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
801
- }, [answer]);
875
+ loadingRef.current = loading;
876
+ }, [loading]);
877
+
878
+ useLayoutEffect(() => {
879
+ if (isOpen) {
880
+ shouldAutoScrollRef.current = true;
881
+ return;
882
+ }
883
+
884
+ if (scrollFrameRef.current !== null) {
885
+ cancelAnimationFrame(scrollFrameRef.current);
886
+ scrollFrameRef.current = null;
887
+ }
888
+ }, [isOpen]);
802
889
 
803
890
  useEffect(() => {
804
- if (answer?.length > 0) {
805
- chatInputRef.current?.focus();
891
+ if (!isOpen || !shouldAutoScrollRef.current) return;
892
+ if (scrollFrameRef.current !== null) return;
893
+
894
+ scrollFrameRef.current = requestAnimationFrame(() => {
895
+ scrollFrameRef.current = null;
896
+ const scrollContainer = chatScrollRef.current;
897
+ if (!scrollContainer || !shouldAutoScrollRef.current) return;
898
+ const reduceMotion = window.matchMedia(
899
+ "(prefers-reduced-motion: reduce)",
900
+ ).matches;
901
+ scrollContainer.scrollTo({
902
+ top: scrollContainer.scrollHeight,
903
+ behavior: reduceMotion || loadingRef.current ? "auto" : "smooth",
904
+ });
905
+ });
906
+ }, [answer, isOpen, loading]);
907
+
908
+ useEffect(() => {
909
+ return () => {
910
+ if (scrollFrameRef.current !== null) {
911
+ cancelAnimationFrame(scrollFrameRef.current);
912
+ }
913
+ };
914
+ }, []);
915
+
916
+ useEffect(() => {
917
+ if (!isMobileModal || !chatSurfaceRef.current) return;
918
+
919
+ const surface = chatSurfaceRef.current;
920
+ const inertSiblings: Array<{
921
+ element: HTMLElement;
922
+ wasInert: boolean;
923
+ }> = [];
924
+ let current: HTMLElement = surface;
925
+
926
+ while (current.parentElement) {
927
+ const parent = current.parentElement;
928
+ for (const sibling of Array.from(parent.children)) {
929
+ if (sibling === current || !(sibling instanceof HTMLElement)) continue;
930
+ inertSiblings.push({ element: sibling, wasInert: sibling.inert });
931
+ sibling.inert = true;
932
+ }
933
+ if (parent === document.body) break;
934
+ current = parent;
806
935
  }
807
- }, [answer, chatInputRef]);
936
+
937
+ const containFocus = (event: FocusEvent) => {
938
+ if (event.target instanceof Node && !surface.contains(event.target)) {
939
+ chatInputRef.current?.focus();
940
+ }
941
+ };
942
+
943
+ document.addEventListener("focusin", containFocus);
944
+ chatInputRef.current?.focus();
945
+
946
+ return () => {
947
+ document.removeEventListener("focusin", containFocus);
948
+ for (const { element, wasInert } of inertSiblings) {
949
+ element.inert = wasInert;
950
+ }
951
+ };
952
+ }, [chatInputRef, isMobileModal]);
953
+
954
+ const handleChatScroll = () => {
955
+ const scrollContainer = chatScrollRef.current;
956
+ if (!scrollContainer) return;
957
+ const distanceFromBottom =
958
+ scrollContainer.scrollHeight -
959
+ scrollContainer.scrollTop -
960
+ scrollContainer.clientHeight;
961
+ shouldAutoScrollRef.current =
962
+ distanceFromBottom <= scrollContainer.clientHeight * 0.15;
963
+ };
964
+
965
+ const handleSurfaceKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
966
+ if (event.key === "Escape" && isMobileModal) {
967
+ event.preventDefault();
968
+ event.stopPropagation();
969
+ closeChat();
970
+ return;
971
+ }
972
+
973
+ if (event.key !== "Tab" || !isMobileModal) return;
974
+ const focusable = Array.from(
975
+ chatSurfaceRef.current?.querySelectorAll<HTMLElement>(
976
+ 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])',
977
+ ) ?? [],
978
+ ).filter(
979
+ (element) =>
980
+ element.offsetParent !== null &&
981
+ element.getAttribute("aria-hidden") !== "true",
982
+ );
983
+ if (focusable.length === 0) {
984
+ event.preventDefault();
985
+ return;
986
+ }
987
+ const first = focusable[0];
988
+ const last = focusable[focusable.length - 1];
989
+ if (event.shiftKey && document.activeElement === first) {
990
+ event.preventDefault();
991
+ last.focus();
992
+ } else if (!event.shiftKey && document.activeElement === last) {
993
+ event.preventDefault();
994
+ first.focus();
995
+ }
996
+ };
808
997
 
809
998
  return (
810
- <>
811
- <StyledChat $isVisible={isOpen} data-markdown-ignore>
999
+ <StyledChatSurface
1000
+ ref={chatSurfaceRef}
1001
+ $isVisible={isOpen}
1002
+ inert={!isOpen}
1003
+ aria-hidden={!isOpen}
1004
+ role={isMobileModal ? "dialog" : "complementary"}
1005
+ aria-modal={isMobileModal ? "true" : undefined}
1006
+ aria-label="AI Assistant"
1007
+ data-chat-surface
1008
+ data-markdown-ignore
1009
+ onKeyDownCapture={handleSurfaceKeyDown}
1010
+ >
1011
+ <StyledChat
1012
+ ref={chatScrollRef}
1013
+ $isVisible={isOpen}
1014
+ onScroll={handleChatScroll}
1015
+ >
812
1016
  <StyledChatTitle>
813
1017
  <StyledChatTitleIconWrapper>
814
1018
  <Sparkles />
@@ -823,7 +1027,7 @@ function Chat() {
823
1027
  <RotateCcw />
824
1028
  </IconButton>
825
1029
  <IconButton
826
- onClick={closeChat}
1030
+ onClick={() => closeChat()}
827
1031
  aria-label="Close chat"
828
1032
  title="Close chat"
829
1033
  >
@@ -889,7 +1093,6 @@ function Chat() {
889
1093
  </Callout>
890
1094
  </StyledError>
891
1095
  )}
892
- <div ref={endRef} />
893
1096
  </StyledChat>
894
1097
 
895
1098
  <StyledChatForm onSubmit={ask} $isVisible={isOpen} data-markdown-ignore>
@@ -911,7 +1114,7 @@ function Chat() {
911
1114
  {loading ? <LoaderPinwheel className="loading" /> : <ArrowUp />}
912
1115
  </StyledRainbowButton>
913
1116
  </StyledChatForm>
914
- </>
1117
+ </StyledChatSurface>
915
1118
  );
916
1119
  }
917
1120
 
@@ -927,8 +1130,11 @@ const ChatContext = createContext<{
927
1130
  answer: Answer[];
928
1131
  setAnswer: (answers: Answer[]) => void;
929
1132
  ask: (e: React.FormEvent) => void;
930
- askAssistant: (question: string) => void;
931
- closeChat: () => void;
1133
+ askAssistant: (question: string, returnFocusTo?: HTMLElement | null) => void;
1134
+ closeChat: (restoreFocus?: boolean) => HTMLElement | null;
1135
+ registerSearchClose: (
1136
+ closeSearch: (restoreFocus?: boolean) => HTMLElement | null,
1137
+ ) => () => void;
932
1138
  resetChat: () => void;
933
1139
  chatInputRef: React.RefObject<HTMLInputElement | null>;
934
1140
  }>({
@@ -944,7 +1150,8 @@ const ChatContext = createContext<{
944
1150
  setAnswer: () => {},
945
1151
  ask: () => {},
946
1152
  askAssistant: () => {},
947
- closeChat: () => {},
1153
+ closeChat: () => null,
1154
+ registerSearchClose: () => () => {},
948
1155
  resetChat: () => {},
949
1156
  chatInputRef: { current: null },
950
1157
  });
@@ -964,31 +1171,129 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
964
1171
  const [answer, setAnswer] = useState<Answer[]>([]);
965
1172
  const abortRef = useRef<AbortController | null>(null);
966
1173
  const chatInputRef = useRef<HTMLInputElement | null>(null);
1174
+ const focusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
1175
+ const restoreFocusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(
1176
+ null,
1177
+ );
1178
+ const pendingRestoreFocusRef = useRef<HTMLElement | null>(null);
1179
+ const openerRef = useRef<HTMLElement | null>(null);
1180
+ const closeSearchRef = useRef<
1181
+ ((restoreFocus?: boolean) => HTMLElement | null) | null
1182
+ >(null);
967
1183
  const isOpenRef = useRef(isOpen);
968
1184
 
969
1185
  useEffect(() => {
970
1186
  isOpenRef.current = isOpen;
971
1187
  }, [isOpen]);
972
1188
 
973
- // Open the assistant, seeding a greeting the first time and focusing the
974
- // input once the panel has slid in (matches the 0.3s panel transition).
975
- const openChat = useCallback(() => {
1189
+ const showChat = useCallback((returnFocusTo?: HTMLElement | null) => {
1190
+ const previousOverlayOpener = closeSearchRef.current?.(false) ?? null;
1191
+ const pendingChatOpener = pendingRestoreFocusRef.current;
1192
+ if (restoreFocusTimeoutRef.current) {
1193
+ clearTimeout(restoreFocusTimeoutRef.current);
1194
+ restoreFocusTimeoutRef.current = null;
1195
+ }
1196
+ pendingRestoreFocusRef.current = null;
1197
+ if (!isOpenRef.current) {
1198
+ const activeElement = document.activeElement;
1199
+ openerRef.current =
1200
+ returnFocusTo?.isConnected === true
1201
+ ? returnFocusTo
1202
+ : previousOverlayOpener?.isConnected === true
1203
+ ? previousOverlayOpener
1204
+ : pendingChatOpener?.isConnected === true
1205
+ ? pendingChatOpener
1206
+ : activeElement instanceof HTMLElement &&
1207
+ activeElement !== document.body
1208
+ ? activeElement
1209
+ : null;
1210
+ }
1211
+ isOpenRef.current = true;
976
1212
  setIsOpen(true);
1213
+ if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);
1214
+ focusTimeoutRef.current = setTimeout(() => {
1215
+ focusTimeoutRef.current = null;
1216
+ chatInputRef.current?.focus();
1217
+ }, 0);
1218
+ }, []);
1219
+
1220
+ // Open the assistant and seed its greeting on the first visit. The opener is
1221
+ // captured before the mobile dialog makes the rest of the page inert.
1222
+ const openChat = useCallback(() => {
1223
+ showChat();
977
1224
  setAnswer((prev) =>
978
1225
  prev.length === 0 ? [{ text: INITIAL_GREETING, answer: true }] : prev,
979
1226
  );
980
- setTimeout(() => {
981
- chatInputRef.current?.focus();
982
- }, 350);
1227
+ }, [showChat]);
1228
+
1229
+ const closeChat = useCallback((restoreFocus = true) => {
1230
+ const pendingOpener = pendingRestoreFocusRef.current;
1231
+ if (!restoreFocus && restoreFocusTimeoutRef.current) {
1232
+ clearTimeout(restoreFocusTimeoutRef.current);
1233
+ restoreFocusTimeoutRef.current = null;
1234
+ pendingRestoreFocusRef.current = null;
1235
+ }
1236
+ if (!isOpenRef.current) return pendingOpener;
1237
+ if (focusTimeoutRef.current) {
1238
+ clearTimeout(focusTimeoutRef.current);
1239
+ focusTimeoutRef.current = null;
1240
+ }
1241
+ const activeElement = document.activeElement;
1242
+ if (
1243
+ activeElement instanceof HTMLElement &&
1244
+ activeElement.closest("[data-chat-surface]")
1245
+ ) {
1246
+ activeElement.blur();
1247
+ }
1248
+ const opener = openerRef.current;
1249
+ openerRef.current = null;
1250
+ isOpenRef.current = false;
1251
+ setIsOpen(false);
1252
+ if (restoreFocusTimeoutRef.current) {
1253
+ clearTimeout(restoreFocusTimeoutRef.current);
1254
+ }
1255
+ if (restoreFocus) {
1256
+ pendingRestoreFocusRef.current = opener;
1257
+ restoreFocusTimeoutRef.current = setTimeout(() => {
1258
+ const focusTarget = pendingRestoreFocusRef.current;
1259
+ restoreFocusTimeoutRef.current = null;
1260
+ pendingRestoreFocusRef.current = null;
1261
+ if (focusTarget?.isConnected) focusTarget.focus();
1262
+ }, 0);
1263
+ } else {
1264
+ pendingRestoreFocusRef.current = null;
1265
+ }
1266
+ return opener;
983
1267
  }, []);
984
1268
 
1269
+ const registerSearchClose = useCallback(
1270
+ (closeSearch: (restoreFocus?: boolean) => HTMLElement | null) => {
1271
+ closeSearchRef.current = closeSearch;
1272
+ return () => {
1273
+ if (closeSearchRef.current === closeSearch) {
1274
+ closeSearchRef.current = null;
1275
+ }
1276
+ };
1277
+ },
1278
+ [],
1279
+ );
1280
+
985
1281
  const toggleChat = useCallback(() => {
986
1282
  if (isOpenRef.current) {
987
- setIsOpen(false);
1283
+ closeChat();
988
1284
  } else {
989
1285
  openChat();
990
1286
  }
991
- }, [openChat]);
1287
+ }, [closeChat, openChat]);
1288
+
1289
+ useEffect(() => {
1290
+ return () => {
1291
+ if (focusTimeoutRef.current) clearTimeout(focusTimeoutRef.current);
1292
+ if (restoreFocusTimeoutRef.current) {
1293
+ clearTimeout(restoreFocusTimeoutRef.current);
1294
+ }
1295
+ };
1296
+ }, []);
992
1297
 
993
1298
  // Global Cmd/Ctrl+I toggles the assistant, but only when chat is enabled.
994
1299
  useEffect(() => {
@@ -1003,9 +1308,12 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
1003
1308
  return () => document.removeEventListener("keydown", handleKeyDown);
1004
1309
  }, [isChatActive, toggleChat]);
1005
1310
 
1006
- async function runQuestion(currentQuestion: string) {
1311
+ async function runQuestion(
1312
+ currentQuestion: string,
1313
+ returnFocusTo?: HTMLElement | null,
1314
+ ) {
1007
1315
  setQuestion("");
1008
- setIsOpen(true);
1316
+ showChat(returnFocusTo);
1009
1317
  setLoading(true);
1010
1318
  setError(null);
1011
1319
 
@@ -1161,21 +1469,20 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
1161
1469
  // response is already streaming (loading), we can't submit yet - open the
1162
1470
  // panel and pre-fill the input so the user can send it the moment the
1163
1471
  // current answer finishes. Otherwise submit it right away.
1164
- function askAssistant(rawQuestion: string) {
1472
+ function askAssistant(
1473
+ rawQuestion: string,
1474
+ returnFocusTo?: HTMLElement | null,
1475
+ ) {
1165
1476
  const trimmed = rawQuestion.trim();
1166
1477
  if (trimmed === "") return;
1167
1478
  if (loading) {
1168
- openChat();
1479
+ showChat(returnFocusTo);
1169
1480
  setQuestion(trimmed);
1170
1481
  } else {
1171
- void runQuestion(trimmed);
1482
+ void runQuestion(trimmed, returnFocusTo);
1172
1483
  }
1173
1484
  }
1174
1485
 
1175
- function closeChat() {
1176
- setIsOpen(false);
1177
- }
1178
-
1179
1486
  function resetChat() {
1180
1487
  abortRef.current?.abort();
1181
1488
  setLoading(false);
@@ -1199,6 +1506,7 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
1199
1506
  ask,
1200
1507
  askAssistant,
1201
1508
  closeChat,
1509
+ registerSearchClose,
1202
1510
  resetChat,
1203
1511
  chatInputRef,
1204
1512
  }}
@@ -1 +1 @@
1
- export declare const searchDocsTemplate = "\"use client\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport dynamic from \"next/dynamic\";\nimport styled from \"styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { interactiveStyles } from \"@/components/layout/SharedStyled\";\nimport { ChatContext } from \"@/components/Chat\";\nimport type { PageItem, MergedResult } from \"@/components/SearchModalContent\";\n\nconst SearchModalContent = dynamic(\n () =>\n import(\"@/components/SearchModalContent\").then(\n (mod) => mod.SearchModalContent,\n ),\n { ssr: false },\n);\n\ninterface SectionItem {\n label: string;\n slug: string;\n}\n\n// Stable empty array so the derived contentResults keeps the same identity\n// across renders when there are no hits (memo deps stay stable).\nconst EMPTY_RESULTS: ContentHit[] = [];\n\ninterface ContentHit {\n slug: string;\n snippet: string;\n}\n\ninterface SearchContextValue {\n openSearch: () => void;\n}\n\nconst SearchContext = createContext<SearchContextValue>({\n openSearch: () => {},\n});\n\nconst StyledKbd = styled.kbd<{ theme: Theme }>`\n font-size: 11px;\n font-family: inherit;\n background: ${({ theme }) => theme.colors.grayLight};\n color: ${({ theme }) => theme.colors.grayDark};\n padding: 2px 6px;\n border-radius: 4px;\n margin-left: auto;\n font-weight: 600;\n display: none;\n\n ${mq(\"lg\")} {\n display: initial;\n }\n`;\n\nconst StyledSearchButton = styled.button<{ theme: Theme }>`\n ${interactiveStyles};\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n display: flex;\n align-items: center;\n gap: 6px;\n background: ${({ theme }) => theme.colors.light};\n color: ${({ theme }) => theme.colors.primary};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n padding: 7px 8px;\n font-family: inherit;\n cursor: pointer;\n\n ${mq(\"lg\")} {\n padding: 5px 8px;\n }\n\n & svg.lucide {\n color: inherit;\n }\n`;\n\nfunction SearchProvider({\n pages,\n sections,\n children,\n}: {\n pages: PageItem[];\n sections?: SectionItem[];\n children: React.ReactNode;\n}) {\n const [isVisible, setIsVisible] = useState(false);\n const [isClosing, setIsClosing] = useState(false);\n const [query, setQuery] = useState(\"\");\n const [activeIndex, setActiveIndex] = useState(0);\n // Latest completed content search, keyed by the query that produced it.\n // contentResults and isSearching are derived from it at render time, so\n // the debounced-search effect never sets state synchronously (which would\n // trigger cascading renders \u2014 react-hooks/set-state-in-effect).\n const [fetched, setFetched] = useState<{\n q: string;\n results: ContentHit[];\n } | null>(null);\n const resultsRef = useRef<HTMLUListElement>(null);\n const closingRef = useRef(false);\n const abortRef = useRef<AbortController | null>(null);\n const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);\n const router = useRouter();\n const { isChatActive, askAssistant } = useContext(ChatContext);\n\n const sectionLabels = useMemo(() => {\n const map: Record<string, string> = {};\n sections?.forEach((s) => {\n map[s.slug] = s.label;\n });\n return map;\n }, [sections]);\n\n const openSearch = useCallback(() => {\n closingRef.current = false;\n setIsClosing(false);\n setIsVisible(true);\n }, []);\n\n const closeSearch = useCallback(() => {\n closingRef.current = true;\n setIsClosing(true);\n if (abortRef.current) abortRef.current.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n }, []);\n\n const handleCloseAnimationEnd = useCallback(() => {\n if (!closingRef.current) return;\n closingRef.current = false;\n setIsVisible(false);\n setIsClosing(false);\n setQuery(\"\");\n setActiveIndex(0);\n setFetched(null);\n }, []);\n\n const trimmedQuery = query.trim();\n const contentResults =\n trimmedQuery.length >= 2 && fetched?.q === trimmedQuery\n ? fetched.results\n : EMPTY_RESULTS;\n const isSearching = trimmedQuery.length >= 2 && fetched?.q !== trimmedQuery;\n\n // Instant title/description filtering\n const titleFiltered = useMemo(() => {\n if (!query.trim()) return pages;\n const q = query.toLowerCase();\n return pages.filter(\n (p) =>\n p.title.toLowerCase().includes(q) ||\n p.description?.toLowerCase().includes(q),\n );\n }, [pages, query]);\n\n // Merge title matches with content matches\n const merged = useMemo<MergedResult[]>(() => {\n if (!query.trim()) {\n return pages.map((p) => ({ page: p }));\n }\n\n const titleMatchSlugs = new Set(titleFiltered.map((p) => p.slug));\n const titleMatches: MergedResult[] = titleFiltered.map((p) => {\n const hit = contentResults.find((cr) => cr.slug === p.slug);\n return { page: p, snippet: hit?.snippet };\n });\n\n const pageMap = new Map(pages.map((p) => [p.slug, p]));\n const contentOnly: MergedResult[] = [];\n for (const cr of contentResults) {\n if (!titleMatchSlugs.has(cr.slug)) {\n const page = pageMap.get(cr.slug);\n if (page) {\n contentOnly.push({ page, snippet: cr.snippet });\n }\n }\n }\n\n return [...titleMatches, ...contentOnly];\n }, [pages, query, titleFiltered, contentResults]);\n\n // Debounced content search. State updates happen only inside the timeout's\n // async callback; short queries need no reset because the derived values\n // above ignore results whose query no longer matches.\n useEffect(() => {\n if (debounceRef.current) clearTimeout(debounceRef.current);\n if (abortRef.current) abortRef.current.abort();\n\n const q = query.trim();\n if (q.length < 2) return;\n\n debounceRef.current = setTimeout(async () => {\n const controller = new AbortController();\n abortRef.current = controller;\n try {\n const res = await fetch(\n `/api/search?q=${encodeURIComponent(q)}&limit=15`,\n { signal: controller.signal },\n );\n if (!res.ok) throw new Error(\"Search failed\");\n const data = await res.json();\n setFetched({ q, results: data.results ?? [] });\n } catch (err: unknown) {\n if (err instanceof DOMException && err.name === \"AbortError\") return;\n setFetched({ q, results: [] });\n }\n }, 300);\n\n return () => {\n if (debounceRef.current) clearTimeout(debounceRef.current);\n };\n }, [query]);\n\n const navigate = useCallback(\n (\n slug: string,\n modifiers?: { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean },\n ) => {\n const url = `/${slug}`;\n\n // Shift+Enter / Shift+Click: open in a separate browser window. Window\n // features (dimensions) are what make the browser spawn a window instead\n // of a tab; noopener/noreferrer keep the new window from reaching back\n // into this one via window.opener.\n if (modifiers?.shiftKey) {\n const width = Math.min(1024, window.screen.availWidth);\n const height = Math.min(800, window.screen.availHeight);\n const left = Math.round((window.screen.availWidth - width) / 2);\n const top = Math.round((window.screen.availHeight - height) / 2);\n window.open(\n url,\n \"_blank\",\n `popup=yes,noopener,noreferrer,width=${width},height=${height},left=${left},top=${top}`,\n );\n return;\n }\n\n // Cmd+Enter / Ctrl+Enter / Cmd+Click: open in a new background tab. With\n // no dimension features the browser keeps this as a tab.\n if (modifiers?.metaKey || modifiers?.ctrlKey) {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n return;\n }\n\n // Plain Enter / Click: navigate in place within the app.\n closeSearch();\n router.push(url);\n },\n [closeSearch, router],\n );\n\n // Hand the current query to the AI assistant, then dismiss the search modal.\n // `askAssistant` opens the chat and either submits the question or (if a\n // response is already streaming) pre-fills it, ready to send.\n const askAssistantWithQuery = useCallback(() => {\n const q = query.trim();\n if (!q) return;\n askAssistant(q);\n closeSearch();\n }, [query, askAssistant, closeSearch]);\n\n // Global Cmd+K / Ctrl+K listener\n const isVisibleRef = useRef(false);\n\n useEffect(() => {\n isVisibleRef.current = isVisible;\n }, [isVisible]);\n\n useEffect(() => {\n function handleKeyDown(e: KeyboardEvent) {\n if ((e.metaKey || e.ctrlKey) && e.key === \"k\") {\n e.preventDefault();\n if (isVisibleRef.current) {\n closeSearch();\n } else {\n openSearch();\n }\n }\n }\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => document.removeEventListener(\"keydown\", handleKeyDown);\n }, [closeSearch, openSearch]);\n\n // Active-row scrolling now lives in SearchModalContent's layout effect,\n // alongside the highlight measurement, so highlight + scroll update together\n // before paint (no flicker) and stay in sync on query changes.\n\n function handleKeyDown(e: React.KeyboardEvent) {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n setActiveIndex((i) => (i < merged.length - 1 ? i + 1 : 0));\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n setActiveIndex((i) => (i > 0 ? i - 1 : merged.length - 1));\n } else if (e.key === \"Enter\") {\n e.preventDefault();\n // Option/Alt+Enter is reserved for handing the query to the AI assistant.\n if (e.altKey) {\n if (isChatActive) askAssistantWithQuery();\n return;\n }\n if (merged[activeIndex]) {\n navigate(merged[activeIndex].page.slug, e);\n }\n } else if (e.key === \"Escape\") {\n closeSearch();\n }\n }\n\n return (\n <SearchContext.Provider value={{ openSearch }}>\n {children}\n {isVisible && (\n <SearchModalContent\n isClosing={isClosing}\n closeSearch={closeSearch}\n onCloseAnimationEnd={handleCloseAnimationEnd}\n query={query}\n setQuery={setQuery}\n activeIndex={activeIndex}\n setActiveIndex={setActiveIndex}\n resultsRef={resultsRef}\n onKeyDown={handleKeyDown}\n merged={merged}\n sectionLabels={sectionLabels}\n isSearching={isSearching}\n navigate={navigate}\n canAskAssistant={isChatActive}\n onAskAssistant={askAssistantWithQuery}\n />\n )}\n </SearchContext.Provider>\n );\n}\n\nexport {\n SearchProvider,\n SearchContext,\n StyledKbd as SearchKbd,\n StyledSearchButton,\n};\n";
1
+ export declare const searchDocsTemplate = "\"use client\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport dynamic from \"next/dynamic\";\nimport styled from \"styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { interactiveStyles } from \"@/components/layout/SharedStyled\";\nimport { ChatContext } from \"@/components/Chat\";\nimport type { PageItem, MergedResult } from \"@/components/SearchModalContent\";\n\nconst SearchModalContent = dynamic(\n () =>\n import(\"@/components/SearchModalContent\").then(\n (mod) => mod.SearchModalContent,\n ),\n { ssr: false },\n);\n\ninterface SectionItem {\n label: string;\n slug: string;\n}\n\n// Stable empty array so the derived contentResults keeps the same identity\n// across renders when there are no hits (memo deps stay stable).\nconst EMPTY_RESULTS: ContentHit[] = [];\n\ninterface ContentHit {\n slug: string;\n snippet: string;\n}\n\ninterface SearchContextValue {\n openSearch: () => void;\n}\n\nconst SearchContext = createContext<SearchContextValue>({\n openSearch: () => {},\n});\n\nconst StyledKbd = styled.kbd<{ theme: Theme }>`\n font-size: 11px;\n font-family: inherit;\n background: ${({ theme }) => theme.colors.grayLight};\n color: ${({ theme }) => theme.colors.grayDark};\n padding: 2px 6px;\n border-radius: 4px;\n margin-left: auto;\n font-weight: 600;\n display: none;\n\n ${mq(\"lg\")} {\n display: initial;\n }\n`;\n\nconst StyledSearchButton = styled.button<{ theme: Theme }>`\n ${interactiveStyles};\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n display: flex;\n align-items: center;\n gap: 6px;\n background: ${({ theme }) => theme.colors.light};\n color: ${({ theme }) => theme.colors.primary};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n padding: 7px 8px;\n font-family: inherit;\n cursor: pointer;\n\n ${mq(\"lg\")} {\n padding: 5px 8px;\n }\n\n & svg.lucide {\n color: inherit;\n }\n`;\n\nfunction SearchProvider({\n pages,\n sections,\n children,\n}: {\n pages: PageItem[];\n sections?: SectionItem[];\n children: React.ReactNode;\n}) {\n const [isVisible, setIsVisible] = useState(false);\n const [isClosing, setIsClosing] = useState(false);\n const [query, setQuery] = useState(\"\");\n const [activeIndex, setActiveIndex] = useState(0);\n const [returnFocusTo, setReturnFocusTo] = useState<HTMLElement | null>(null);\n // Latest completed content search, keyed by the query that produced it.\n // contentResults and isSearching are derived from it at render time, so\n // the debounced-search effect never sets state synchronously (which would\n // trigger cascading renders \u2014 react-hooks/set-state-in-effect).\n const [fetched, setFetched] = useState<{\n q: string;\n results: ContentHit[];\n } | null>(null);\n const resultsRef = useRef<HTMLUListElement>(null);\n const closingRef = useRef(false);\n const isVisibleRef = useRef(false);\n const searchOpenerRef = useRef<HTMLElement | null>(null);\n const restoreSearchFocusRef = useRef(true);\n const abortRef = useRef<AbortController | null>(null);\n const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);\n const router = useRouter();\n const { isChatActive, askAssistant, closeChat, registerSearchClose } =\n useContext(ChatContext);\n\n const sectionLabels = useMemo(() => {\n const map: Record<string, string> = {};\n sections?.forEach((s) => {\n map[s.slug] = s.label;\n });\n return map;\n }, [sections]);\n\n const openSearch = useCallback(() => {\n const previousOverlayOpener = closeChat(false);\n closingRef.current = false;\n restoreSearchFocusRef.current = true;\n const activeElement = document.activeElement;\n const opener =\n previousOverlayOpener?.isConnected === true\n ? previousOverlayOpener\n : activeElement instanceof HTMLElement &&\n activeElement !== document.body\n ? activeElement\n : null;\n searchOpenerRef.current = opener;\n setReturnFocusTo(opener);\n isVisibleRef.current = true;\n setIsClosing(false);\n setIsVisible(true);\n }, [closeChat]);\n\n const closeSearch = useCallback(() => {\n closingRef.current = true;\n setIsClosing(true);\n if (abortRef.current) abortRef.current.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n }, []);\n\n const shouldRestoreSearchFocus = useCallback(\n () => restoreSearchFocusRef.current,\n [],\n );\n\n const handleCloseAnimationEnd = useCallback(() => {\n if (!closingRef.current) return;\n closingRef.current = false;\n isVisibleRef.current = false;\n setIsVisible(false);\n setIsClosing(false);\n setQuery(\"\");\n setActiveIndex(0);\n setFetched(null);\n searchOpenerRef.current = null;\n setReturnFocusTo(null);\n }, []);\n\n const closeSearchImmediately = useCallback((restoreFocus = true) => {\n if (!isVisibleRef.current) return null;\n restoreSearchFocusRef.current = restoreFocus;\n const opener = searchOpenerRef.current;\n searchOpenerRef.current = null;\n setReturnFocusTo(null);\n closingRef.current = false;\n isVisibleRef.current = false;\n if (abortRef.current) abortRef.current.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n const activeElement = document.activeElement;\n if (\n activeElement instanceof HTMLElement &&\n activeElement.closest(\"[data-search-dialog]\")\n ) {\n activeElement.blur();\n }\n setIsVisible(false);\n setIsClosing(false);\n setQuery(\"\");\n setActiveIndex(0);\n setFetched(null);\n return opener;\n }, []);\n\n useEffect(\n () => registerSearchClose(closeSearchImmediately),\n [closeSearchImmediately, registerSearchClose],\n );\n\n const trimmedQuery = query.trim();\n const contentResults =\n trimmedQuery.length >= 2 && fetched?.q === trimmedQuery\n ? fetched.results\n : EMPTY_RESULTS;\n const isSearching = trimmedQuery.length >= 2 && fetched?.q !== trimmedQuery;\n\n // Instant title/description filtering\n const titleFiltered = useMemo(() => {\n if (!query.trim()) return pages;\n const q = query.toLowerCase();\n return pages.filter(\n (p) =>\n p.title.toLowerCase().includes(q) ||\n p.description?.toLowerCase().includes(q),\n );\n }, [pages, query]);\n\n // Merge title matches with content matches\n const merged = useMemo<MergedResult[]>(() => {\n if (!query.trim()) {\n return pages.map((p) => ({ page: p }));\n }\n\n const titleMatchSlugs = new Set(titleFiltered.map((p) => p.slug));\n const titleMatches: MergedResult[] = titleFiltered.map((p) => {\n const hit = contentResults.find((cr) => cr.slug === p.slug);\n return { page: p, snippet: hit?.snippet };\n });\n\n const pageMap = new Map(pages.map((p) => [p.slug, p]));\n const contentOnly: MergedResult[] = [];\n for (const cr of contentResults) {\n if (!titleMatchSlugs.has(cr.slug)) {\n const page = pageMap.get(cr.slug);\n if (page) {\n contentOnly.push({ page, snippet: cr.snippet });\n }\n }\n }\n\n return [...titleMatches, ...contentOnly];\n }, [pages, query, titleFiltered, contentResults]);\n\n // Debounced content search. State updates happen only inside the timeout's\n // async callback; short queries need no reset because the derived values\n // above ignore results whose query no longer matches.\n useEffect(() => {\n if (debounceRef.current) clearTimeout(debounceRef.current);\n if (abortRef.current) abortRef.current.abort();\n\n const q = query.trim();\n if (q.length < 2) return;\n\n debounceRef.current = setTimeout(async () => {\n const controller = new AbortController();\n abortRef.current = controller;\n try {\n const res = await fetch(\n `/api/search?q=${encodeURIComponent(q)}&limit=15`,\n { signal: controller.signal },\n );\n if (!res.ok) throw new Error(\"Search failed\");\n const data = await res.json();\n setFetched({ q, results: data.results ?? [] });\n } catch (err: unknown) {\n if (err instanceof DOMException && err.name === \"AbortError\") return;\n setFetched({ q, results: [] });\n }\n }, 300);\n\n return () => {\n if (debounceRef.current) clearTimeout(debounceRef.current);\n };\n }, [query]);\n\n const navigate = useCallback(\n (\n slug: string,\n modifiers?: { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean },\n ) => {\n const url = `/${slug}`;\n\n // Shift+Enter / Shift+Click: open in a separate browser window. Window\n // features (dimensions) are what make the browser spawn a window instead\n // of a tab; noopener/noreferrer keep the new window from reaching back\n // into this one via window.opener.\n if (modifiers?.shiftKey) {\n const width = Math.min(1024, window.screen.availWidth);\n const height = Math.min(800, window.screen.availHeight);\n const left = Math.round((window.screen.availWidth - width) / 2);\n const top = Math.round((window.screen.availHeight - height) / 2);\n window.open(\n url,\n \"_blank\",\n `popup=yes,noopener,noreferrer,width=${width},height=${height},left=${left},top=${top}`,\n );\n return;\n }\n\n // Cmd+Enter / Ctrl+Enter / Cmd+Click: open in a new background tab. With\n // no dimension features the browser keeps this as a tab.\n if (modifiers?.metaKey || modifiers?.ctrlKey) {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n return;\n }\n\n // Plain Enter / Click: navigate in place within the app.\n closeSearch();\n router.push(url);\n },\n [closeSearch, router],\n );\n\n // Hand the current query to the AI assistant, then dismiss the search modal.\n // `askAssistant` opens the chat and either submits the question or (if a\n // response is already streaming) pre-fills it, ready to send.\n const askAssistantWithQuery = useCallback(() => {\n const q = query.trim();\n if (!q) return;\n const opener = closeSearchImmediately(false);\n askAssistant(q, opener);\n }, [query, askAssistant, closeSearchImmediately]);\n\n // Global Cmd+K / Ctrl+K listener\n useEffect(() => {\n function handleKeyDown(e: KeyboardEvent) {\n if ((e.metaKey || e.ctrlKey) && e.key === \"k\") {\n e.preventDefault();\n if (isVisibleRef.current) {\n closeSearch();\n } else {\n openSearch();\n }\n }\n }\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => document.removeEventListener(\"keydown\", handleKeyDown);\n }, [closeSearch, openSearch]);\n\n // Active-row scrolling now lives in SearchModalContent's layout effect,\n // alongside the highlight measurement, so highlight + scroll update together\n // before paint (no flicker) and stay in sync on query changes.\n\n function handleKeyDown(e: React.KeyboardEvent) {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n setActiveIndex((i) => (i < merged.length - 1 ? i + 1 : 0));\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n setActiveIndex((i) => (i > 0 ? i - 1 : merged.length - 1));\n } else if (e.key === \"Enter\") {\n e.preventDefault();\n // Option/Alt+Enter is reserved for handing the query to the AI assistant.\n if (e.altKey) {\n if (isChatActive) askAssistantWithQuery();\n return;\n }\n if (merged[activeIndex]) {\n navigate(merged[activeIndex].page.slug, e);\n }\n } else if (e.key === \"Escape\") {\n closeSearch();\n }\n }\n\n return (\n <SearchContext.Provider value={{ openSearch }}>\n {children}\n {isVisible && (\n <SearchModalContent\n isClosing={isClosing}\n closeSearch={closeSearch}\n onCloseAnimationEnd={handleCloseAnimationEnd}\n query={query}\n setQuery={setQuery}\n activeIndex={activeIndex}\n setActiveIndex={setActiveIndex}\n resultsRef={resultsRef}\n onKeyDown={handleKeyDown}\n merged={merged}\n sectionLabels={sectionLabels}\n isSearching={isSearching}\n navigate={navigate}\n canAskAssistant={isChatActive}\n onAskAssistant={askAssistantWithQuery}\n shouldRestoreFocus={shouldRestoreSearchFocus}\n returnFocusTo={returnFocusTo}\n />\n )}\n </SearchContext.Provider>\n );\n}\n\nexport {\n SearchProvider,\n SearchContext,\n StyledKbd as SearchKbd,\n StyledSearchButton,\n};\n";