doccupine 0.0.139 → 0.0.141

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 (151) 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 -1895
  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 +18 -0
  19. package/dist/lib/utils.js +125 -0
  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 +102 -25
  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 +411 -104
  38. package/dist/templates/components/Docs.d.ts +1 -1
  39. package/dist/templates/components/Docs.js +56 -13
  40. package/dist/templates/components/SearchDocs.d.ts +1 -1
  41. package/dist/templates/components/SearchDocs.js +63 -11
  42. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  43. package/dist/templates/components/SearchModalContent.js +191 -49
  44. package/dist/templates/components/SideBar.d.ts +1 -1
  45. package/dist/templates/components/SideBar.js +8 -2
  46. package/dist/templates/components/layout/Accordion.d.ts +1 -1
  47. package/dist/templates/components/layout/Accordion.js +26 -3
  48. package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
  49. package/dist/templates/components/layout/ApiPlayground.js +4 -7
  50. package/dist/templates/components/layout/Badge.d.ts +1 -1
  51. package/dist/templates/components/layout/Badge.js +1 -1
  52. package/dist/templates/components/layout/Button.d.ts +1 -1
  53. package/dist/templates/components/layout/Button.js +4 -4
  54. package/dist/templates/components/layout/Callout.d.ts +1 -1
  55. package/dist/templates/components/layout/Callout.js +6 -6
  56. package/dist/templates/components/layout/Card.d.ts +1 -1
  57. package/dist/templates/components/layout/Card.js +9 -4
  58. package/dist/templates/components/layout/CherryThemeProvider.d.ts +1 -1
  59. package/dist/templates/components/layout/CherryThemeProvider.js +63 -12
  60. package/dist/templates/components/layout/Code.d.ts +1 -1
  61. package/dist/templates/components/layout/Code.js +5 -5
  62. package/dist/templates/components/layout/CopyButton.d.ts +1 -1
  63. package/dist/templates/components/layout/CopyButton.js +1 -1
  64. package/dist/templates/components/layout/DemoTheme.d.ts +1 -1
  65. package/dist/templates/components/layout/DemoTheme.js +8 -28
  66. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  67. package/dist/templates/components/layout/DocsComponents.js +57 -18
  68. package/dist/templates/components/layout/GlobalStyles.d.ts +1 -1
  69. package/dist/templates/components/layout/GlobalStyles.js +15 -9
  70. package/dist/templates/components/layout/Prompt.d.ts +1 -1
  71. package/dist/templates/components/layout/Prompt.js +4 -7
  72. package/dist/templates/components/layout/Steps.d.ts +1 -1
  73. package/dist/templates/components/layout/Steps.js +7 -1
  74. package/dist/templates/components/layout/Tabs.d.ts +1 -1
  75. package/dist/templates/components/layout/Tabs.js +108 -19
  76. package/dist/templates/env.example.d.ts +1 -1
  77. package/dist/templates/env.example.js +11 -0
  78. package/dist/templates/eslint.config.d.ts +1 -1
  79. package/dist/templates/eslint.config.js +20 -0
  80. package/dist/templates/gitignore.d.ts +1 -1
  81. package/dist/templates/gitignore.js +4 -3
  82. package/dist/templates/lib/access.d.ts +1 -0
  83. package/dist/templates/lib/access.js +41 -0
  84. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  85. package/dist/templates/mdx/ai-assistant.mdx.js +17 -1
  86. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  87. package/dist/templates/mdx/api-playground.mdx.js +5 -3
  88. package/dist/templates/mdx/authentication.mdx.d.ts +1 -1
  89. package/dist/templates/mdx/authentication.mdx.js +5 -3
  90. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  91. package/dist/templates/mdx/commands.mdx.js +20 -6
  92. package/dist/templates/mdx/components.mdx.d.ts +1 -1
  93. package/dist/templates/mdx/components.mdx.js +3 -0
  94. package/dist/templates/mdx/deployment-and-hosting.mdx.d.ts +1 -1
  95. package/dist/templates/mdx/deployment-and-hosting.mdx.js +2 -2
  96. package/dist/templates/mdx/globals.mdx.d.ts +1 -1
  97. package/dist/templates/mdx/globals.mdx.js +14 -11
  98. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  99. package/dist/templates/mdx/model-context-protocol.mdx.js +22 -35
  100. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  101. package/dist/templates/mdx/platform/ai-assistant.mdx.js +23 -0
  102. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  103. package/dist/templates/mdx/platform/api-playground.mdx.js +7 -0
  104. package/dist/templates/mdx/platform/authentication.mdx.d.ts +1 -0
  105. package/dist/templates/mdx/platform/authentication.mdx.js +63 -0
  106. package/dist/templates/mdx/platform/build-and-deploy.mdx.d.ts +1 -1
  107. package/dist/templates/mdx/platform/build-and-deploy.mdx.js +1 -1
  108. package/dist/templates/mdx/platform/import-from-github.mdx.d.ts +1 -1
  109. package/dist/templates/mdx/platform/import-from-github.mdx.js +2 -2
  110. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  111. package/dist/templates/mdx/platform/index.mdx.js +1 -0
  112. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  113. package/dist/templates/mdx/platform/mcp.mdx.js +2 -1
  114. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  115. package/dist/templates/mdx/platform/navigation-settings.mdx.js +12 -1
  116. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  117. package/dist/templates/mdx/platform/publishing.mdx.js +43 -10
  118. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  119. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +48 -9
  120. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  121. package/dist/templates/mdx/sections.mdx.js +4 -0
  122. package/dist/templates/mdx/space.mdx.d.ts +1 -0
  123. package/dist/templates/mdx/space.mdx.js +125 -0
  124. package/dist/templates/mdx/tabs.mdx.d.ts +1 -1
  125. package/dist/templates/mdx/tabs.mdx.js +4 -0
  126. package/dist/templates/next.config.js +20 -8
  127. package/dist/templates/package.js +3 -3
  128. package/dist/templates/prettierignore.d.ts +1 -1
  129. package/dist/templates/prettierignore.js +1 -0
  130. package/dist/templates/proxy.js +47 -19
  131. package/dist/templates/scripts/build-docs-index.d.ts +1 -1
  132. package/dist/templates/scripts/build-docs-index.js +1 -0
  133. package/dist/templates/services/mcp/docsContentStub.d.ts +1 -0
  134. package/dist/templates/services/mcp/docsContentStub.js +1 -0
  135. package/dist/templates/services/mcp/server.d.ts +1 -1
  136. package/dist/templates/services/mcp/server.js +140 -83
  137. package/dist/templates/services/mcp/tools.d.ts +1 -1
  138. package/dist/templates/services/mcp/tools.js +65 -137
  139. package/dist/templates/utils/playgroundAllowlist.d.ts +1 -1
  140. package/dist/templates/utils/playgroundAllowlist.js +13 -4
  141. package/dist/templates/utils/rateLimit.d.ts +1 -1
  142. package/dist/templates/utils/rateLimit.js +40 -3
  143. package/dist/templates/utils/requestBody.d.ts +1 -0
  144. package/dist/templates/utils/requestBody.js +56 -0
  145. package/dist/templates/utils/ssrfGuard.d.ts +1 -1
  146. package/dist/templates/utils/ssrfGuard.js +138 -33
  147. package/package.json +14 -9
  148. package/dist/lib/mdxToMarkdown.d.ts +0 -1
  149. package/dist/lib/mdxToMarkdown.js +0 -134
  150. package/dist/templates/mdx/image-and-embeds.mdx.d.ts +0 -1
  151. 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,8 @@ 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";
22
+ import { Callout } from "@/components/layout/Callout";
20
23
  import { useLockBodyScroll } from "@/components/LockBodyScroll";
21
24
  import { useMDXComponents as getMDXComponents } from "@/components/MDXComponents";
22
25
  import {
@@ -30,6 +33,26 @@ import {
30
33
 
31
34
  const mdxComponents = getMDXComponents({});
32
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
+
33
56
  const styledText = css<{ theme: Theme }>\`
34
57
  font-size: \${({ theme }) => theme.fontSizes.text.xs};
35
58
  line-height: \${({ theme }) => theme.lineHeights.text.xs};
@@ -40,6 +63,27 @@ const styledText = css<{ theme: Theme }>\`
40
63
  }
41
64
  \`;
42
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
+
43
87
  const StyledChat = styled.div<{ theme: Theme; $isVisible: boolean }>\`
44
88
  margin: 0;
45
89
  position: fixed;
@@ -51,11 +95,17 @@ const StyledChat = styled.div<{ theme: Theme; $isVisible: boolean }>\`
51
95
  overflow-x: hidden;
52
96
  z-index: 1000;
53
97
  padding: 0 20px;
54
- 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;
55
104
  transform: translateX(0);
56
105
  background: \${({ theme }) => theme.colors.light};
57
106
  -webkit-overflow-scrolling: touch;
58
107
  opacity: 1;
108
+ visibility: visible;
59
109
 
60
110
  &::-webkit-scrollbar {
61
111
  display: none;
@@ -66,8 +116,14 @@ const StyledChat = styled.div<{ theme: Theme; $isVisible: boolean }>\`
66
116
  css\`
67
117
  transform: translateX(100%);
68
118
  opacity: 0;
119
+ visibility: hidden;
120
+ transition-delay: 0s, 0s, 0.3s;
69
121
  \`}
70
122
 
123
+ @media (prefers-reduced-motion: reduce) {
124
+ transition: none;
125
+ }
126
+
71
127
  \${mq("lg")} {
72
128
  width: ${CHAT_WIDTH}px;
73
129
  border-left: solid 1px \${({ theme }) => theme.colors.grayLight};
@@ -359,9 +415,17 @@ const StyledChatForm = styled.form<{ theme: Theme; $isVisible: boolean }>\`
359
415
  z-index: 1000;
360
416
  width: 100%;
361
417
  border-top: solid 1px \${({ theme }) => theme.colors.grayLight};
362
- 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;
363
426
  transform: translateX(100%);
364
427
  opacity: 0;
428
+ visibility: hidden;
365
429
 
366
430
  \${mq("lg")} {
367
431
  width: ${CHAT_WIDTH}px;
@@ -373,8 +437,14 @@ const StyledChatForm = styled.form<{ theme: Theme; $isVisible: boolean }>\`
373
437
  css\`
374
438
  opacity: 1;
375
439
  transform: translateX(0);
440
+ visibility: visible;
441
+ transition-delay: 0s;
376
442
  \`}
377
443
 
444
+ @media (prefers-reduced-motion: reduce) {
445
+ transition: none;
446
+ }
447
+
378
448
  & .loading {
379
449
  animation: \${loadingAnimation} 1s linear infinite;
380
450
  }
@@ -470,16 +540,9 @@ const StyledGlowSmallButton = styled(StyledSmallButton)<{
470
540
  \`}
471
541
  \`;
472
542
 
473
- const StyledError = styled.div<{ theme: Theme }>\`
474
- overflow-x: auto;
475
- \${thinScrollbar};
476
- background: \${({ theme }) => theme.colors.error};
477
- color: \${({ theme }) => theme.colors.surface};
478
- padding: 10px;
479
- border-radius: 8px;
543
+ const StyledError = styled.div\`
480
544
  margin: 20px 0;
481
545
  width: 100%;
482
- \${styledText};
483
546
  \`;
484
547
 
485
548
  const loadingDotAnimation = keyframes\`
@@ -798,23 +861,158 @@ function Chat() {
798
861
  resetChat,
799
862
  chatInputRef,
800
863
  } = useContext(ChatContext);
801
- 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;
802
871
 
803
872
  useLockBodyScroll(isOpen);
804
873
 
805
874
  useEffect(() => {
806
- endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
807
- }, [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]);
808
889
 
809
890
  useEffect(() => {
810
- if (answer?.length > 0) {
811
- 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;
935
+ }
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();
812
995
  }
813
- }, [answer, chatInputRef]);
996
+ };
814
997
 
815
998
  return (
816
- <>
817
- <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
+ >
818
1016
  <StyledChatTitle>
819
1017
  <StyledChatTitleIconWrapper>
820
1018
  <Sparkles />
@@ -829,7 +1027,7 @@ function Chat() {
829
1027
  <RotateCcw />
830
1028
  </IconButton>
831
1029
  <IconButton
832
- onClick={closeChat}
1030
+ onClick={() => closeChat()}
833
1031
  aria-label="Close chat"
834
1032
  title="Close chat"
835
1033
  >
@@ -888,10 +1086,13 @@ function Chat() {
888
1086
  )}
889
1087
  {error && (
890
1088
  <StyledError>
891
- <strong>Error:</strong> {error}
1089
+ <Callout type="danger">
1090
+ <p>
1091
+ <strong>Error:</strong> {error}
1092
+ </p>
1093
+ </Callout>
892
1094
  </StyledError>
893
1095
  )}
894
- <div ref={endRef} />
895
1096
  </StyledChat>
896
1097
 
897
1098
  <StyledChatForm onSubmit={ask} $isVisible={isOpen} data-markdown-ignore>
@@ -913,7 +1114,7 @@ function Chat() {
913
1114
  {loading ? <LoaderPinwheel className="loading" /> : <ArrowUp />}
914
1115
  </StyledRainbowButton>
915
1116
  </StyledChatForm>
916
- </>
1117
+ </StyledChatSurface>
917
1118
  );
918
1119
  }
919
1120
 
@@ -929,8 +1130,11 @@ const ChatContext = createContext<{
929
1130
  answer: Answer[];
930
1131
  setAnswer: (answers: Answer[]) => void;
931
1132
  ask: (e: React.FormEvent) => void;
932
- askAssistant: (question: string) => void;
933
- 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;
934
1138
  resetChat: () => void;
935
1139
  chatInputRef: React.RefObject<HTMLInputElement | null>;
936
1140
  }>({
@@ -946,7 +1150,8 @@ const ChatContext = createContext<{
946
1150
  setAnswer: () => {},
947
1151
  ask: () => {},
948
1152
  askAssistant: () => {},
949
- closeChat: () => {},
1153
+ closeChat: () => null,
1154
+ registerSearchClose: () => () => {},
950
1155
  resetChat: () => {},
951
1156
  chatInputRef: { current: null },
952
1157
  });
@@ -966,31 +1171,129 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
966
1171
  const [answer, setAnswer] = useState<Answer[]>([]);
967
1172
  const abortRef = useRef<AbortController | null>(null);
968
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);
969
1183
  const isOpenRef = useRef(isOpen);
970
1184
 
971
1185
  useEffect(() => {
972
1186
  isOpenRef.current = isOpen;
973
1187
  }, [isOpen]);
974
1188
 
975
- // Open the assistant, seeding a greeting the first time and focusing the
976
- // input once the panel has slid in (matches the 0.3s panel transition).
977
- 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;
978
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();
979
1224
  setAnswer((prev) =>
980
1225
  prev.length === 0 ? [{ text: INITIAL_GREETING, answer: true }] : prev,
981
1226
  );
982
- setTimeout(() => {
983
- chatInputRef.current?.focus();
984
- }, 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;
985
1267
  }, []);
986
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
+
987
1281
  const toggleChat = useCallback(() => {
988
1282
  if (isOpenRef.current) {
989
- setIsOpen(false);
1283
+ closeChat();
990
1284
  } else {
991
1285
  openChat();
992
1286
  }
993
- }, [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
+ }, []);
994
1297
 
995
1298
  // Global Cmd/Ctrl+I toggles the assistant, but only when chat is enabled.
996
1299
  useEffect(() => {
@@ -1005,9 +1308,12 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
1005
1308
  return () => document.removeEventListener("keydown", handleKeyDown);
1006
1309
  }, [isChatActive, toggleChat]);
1007
1310
 
1008
- async function runQuestion(currentQuestion: string) {
1311
+ async function runQuestion(
1312
+ currentQuestion: string,
1313
+ returnFocusTo?: HTMLElement | null,
1314
+ ) {
1009
1315
  setQuestion("");
1010
- setIsOpen(true);
1316
+ showChat(returnFocusTo);
1011
1317
  setLoading(true);
1012
1318
  setError(null);
1013
1319
 
@@ -1077,69 +1383,70 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
1077
1383
  buffer = parts.pop() ?? "";
1078
1384
 
1079
1385
  for (const line of parts) {
1080
- if (line.startsWith("data: ")) {
1386
+ if (!line.startsWith("data: ")) continue;
1387
+
1388
+ // Guard only the parse: a malformed frame is skipped, while the
1389
+ // server's error event below must throw past this loop to the
1390
+ // outer catch so it renders in the chat's error callout instead
1391
+ // of dying in a parse-error log.
1392
+ let data;
1393
+ try {
1394
+ data = JSON.parse(line.slice(6));
1395
+ } catch {
1396
+ console.error("Failed to parse SSE data:", line);
1397
+ continue;
1398
+ }
1399
+
1400
+ if (data.type === "metadata") {
1401
+ const allSources: Source[] = data.data?.sources ?? [];
1402
+ const seen = new Set<string>();
1403
+ sources = allSources.filter((s: Source) => {
1404
+ if (s.score < 0.4 || seen.has(s.uri)) return false;
1405
+ seen.add(s.uri);
1406
+ return true;
1407
+ });
1408
+ } else if (data.type === "content") {
1409
+ contentParts.push(data.data);
1410
+ const streamedContent = contentParts.join("");
1411
+
1412
+ setAnswer((prev) => {
1413
+ const newAnswers = [...prev];
1414
+ newAnswers[streamingAnswerIndex] = {
1415
+ text: streamedContent,
1416
+ answer: true,
1417
+ sources,
1418
+ };
1419
+ return newAnswers;
1420
+ });
1421
+ } else if (data.type === "error") {
1422
+ throw new Error(data.data);
1423
+ } else if (data.type === "done") {
1424
+ const streamedContent = contentParts.join("");
1425
+ let mdxSource: MDXRemoteSerializeResult | null = null;
1081
1426
  try {
1082
- const data = JSON.parse(line.slice(6));
1083
-
1084
- if (data.type === "metadata") {
1085
- const allSources: Source[] = data.data?.sources ?? [];
1086
- const seen = new Set<string>();
1087
- sources = allSources.filter((s: Source) => {
1088
- if (s.score < 0.4 || seen.has(s.uri)) return false;
1089
- seen.add(s.uri);
1090
- return true;
1091
- });
1092
- } else if (data.type === "content") {
1093
- contentParts.push(data.data);
1094
- const streamedContent = contentParts.join("");
1095
-
1096
- setAnswer((prev) => {
1097
- const newAnswers = [...prev];
1098
- newAnswers[streamingAnswerIndex] = {
1099
- text: streamedContent,
1100
- answer: true,
1101
- sources,
1102
- };
1103
- return newAnswers;
1104
- });
1105
- } else if (data.type === "error") {
1106
- throw new Error(data.data);
1107
- } else if (data.type === "done") {
1108
- const streamedContent = contentParts.join("");
1109
- let mdxSource: MDXRemoteSerializeResult | null = null;
1110
- try {
1111
- mdxSource = await serialize(streamedContent, {
1112
- parseFrontmatter: false,
1113
- mdxOptions: {
1114
- remarkPlugins: [remarkGfm],
1115
- rehypePlugins: [rehypeHighlight],
1116
- format: "md",
1117
- development: false,
1118
- },
1119
- });
1120
- } catch (mdxError: unknown) {
1121
- console.error("MDX serialization error:", mdxError);
1122
- }
1123
-
1124
- setAnswer((prev) => {
1125
- const newAnswers = [...prev];
1126
- newAnswers[streamingAnswerIndex] = {
1127
- text: streamedContent,
1128
- answer: true,
1129
- mdx: mdxSource || undefined,
1130
- sources,
1131
- };
1132
- return newAnswers;
1133
- });
1134
- }
1135
- } catch (parseError) {
1136
- if (
1137
- parseError instanceof Error &&
1138
- parseError.message !== "Unknown error"
1139
- ) {
1140
- console.error("Failed to parse SSE data:", parseError);
1141
- }
1427
+ mdxSource = await serialize(streamedContent, {
1428
+ parseFrontmatter: false,
1429
+ mdxOptions: {
1430
+ remarkPlugins: [remarkGfm],
1431
+ rehypePlugins: [rehypeHighlight],
1432
+ format: "md",
1433
+ development: false,
1434
+ },
1435
+ });
1436
+ } catch (mdxError: unknown) {
1437
+ console.error("MDX serialization error:", mdxError);
1142
1438
  }
1439
+
1440
+ setAnswer((prev) => {
1441
+ const newAnswers = [...prev];
1442
+ newAnswers[streamingAnswerIndex] = {
1443
+ text: streamedContent,
1444
+ answer: true,
1445
+ mdx: mdxSource || undefined,
1446
+ sources,
1447
+ };
1448
+ return newAnswers;
1449
+ });
1143
1450
  }
1144
1451
  }
1145
1452
  }
@@ -1162,21 +1469,20 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
1162
1469
  // response is already streaming (loading), we can't submit yet - open the
1163
1470
  // panel and pre-fill the input so the user can send it the moment the
1164
1471
  // current answer finishes. Otherwise submit it right away.
1165
- function askAssistant(rawQuestion: string) {
1472
+ function askAssistant(
1473
+ rawQuestion: string,
1474
+ returnFocusTo?: HTMLElement | null,
1475
+ ) {
1166
1476
  const trimmed = rawQuestion.trim();
1167
1477
  if (trimmed === "") return;
1168
1478
  if (loading) {
1169
- openChat();
1479
+ showChat(returnFocusTo);
1170
1480
  setQuestion(trimmed);
1171
1481
  } else {
1172
- void runQuestion(trimmed);
1482
+ void runQuestion(trimmed, returnFocusTo);
1173
1483
  }
1174
1484
  }
1175
1485
 
1176
- function closeChat() {
1177
- setIsOpen(false);
1178
- }
1179
-
1180
1486
  function resetChat() {
1181
1487
  abortRef.current?.abort();
1182
1488
  setLoading(false);
@@ -1200,6 +1506,7 @@ const ChtProvider = ({ children, isChatActive }: ChatContextProviderProps) => {
1200
1506
  ask,
1201
1507
  askAssistant,
1202
1508
  closeChat,
1509
+ registerSearchClose,
1203
1510
  resetChat,
1204
1511
  chatInputRef,
1205
1512
  }}