doccupine 0.0.158 → 0.0.159

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 (149) hide show
  1. package/README.md +51 -1
  2. package/dist/generator/app-scaffolder.js +11 -3
  3. package/dist/generator/generated-page-publisher.d.ts +6 -6
  4. package/dist/generator/generated-page-publisher.js +7 -5
  5. package/dist/generator/mdx-pass-builder.d.ts +4 -4
  6. package/dist/generator/mdx-pass-builder.js +8 -1
  7. package/dist/generator/mdx-reconciliation-coordinator.d.ts +23 -9
  8. package/dist/generator/mdx-reconciliation-coordinator.js +63 -9
  9. package/dist/generator/page-catalog.d.ts +2 -4
  10. package/dist/generator/page-catalog.js +7 -2
  11. package/dist/generator/page-renderer.d.ts +15 -5
  12. package/dist/generator/page-renderer.js +38 -11
  13. package/dist/generator/project-config-repository.d.ts +4 -1
  14. package/dist/generator/project-config-repository.js +26 -0
  15. package/dist/generator/public-asset-manager.d.ts +10 -0
  16. package/dist/generator/public-asset-manager.js +63 -3
  17. package/dist/generator/section-index-generator.d.ts +10 -1
  18. package/dist/generator/section-index-generator.js +43 -15
  19. package/dist/generator/section-resolver.d.ts +8 -0
  20. package/dist/generator/site-artifacts.d.ts +4 -3
  21. package/dist/generator/site-artifacts.js +94 -9
  22. package/dist/generator/watch-coordinator.js +6 -1
  23. package/dist/lib/generated-artifacts.d.ts +3 -0
  24. package/dist/lib/generated-artifacts.js +36 -0
  25. package/dist/lib/layout.d.ts +6 -3
  26. package/dist/lib/layout.js +107 -4
  27. package/dist/lib/metadata.d.ts +7 -0
  28. package/dist/lib/metadata.js +33 -10
  29. package/dist/lib/structures.js +20 -0
  30. package/dist/lib/types.d.ts +28 -0
  31. package/dist/lib/ui-strings.d.ts +44 -0
  32. package/dist/lib/ui-strings.js +48 -0
  33. package/dist/lib/variants.d.ts +91 -0
  34. package/dist/lib/variants.js +411 -0
  35. package/dist/mdx-to-nextjs-generator.d.ts +22 -5
  36. package/dist/mdx-to-nextjs-generator.js +89 -10
  37. package/dist/templates/app/api/mcp/route.d.ts +1 -1
  38. package/dist/templates/app/api/mcp/route.js +14 -1
  39. package/dist/templates/app/api/rag/route.d.ts +1 -1
  40. package/dist/templates/app/api/rag/route.js +13 -2
  41. package/dist/templates/app/api/search/route.d.ts +1 -1
  42. package/dist/templates/app/api/search/route.js +16 -1
  43. package/dist/templates/app/sitemap.d.ts +2 -0
  44. package/dist/templates/app/sitemap.js +48 -3
  45. package/dist/templates/components/Chat.d.ts +1 -1
  46. package/dist/templates/components/Chat.js +40 -12
  47. package/dist/templates/components/Docs.d.ts +1 -1
  48. package/dist/templates/components/Docs.js +5 -2
  49. package/dist/templates/components/DocsSideBar.d.ts +1 -1
  50. package/dist/templates/components/DocsSideBar.js +3 -1
  51. package/dist/templates/components/SearchDocs.d.ts +1 -1
  52. package/dist/templates/components/SearchDocs.js +17 -3
  53. package/dist/templates/components/SearchModalContent.d.ts +1 -1
  54. package/dist/templates/components/SearchModalContent.js +22 -14
  55. package/dist/templates/components/SectionNavProvider.d.ts +1 -1
  56. package/dist/templates/components/SectionNavProvider.js +32 -20
  57. package/dist/templates/components/SideBar.d.ts +1 -1
  58. package/dist/templates/components/SideBar.js +26 -12
  59. package/dist/templates/components/layout/ActionBar.d.ts +1 -1
  60. package/dist/templates/components/layout/ActionBar.js +9 -7
  61. package/dist/templates/components/layout/Code.d.ts +1 -1
  62. package/dist/templates/components/layout/Code.js +6 -3
  63. package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
  64. package/dist/templates/components/layout/DocsComponents.js +38 -5
  65. package/dist/templates/components/layout/DocsNavigation.d.ts +1 -1
  66. package/dist/templates/components/layout/DocsNavigation.js +4 -2
  67. package/dist/templates/components/layout/Dropdown.d.ts +1 -0
  68. package/dist/templates/components/layout/Dropdown.js +308 -0
  69. package/dist/templates/components/layout/FocusModeToggle.d.ts +1 -1
  70. package/dist/templates/components/layout/FocusModeToggle.js +7 -4
  71. package/dist/templates/components/layout/Footer.d.ts +1 -1
  72. package/dist/templates/components/layout/Footer.js +4 -2
  73. package/dist/templates/components/layout/Header.d.ts +1 -1
  74. package/dist/templates/components/layout/Header.js +18 -8
  75. package/dist/templates/components/layout/SectionBar.d.ts +1 -1
  76. package/dist/templates/components/layout/SectionBar.js +16 -10
  77. package/dist/templates/components/layout/VariantSwitchers.d.ts +1 -0
  78. package/dist/templates/components/layout/VariantSwitchers.js +313 -0
  79. package/dist/templates/components/useStrings.d.ts +1 -0
  80. package/dist/templates/components/useStrings.js +10 -0
  81. package/dist/templates/components/useVariant.d.ts +1 -0
  82. package/dist/templates/components/useVariant.js +13 -0
  83. package/dist/templates/llms/llmsIndex.d.ts +13 -0
  84. package/dist/templates/llms/llmsIndex.js +18 -3
  85. package/dist/templates/mdx/ai-assistant.mdx.d.ts +1 -1
  86. package/dist/templates/mdx/ai-assistant.mdx.js +2 -0
  87. package/dist/templates/mdx/api-playground.mdx.d.ts +1 -1
  88. package/dist/templates/mdx/api-playground.mdx.js +2 -0
  89. package/dist/templates/mdx/commands.mdx.d.ts +1 -1
  90. package/dist/templates/mdx/commands.mdx.js +1 -1
  91. package/dist/templates/mdx/fonts.mdx.d.ts +1 -1
  92. package/dist/templates/mdx/fonts.mdx.js +1 -1
  93. package/dist/templates/mdx/footer-links.mdx.d.ts +1 -1
  94. package/dist/templates/mdx/footer-links.mdx.js +1 -1
  95. package/dist/templates/mdx/index.mdx.d.ts +1 -1
  96. package/dist/templates/mdx/index.mdx.js +2 -0
  97. package/dist/templates/mdx/languages.mdx.d.ts +1 -0
  98. package/dist/templates/mdx/languages.mdx.js +94 -0
  99. package/dist/templates/mdx/media-and-assets.mdx.d.ts +1 -1
  100. package/dist/templates/mdx/media-and-assets.mdx.js +1 -1
  101. package/dist/templates/mdx/model-context-protocol.mdx.d.ts +1 -1
  102. package/dist/templates/mdx/model-context-protocol.mdx.js +6 -0
  103. package/dist/templates/mdx/navigation.mdx.d.ts +1 -1
  104. package/dist/templates/mdx/navigation.mdx.js +2 -0
  105. package/dist/templates/mdx/platform/ai-assistant.mdx.d.ts +1 -1
  106. package/dist/templates/mdx/platform/ai-assistant.mdx.js +2 -0
  107. package/dist/templates/mdx/platform/api-playground.mdx.d.ts +1 -1
  108. package/dist/templates/mdx/platform/api-playground.mdx.js +2 -0
  109. package/dist/templates/mdx/platform/file-editor.mdx.d.ts +1 -1
  110. package/dist/templates/mdx/platform/file-editor.mdx.js +2 -0
  111. package/dist/templates/mdx/platform/index.mdx.d.ts +1 -1
  112. package/dist/templates/mdx/platform/index.mdx.js +1 -1
  113. package/dist/templates/mdx/platform/languages.mdx.d.ts +1 -0
  114. package/dist/templates/mdx/platform/languages.mdx.js +50 -0
  115. package/dist/templates/mdx/platform/mcp.mdx.d.ts +1 -1
  116. package/dist/templates/mdx/platform/mcp.mdx.js +2 -0
  117. package/dist/templates/mdx/platform/navigation-settings.mdx.d.ts +1 -1
  118. package/dist/templates/mdx/platform/navigation-settings.mdx.js +2 -0
  119. package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
  120. package/dist/templates/mdx/platform/publishing.mdx.js +4 -0
  121. package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
  122. package/dist/templates/mdx/platform/self-updating-docs.mdx.js +2 -0
  123. package/dist/templates/mdx/platform/versions.mdx.d.ts +1 -0
  124. package/dist/templates/mdx/platform/versions.mdx.js +33 -0
  125. package/dist/templates/mdx/sections.mdx.d.ts +1 -1
  126. package/dist/templates/mdx/sections.mdx.js +1 -1
  127. package/dist/templates/mdx/theme.mdx.d.ts +1 -1
  128. package/dist/templates/mdx/theme.mdx.js +1 -1
  129. package/dist/templates/mdx/versions.mdx.d.ts +1 -0
  130. package/dist/templates/mdx/versions.mdx.js +78 -0
  131. package/dist/templates/mdx/what-is-doccupine.mdx.d.ts +1 -1
  132. package/dist/templates/mdx/what-is-doccupine.mdx.js +1 -1
  133. package/dist/templates/prettierignore.d.ts +1 -1
  134. package/dist/templates/prettierignore.js +2 -0
  135. package/dist/templates/services/mcp/server.d.ts +1 -1
  136. package/dist/templates/services/mcp/server.js +54 -10
  137. package/dist/templates/services/mcp/tools.d.ts +1 -1
  138. package/dist/templates/services/mcp/tools.js +81 -6
  139. package/dist/templates/services/mcp/types.d.ts +1 -1
  140. package/dist/templates/services/mcp/types.js +10 -0
  141. package/dist/templates/services/search.d.ts +1 -1
  142. package/dist/templates/services/search.js +34 -4
  143. package/dist/templates/utils/orderNavItems.d.ts +1 -1
  144. package/dist/templates/utils/orderNavItems.js +2 -0
  145. package/dist/templates/utils/strings.d.ts +1 -0
  146. package/dist/templates/utils/strings.js +27 -0
  147. package/dist/templates/utils/variants.d.ts +1 -0
  148. package/dist/templates/utils/variants.js +170 -0
  149. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  export const docsSideBarTemplate = `"use client";
2
2
  import { useCallback, useEffect, useRef, useState } from "react";
3
3
  import { Space } from "cherry-styled-components";
4
+ import { useStrings } from "@/components/useStrings";
4
5
  import {
5
6
  StyledIndexSidebar,
6
7
  StyledIndexSidebarLink,
@@ -24,6 +25,7 @@ function getOffset() {
24
25
  export function DocsSideBar({ headings }: { headings: Heading[] }) {
25
26
  const [activeId, setActiveId] = useState<string>("");
26
27
  const activeRef = useRef<HTMLLIElement>(null);
28
+ const t = useStrings();
27
29
 
28
30
  const handleScroll = useCallback(() => {
29
31
  if (headings.length === 0) return;
@@ -146,7 +148,7 @@ export function DocsSideBar({ headings }: { headings: Heading[] }) {
146
148
  <StyledIndexSidebar data-sidebar data-markdown-ignore>
147
149
  {headings?.length > 0 && (
148
150
  <li aria-hidden="true">
149
- <StyledIndexSidebarLabel>On this page</StyledIndexSidebarLabel>
151
+ <StyledIndexSidebarLabel>{t.onThisPage}</StyledIndexSidebarLabel>
150
152
  <Space $size={15} />
151
153
  </li>
152
154
  )}
@@ -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 { useChat } from \"cherry-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 /* Pinned to the 30px compact header-control tier, matching Cherry's\n ChatLauncher, so the height cannot drift with platform font metrics\n and the header controls always align exactly. */\n box-sizing: border-box;\n height: 30px;\n background: ${({ theme }) => theme.colors.light};\n color: ${({ theme }) => theme.colors.primary};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n padding: 0 8px;\n font-family: inherit;\n cursor: pointer;\n\n & svg.lucide {\n color: inherit;\n min-width: 14px;\n }\n\n ${mq(\"lg\")} {\n padding: 0 4px 0 8px;\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 } = useContext(ChatContext);\n const { ask, close: closeChat, isOpen: isChatOpen } = useChat();\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 // Only one overlay at a time: the chat panel opening (launcher, Cmd+I, or\n // `ask`) dismisses the search modal without restoring focus, since focus\n // has already moved into the chat composer.\n useEffect(() => {\n if (isChatOpen) closeSearchImmediately(false);\n }, [isChatOpen, closeSearchImmediately]);\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 // `ask` opens the chat and either submits the question or (if a response is\n // 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 ask(q, opener);\n }, [query, ask, 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";
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 { useChat } from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { interactiveStyles } from \"@/components/layout/SharedStyled\";\nimport { ChatContext } from \"@/components/Chat\";\nimport { useVariant } from \"@/components/useVariant\";\nimport type { PageItem, MergedResult } from \"@/components/SearchModalContent\";\nimport { pageVariantPrefix } from \"@/utils/variants\";\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 /* Pinned to the 30px compact header-control tier, matching Cherry's\n ChatLauncher, so the height cannot drift with platform font metrics\n and the header controls always align exactly. */\n box-sizing: border-box;\n height: 30px;\n background: ${({ theme }) => theme.colors.light};\n color: ${({ theme }) => theme.colors.primary};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n padding: 0 8px;\n font-family: inherit;\n cursor: pointer;\n\n & svg.lucide {\n color: inherit;\n min-width: 14px;\n }\n\n ${mq(\"lg\")} {\n padding: 0 4px 0 8px;\n }\n`;\n\nfunction SearchProvider({\n pages: allPages,\n sections,\n children,\n}: {\n pages: PageItem[];\n sections?: SectionItem[];\n children: React.ReactNode;\n}) {\n // Search stays inside the current language and version: the title matches\n // below and the content search on the server both see this scope only.\n const variant = useVariant();\n const pages = useMemo(\n () => allPages.filter((page) => pageVariantPrefix(page) === variant.prefix),\n [allPages, variant.prefix],\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 } = useContext(ChatContext);\n const { ask, close: closeChat, isOpen: isChatOpen } = useChat();\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 // Only one overlay at a time: the chat panel opening (launcher, Cmd+I, or\n // `ask`) dismisses the search modal without restoring focus, since focus\n // has already moved into the chat composer.\n useEffect(() => {\n if (isChatOpen) closeSearchImmediately(false);\n }, [isChatOpen, closeSearchImmediately]);\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 const scope = [\n variant.locale ? \"&locale=\" + encodeURIComponent(variant.locale) : \"\",\n variant.version ? \"&version=\" + encodeURIComponent(variant.version) : \"\",\n ].join(\"\");\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${scope}`,\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, variant.locale, variant.version]);\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 // `ask` opens the chat and either submits the question or (if a response is\n // 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 ask(q, opener);\n }, [query, ask, 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";
@@ -15,7 +15,9 @@ import { useChat } from "cherry-styled-components";
15
15
  import { mq, Theme } from "@/app/theme";
16
16
  import { interactiveStyles } from "@/components/layout/SharedStyled";
17
17
  import { ChatContext } from "@/components/Chat";
18
+ import { useVariant } from "@/components/useVariant";
18
19
  import type { PageItem, MergedResult } from "@/components/SearchModalContent";
20
+ import { pageVariantPrefix } from "@/utils/variants";
19
21
 
20
22
  const SearchModalContent = dynamic(
21
23
  () =>
@@ -92,7 +94,7 @@ const StyledSearchButton = styled.button<{ theme: Theme }>\`
92
94
  \`;
93
95
 
94
96
  function SearchProvider({
95
- pages,
97
+ pages: allPages,
96
98
  sections,
97
99
  children,
98
100
  }: {
@@ -100,6 +102,13 @@ function SearchProvider({
100
102
  sections?: SectionItem[];
101
103
  children: React.ReactNode;
102
104
  }) {
105
+ // Search stays inside the current language and version: the title matches
106
+ // below and the content search on the server both see this scope only.
107
+ const variant = useVariant();
108
+ const pages = useMemo(
109
+ () => allPages.filter((page) => pageVariantPrefix(page) === variant.prefix),
110
+ [allPages, variant.prefix],
111
+ );
103
112
  const [isVisible, setIsVisible] = useState(false);
104
113
  const [isClosing, setIsClosing] = useState(false);
105
114
  const [query, setQuery] = useState("");
@@ -262,12 +271,17 @@ function SearchProvider({
262
271
  const q = query.trim();
263
272
  if (q.length < 2) return;
264
273
 
274
+ const scope = [
275
+ variant.locale ? "&locale=" + encodeURIComponent(variant.locale) : "",
276
+ variant.version ? "&version=" + encodeURIComponent(variant.version) : "",
277
+ ].join("");
278
+
265
279
  debounceRef.current = setTimeout(async () => {
266
280
  const controller = new AbortController();
267
281
  abortRef.current = controller;
268
282
  try {
269
283
  const res = await fetch(
270
- \`/api/search?q=\${encodeURIComponent(q)}&limit=15\`,
284
+ \`/api/search?q=\${encodeURIComponent(q)}&limit=15\${scope}\`,
271
285
  { signal: controller.signal },
272
286
  );
273
287
  if (!res.ok) throw new Error("Search failed");
@@ -282,7 +296,7 @@ function SearchProvider({
282
296
  return () => {
283
297
  if (debounceRef.current) clearTimeout(debounceRef.current);
284
298
  };
285
- }, [query]);
299
+ }, [query, variant.locale, variant.version]);
286
300
 
287
301
  const navigate = useCallback(
288
302
  (
@@ -1 +1 @@
1
- export declare const searchModalContentTemplate = "\"use client\";\nimport React from \"react\";\nimport styled, { css, keyframes } from \"styled-components\";\nimport { Search, X } from \"lucide-react\";\nimport { IconButton } from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { Spinner } from \"@/components/Spinner\";\nimport {\n interactiveStyles,\n thinScrollbar,\n} from \"@/components/layout/SharedStyled\";\n\nexport interface PageItem {\n slug: string;\n title: string;\n description?: string;\n category: string;\n section?: string;\n}\n\nexport interface MergedResult {\n page: PageItem;\n snippet?: string;\n}\n\nexport interface SearchModalContentProps {\n isClosing: boolean;\n closeSearch: () => void;\n onCloseAnimationEnd: () => void;\n query: string;\n setQuery: (q: string) => void;\n activeIndex: number;\n setActiveIndex: (i: number | ((prev: number) => number)) => void;\n resultsRef: React.RefObject<HTMLUListElement | null>;\n onKeyDown: (e: React.KeyboardEvent) => void;\n merged: MergedResult[];\n sectionLabels: Record<string, string>;\n isSearching: boolean;\n navigate: (\n slug: string,\n modifiers?: { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean },\n ) => void;\n canAskAssistant: boolean;\n onAskAssistant: () => void;\n shouldRestoreFocus: () => boolean;\n returnFocusTo: HTMLElement | null;\n}\n\nconst ANIMATION_MS = 300;\n\nconst backdropIn = keyframes`\n from { opacity: 0; }\n to { opacity: 1; }\n`;\n\nconst backdropOut = keyframes`\n from { opacity: 1; }\n to { opacity: 0; }\n`;\n\nconst modalIn = keyframes`\n from { opacity: 0; transform: scale(0.96) translateY(-8px); }\n to { opacity: 1; transform: scale(1) translateY(0); }\n`;\n\nconst modalOut = keyframes`\n from { opacity: 1; transform: scale(1) translateY(0); }\n to { opacity: 0; transform: scale(0.96) translateY(-8px); }\n`;\n\nconst StyledBackdrop = styled.div<{ theme: Theme; $isClosing: boolean }>`\n position: fixed;\n inset: 0;\n z-index: 9999;\n /* Backdrop is intentionally near-black in both modes \u2014 covers everything\n behind the modal regardless of the user's theme. */\n background: rgba(0, 0, 0, 0.5);\n backdrop-filter: blur(4px);\n -webkit-backdrop-filter: blur(4px);\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding: 20px;\n animation: ${({ $isClosing }) => ($isClosing ? backdropOut : backdropIn)}\n ${ANIMATION_MS}ms ease forwards;\n\n ${mq(\"lg\")} {\n padding: 120px 20px 20px 20px;\n }\n`;\n\nconst StyledModal = styled.div<{ theme: Theme; $isClosing: boolean }>`\n background: ${({ theme }) => theme.colors.light};\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n box-shadow: ${({ theme }) => theme.shadows.xs};\n width: 100%;\n max-width: 560px;\n max-height: calc(100dvh - 40px);\n display: flex;\n flex-direction: column;\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n padding-bottom: 8px;\n animation: ${({ $isClosing }) => ($isClosing ? modalOut : modalIn)}\n ${ANIMATION_MS}ms ease forwards;\n\n ${mq(\"lg\")} {\n max-height: calc(100dvh - 240px);\n }\n`;\n\nconst StyledInputWrapper = styled.div<{ theme: Theme }>`\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 16px;\n flex-shrink: 0;\n border-bottom: solid 1px ${({ theme }) => theme.colors.grayLight};\n\n & svg.lucide {\n color: ${({ theme }) => theme.colors.gray};\n flex-shrink: 0;\n }\n`;\n\nconst StyledInput = styled.input<{ theme: Theme }>`\n flex: 1;\n border: none;\n outline: none;\n background: transparent;\n font-size: ${({ theme }) => theme.fontSizes.text.lg};\n line-height: ${({ theme }) => theme.lineHeights.text.lg};\n color: ${({ theme }) => theme.colors.dark};\n font-family: inherit;\n\n &::placeholder {\n color: ${({ theme }) => theme.colors.gray};\n }\n\n /* type=\"search\" gets the platform clear button, which duplicates the modal's\n own close control and sits at a size and color we do not control. */\n &::-webkit-search-cancel-button,\n &::-webkit-search-decoration {\n -webkit-appearance: none;\n appearance: none;\n }\n`;\n\n// \"Ask AI\" affordance shown before the close button when the AI chat is\n// enabled. Desktop-only (like the header's Cmd+K hint) since it advertises the\n// Option+Enter shortcut; mobile users reach the assistant from the header CTA.\nconst StyledAskAssistant = styled.button<{ theme: Theme }>`\n ${interactiveStyles};\n display: none;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n background: ${({ theme }) => theme.colors.light};\n color: ${({ theme }) => theme.colors.grayDark};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n padding: 5px 4px 5px 8px;\n font-family: inherit;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n font-weight: 500;\n line-height: 1;\n white-space: nowrap;\n cursor: pointer;\n\n &:disabled {\n opacity: 0.5;\n cursor: default;\n\n &:hover {\n border-color: ${({ theme }) => theme.colors.grayLight};\n }\n\n &:focus,\n &:active {\n outline: none;\n box-shadow: 0 0 0 0 ${({ theme }) => theme.colors.primaryLight};\n }\n }\n\n ${mq(\"lg\")} {\n display: inline-flex;\n }\n`;\n\nconst StyledAskKeys = styled.span`\n display: inline-flex;\n align-items: center;\n gap: 3px;\n`;\n\nconst StyledAskKbd = styled.kbd<{ theme: Theme }>`\n font-family: inherit;\n font-size: 12px;\n font-weight: 600;\n line-height: 1;\n min-width: 18px;\n height: 18px;\n padding: 0 4px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n background: ${({ theme }) => theme.colors.grayLight};\n color: ${({ theme }) => theme.colors.grayDark};\n border-radius: 4px;\n`;\n\n// The return glyph's ink sits high in its em box, so it reads top-aligned even\n// when the keycap flex-centers it. Nudge just the character (not the pill) down\n// a pixel so it optically centers and lines up with the option glyph.\nconst StyledReturnGlyph = styled.span`\n display: inline-block;\n transform: translateY(1.5px);\n`;\n\nconst StyledResults = styled.ul<{ theme: Theme }>`\n list-style: none;\n position: relative;\n margin: 8px 0 0 0;\n padding: 0 8px;\n overflow-y: auto;\n flex: 1;\n min-height: 0;\n -webkit-overflow-scrolling: touch;\n ${thinScrollbar};\n\n &[hidden] {\n display: none;\n }\n`;\n\n// Single indicator that slides between result items instead of each item\n// fading its own background in and out. Positioned/sized from the active item's\n// measured offset (see the layout effect below); the transition on\n// transform + height produces the up/down glide as the active item changes.\nconst StyledHighlight = styled.div<{\n theme: Theme;\n $top: number;\n $height: number;\n}>`\n position: absolute;\n left: 8px;\n right: 8px;\n top: 0;\n z-index: 0;\n pointer-events: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n transition:\n transform 0.2s cubic-bezier(0.22, 1, 0.36, 1),\n height 0.2s cubic-bezier(0.22, 1, 0.36, 1);\n will-change: transform, height;\n transform: translateY(${({ $top }) => $top}px);\n height: ${({ $height }) => $height}px;\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n`;\n\nconst StyledResultItem = styled.li<{ theme: Theme; $isActive: boolean }>`\n position: relative;\n z-index: 1;\n padding: 10px 12px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n cursor: pointer;\n\n &:focus-visible {\n outline: none;\n box-shadow: inset 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n & > span:first-of-type {\n color: ${theme.colors.primary};\n }\n `}\n`;\n\nconst StyledResultTitle = styled.span<{ theme: Theme }>`\n font-size: ${({ theme }) => theme.fontSizes.text.lg};\n font-weight: 500;\n color: ${({ theme }) => theme.colors.dark};\n display: block;\n transition: color 0.15s ease;\n`;\n\nconst StyledResultMeta = styled.span<{ theme: Theme }>`\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n color: ${({ theme }) => theme.colors.gray};\n display: block;\n margin-top: 2px;\n`;\n\nconst StyledSnippet = styled.span<{ theme: Theme }>`\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n color: ${({ theme }) => theme.colors.grayDark};\n display: block;\n margin-top: 4px;\n line-height: 1.4;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n\n & mark {\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 35%, transparent)`};\n color: inherit;\n border-radius: 4px;\n padding: 0 1px;\n }\n`;\n\nconst StyledEmpty = styled.div<{ theme: Theme }>`\n padding: 20px 20px 12px;\n min-height: 40px;\n display: flex;\n align-items: center;\n justify-content: center;\n /* Separates the spinner from \"Searching documentation...\"; the whitespace\n between them in the markup collapses away as an anonymous flex item. */\n gap: 8px;\n text-align: center;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n color: ${({ theme }) => theme.colors.gray};\n`;\n\nconst StyledLiveStatus = styled.div`\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n border: 0;\n`;\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nfunction highlightMatch(snippet: string, query: string): string {\n const escaped = escapeHtml(snippet);\n if (!query.trim()) return escaped;\n const q = escapeHtml(query.trim());\n const regex = new RegExp(\n `(${q.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")})`,\n \"gi\",\n );\n return escaped.replace(regex, \"<mark>$1</mark>\");\n}\n\nexport function SearchModalContent({\n isClosing,\n closeSearch,\n onCloseAnimationEnd,\n query,\n setQuery,\n activeIndex,\n setActiveIndex,\n resultsRef,\n onKeyDown,\n merged,\n sectionLabels,\n isSearching,\n navigate,\n canAskAssistant,\n onAskAssistant,\n shouldRestoreFocus,\n returnFocusTo,\n}: SearchModalContentProps) {\n const dialogRef = React.useRef<HTMLDivElement | null>(null);\n const inputRef = React.useRef<HTMLInputElement | null>(null);\n const previouslyFocusedRef = React.useRef<HTMLElement | null>(\n returnFocusTo?.isConnected === true\n ? returnFocusTo\n : typeof document === \"undefined\"\n ? null\n : (document.activeElement as HTMLElement | null),\n );\n const listboxId = React.useId();\n const optionId = (index: number) => listboxId + \"-option-\" + index;\n\n React.useEffect(() => {\n const previouslyFocused = previouslyFocusedRef.current;\n const containFocus = (event: FocusEvent) => {\n if (\n event.target instanceof Node &&\n !dialogRef.current?.contains(event.target)\n ) {\n inputRef.current?.focus();\n }\n };\n\n document.addEventListener(\"focusin\", containFocus);\n inputRef.current?.focus();\n\n return () => {\n document.removeEventListener(\"focusin\", containFocus);\n if (shouldRestoreFocus() && previouslyFocused?.isConnected) {\n previouslyFocused.focus();\n }\n };\n }, [shouldRestoreFocus]);\n\n const handleDialogKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (event.key === \"Escape\") {\n event.preventDefault();\n event.stopPropagation();\n closeSearch();\n return;\n }\n\n if (event.key !== \"Tab\") return;\n\n const focusable = Array.from(\n dialogRef.current?.querySelectorAll<HTMLElement>(\n 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])',\n ) ?? [],\n ).filter(\n (element) =>\n element.offsetParent !== null &&\n element.getAttribute(\"aria-hidden\") !== \"true\",\n );\n\n if (focusable.length === 0) {\n event.preventDefault();\n return;\n }\n\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n // Measure the active item so the sliding highlight can be placed over it.\n // useLayoutEffect runs before paint, so the first position is committed\n // without a transition (no slide-in on open); later activeIndex/hover\n // changes glide because only the transform + height differ.\n const [indicator, setIndicator] = React.useState<{\n top: number;\n height: number;\n } | null>(null);\n\n React.useLayoutEffect(() => {\n const list = resultsRef.current;\n if (!list) {\n setIndicator(null);\n return;\n }\n const items = list.querySelectorAll(\"li\");\n const active = items[activeIndex] as HTMLElement | undefined;\n if (!active) {\n setIndicator(null);\n return;\n }\n setIndicator({ top: active.offsetTop, height: active.offsetHeight });\n\n // Keep the active row inside the scroll viewport in the SAME pre-paint pass\n // that positions the highlight, so the two never desync into a one-frame\n // flicker. merged is a dependency, so re-filtering (a new query) also\n // re-scrolls the reset active row into view even when its index is\n // unchanged. This list is flat (no group headers), so no header inclusion\n // is needed; a small margin keeps rows off the container's hard edges.\n // Adjust scrollTop directly (never scrollIntoView, which can also pan\n // ancestors).\n const margin = 8;\n const viewTop = active.offsetTop - margin;\n const viewBottom = active.offsetTop + active.offsetHeight + margin;\n\n if (viewTop < list.scrollTop) {\n list.scrollTop = viewTop;\n } else if (viewBottom > list.scrollTop + list.clientHeight) {\n list.scrollTop = viewBottom - list.clientHeight;\n }\n }, [activeIndex, merged, resultsRef]);\n\n return (\n <StyledBackdrop\n $isClosing={isClosing}\n onClick={closeSearch}\n onAnimationEnd={(e) => {\n // animationend bubbles, so this handler also fires for animations\n // completing on descendants (the inner modal, icons, result items).\n // Only the backdrop's own exit animation should trigger the unmount -\n // otherwise a child finishing its animation first tears the modal down\n // before the close animation plays, making it vanish instantly.\n if (e.target === e.currentTarget) onCloseAnimationEnd();\n }}\n >\n <StyledModal\n ref={dialogRef}\n $isClosing={isClosing}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label=\"Search documentation\"\n data-search-dialog\n onKeyDownCapture={handleDialogKeyDown}\n onClick={(e) => e.stopPropagation()}\n >\n <StyledInputWrapper>\n <Search size={18} />\n <StyledInput\n ref={inputRef}\n type=\"search\"\n value={query}\n onChange={(e) => {\n setQuery(e.target.value);\n setActiveIndex(0);\n }}\n onKeyDown={onKeyDown}\n placeholder=\"Search docs...\"\n autoComplete=\"off\"\n spellCheck={false}\n aria-label=\"Search documentation\"\n role=\"combobox\"\n aria-autocomplete=\"list\"\n aria-haspopup=\"listbox\"\n aria-expanded=\"true\"\n aria-controls={listboxId}\n aria-activedescendant={\n merged[activeIndex] ? optionId(activeIndex) : undefined\n }\n />\n {canAskAssistant && (\n <StyledAskAssistant\n type=\"button\"\n onClick={onAskAssistant}\n disabled={!query.trim()}\n aria-label=\"Ask AI\"\n title=\"Ask AI\"\n >\n Ask AI\n <StyledAskKeys aria-hidden=\"true\">\n <StyledAskKbd>&#8997;</StyledAskKbd>\n <StyledAskKbd>\n <StyledReturnGlyph>&#8629;</StyledReturnGlyph>\n </StyledAskKbd>\n </StyledAskKeys>\n </StyledAskAssistant>\n )}\n <IconButton\n onClick={closeSearch}\n aria-label=\"Close search\"\n title=\"Close search\"\n >\n <X />\n </IconButton>\n </StyledInputWrapper>\n <StyledLiveStatus role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">\n {isSearching\n ? \"Searching documentation\"\n : merged.length === 0\n ? \"No search results found\"\n : `${merged.length} search ${merged.length === 1 ? \"result\" : \"results\"} available`}\n </StyledLiveStatus>\n <StyledResults\n ref={resultsRef}\n id={listboxId}\n role=\"listbox\"\n aria-label=\"Search results\"\n aria-busy={isSearching}\n hidden={merged.length === 0}\n >\n {indicator && (\n <StyledHighlight\n aria-hidden=\"true\"\n $top={indicator.top}\n $height={indicator.height}\n />\n )}\n {merged.map((result, index) => (\n <StyledResultItem\n key={result.page.slug + result.page.section}\n id={optionId(index)}\n role=\"option\"\n aria-selected={index === activeIndex}\n $isActive={index === activeIndex}\n onClick={(e) => navigate(result.page.slug, e)}\n onMouseEnter={() => setActiveIndex(index)}\n >\n <StyledResultTitle>{result.page.title}</StyledResultTitle>\n <StyledResultMeta>\n {result.page.section\n ? `${sectionLabels[result.page.section] || result.page.section} / `\n : \"\"}\n {result.page.category}\n </StyledResultMeta>\n {result.snippet && (\n <StyledSnippet\n dangerouslySetInnerHTML={{\n __html: highlightMatch(result.snippet, query),\n }}\n />\n )}\n </StyledResultItem>\n ))}\n </StyledResults>\n {merged.length === 0 && (\n <StyledEmpty aria-hidden=\"true\">\n {isSearching ? (\n <>\n <Spinner size={18} /> Searching documentation...\n </>\n ) : (\n \"No results found\"\n )}\n </StyledEmpty>\n )}\n </StyledModal>\n </StyledBackdrop>\n );\n}\n";
1
+ export declare const searchModalContentTemplate = "\"use client\";\nimport React from \"react\";\nimport styled, { css, keyframes } from \"styled-components\";\nimport { Search, X } from \"lucide-react\";\nimport { IconButton } from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { Spinner } from \"@/components/Spinner\";\nimport { useStrings } from \"@/components/useStrings\";\nimport { withCount } from \"@/utils/strings\";\nimport {\n interactiveStyles,\n thinScrollbar,\n} from \"@/components/layout/SharedStyled\";\n\nexport interface PageItem {\n slug: string;\n title: string;\n description?: string;\n category: string;\n section?: string;\n locale?: string;\n version?: string;\n}\n\nexport interface MergedResult {\n page: PageItem;\n snippet?: string;\n}\n\nexport interface SearchModalContentProps {\n isClosing: boolean;\n closeSearch: () => void;\n onCloseAnimationEnd: () => void;\n query: string;\n setQuery: (q: string) => void;\n activeIndex: number;\n setActiveIndex: (i: number | ((prev: number) => number)) => void;\n resultsRef: React.RefObject<HTMLUListElement | null>;\n onKeyDown: (e: React.KeyboardEvent) => void;\n merged: MergedResult[];\n sectionLabels: Record<string, string>;\n isSearching: boolean;\n navigate: (\n slug: string,\n modifiers?: { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean },\n ) => void;\n canAskAssistant: boolean;\n onAskAssistant: () => void;\n shouldRestoreFocus: () => boolean;\n returnFocusTo: HTMLElement | null;\n}\n\nconst ANIMATION_MS = 300;\n\nconst backdropIn = keyframes`\n from { opacity: 0; }\n to { opacity: 1; }\n`;\n\nconst backdropOut = keyframes`\n from { opacity: 1; }\n to { opacity: 0; }\n`;\n\nconst modalIn = keyframes`\n from { opacity: 0; transform: scale(0.96) translateY(-8px); }\n to { opacity: 1; transform: scale(1) translateY(0); }\n`;\n\nconst modalOut = keyframes`\n from { opacity: 1; transform: scale(1) translateY(0); }\n to { opacity: 0; transform: scale(0.96) translateY(-8px); }\n`;\n\nconst StyledBackdrop = styled.div<{ theme: Theme; $isClosing: boolean }>`\n position: fixed;\n inset: 0;\n z-index: 9999;\n /* Backdrop is intentionally near-black in both modes \u2014 covers everything\n behind the modal regardless of the user's theme. */\n background: rgba(0, 0, 0, 0.5);\n backdrop-filter: blur(4px);\n -webkit-backdrop-filter: blur(4px);\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding: 20px;\n animation: ${({ $isClosing }) => ($isClosing ? backdropOut : backdropIn)}\n ${ANIMATION_MS}ms ease forwards;\n\n ${mq(\"lg\")} {\n padding: 120px 20px 20px 20px;\n }\n`;\n\nconst StyledModal = styled.div<{ theme: Theme; $isClosing: boolean }>`\n background: ${({ theme }) => theme.colors.light};\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n box-shadow: ${({ theme }) => theme.shadows.xs};\n width: 100%;\n max-width: 560px;\n max-height: calc(100dvh - 40px);\n display: flex;\n flex-direction: column;\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n padding-bottom: 8px;\n animation: ${({ $isClosing }) => ($isClosing ? modalOut : modalIn)}\n ${ANIMATION_MS}ms ease forwards;\n\n ${mq(\"lg\")} {\n max-height: calc(100dvh - 240px);\n }\n`;\n\nconst StyledInputWrapper = styled.div<{ theme: Theme }>`\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 16px;\n flex-shrink: 0;\n border-bottom: solid 1px ${({ theme }) => theme.colors.grayLight};\n\n & svg.lucide {\n color: ${({ theme }) => theme.colors.gray};\n flex-shrink: 0;\n }\n`;\n\nconst StyledInput = styled.input<{ theme: Theme }>`\n flex: 1;\n padding: 0;\n border: none;\n outline: none;\n background: transparent;\n font-size: ${({ theme }) => theme.fontSizes.text.lg};\n line-height: ${({ theme }) => theme.lineHeights.text.lg};\n color: ${({ theme }) => theme.colors.dark};\n font-family: inherit;\n\n &::placeholder {\n color: ${({ theme }) => theme.colors.gray};\n }\n\n /* type=\"search\" gets the platform clear button, which duplicates the modal's\n own close control and sits at a size and color we do not control. */\n &::-webkit-search-cancel-button,\n &::-webkit-search-decoration {\n -webkit-appearance: none;\n appearance: none;\n }\n`;\n\n// \"Ask AI\" affordance shown before the close button when the AI chat is\n// enabled. Desktop-only (like the header's Cmd+K hint) since it advertises the\n// Option+Enter shortcut; mobile users reach the assistant from the header CTA.\nconst StyledAskAssistant = styled.button<{ theme: Theme }>`\n ${interactiveStyles};\n display: none;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n background: ${({ theme }) => theme.colors.light};\n color: ${({ theme }) => theme.colors.grayDark};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n padding: 5px 4px 5px 8px;\n font-family: inherit;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n font-weight: 500;\n line-height: 1;\n white-space: nowrap;\n cursor: pointer;\n\n &:disabled {\n opacity: 0.5;\n cursor: default;\n\n &:hover {\n border-color: ${({ theme }) => theme.colors.grayLight};\n }\n\n &:focus,\n &:active {\n outline: none;\n box-shadow: 0 0 0 0 ${({ theme }) => theme.colors.primaryLight};\n }\n }\n\n ${mq(\"lg\")} {\n display: inline-flex;\n }\n`;\n\nconst StyledAskKeys = styled.span`\n display: inline-flex;\n align-items: center;\n gap: 3px;\n`;\n\nconst StyledAskKbd = styled.kbd<{ theme: Theme }>`\n font-family: inherit;\n font-size: 12px;\n font-weight: 600;\n line-height: 1;\n min-width: 18px;\n height: 18px;\n padding: 0 4px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n background: ${({ theme }) => theme.colors.grayLight};\n color: ${({ theme }) => theme.colors.grayDark};\n border-radius: 4px;\n`;\n\n// The return glyph's ink sits high in its em box, so it reads top-aligned even\n// when the keycap flex-centers it. Nudge just the character (not the pill) down\n// a pixel so it optically centers and lines up with the option glyph.\nconst StyledReturnGlyph = styled.span`\n display: inline-block;\n transform: translateY(1.5px);\n`;\n\nconst StyledResults = styled.ul<{ theme: Theme }>`\n list-style: none;\n position: relative;\n margin: 8px 0 0 0;\n padding: 0 8px;\n overflow-y: auto;\n flex: 1;\n min-height: 0;\n -webkit-overflow-scrolling: touch;\n ${thinScrollbar};\n\n &[hidden] {\n display: none;\n }\n`;\n\n// Single indicator that slides between result items instead of each item\n// fading its own background in and out. Positioned/sized from the active item's\n// measured offset (see the layout effect below); the transition on\n// transform + height produces the up/down glide as the active item changes.\nconst StyledHighlight = styled.div<{\n theme: Theme;\n $top: number;\n $height: number;\n}>`\n position: absolute;\n left: 8px;\n right: 8px;\n top: 0;\n z-index: 0;\n pointer-events: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n transition:\n transform 0.2s cubic-bezier(0.22, 1, 0.36, 1),\n height 0.2s cubic-bezier(0.22, 1, 0.36, 1);\n will-change: transform, height;\n transform: translateY(${({ $top }) => $top}px);\n height: ${({ $height }) => $height}px;\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n`;\n\nconst StyledResultItem = styled.li<{ theme: Theme; $isActive: boolean }>`\n position: relative;\n z-index: 1;\n padding: 10px 12px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n cursor: pointer;\n\n &:focus-visible {\n outline: none;\n box-shadow: inset 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n & > span:first-of-type {\n color: ${theme.colors.primary};\n }\n `}\n`;\n\nconst StyledResultTitle = styled.span<{ theme: Theme }>`\n font-size: ${({ theme }) => theme.fontSizes.text.lg};\n font-weight: 500;\n color: ${({ theme }) => theme.colors.dark};\n display: block;\n transition: color 0.15s ease;\n`;\n\nconst StyledResultMeta = styled.span<{ theme: Theme }>`\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n color: ${({ theme }) => theme.colors.gray};\n display: block;\n margin-top: 2px;\n`;\n\nconst StyledSnippet = styled.span<{ theme: Theme }>`\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n color: ${({ theme }) => theme.colors.grayDark};\n display: block;\n margin-top: 4px;\n line-height: 1.4;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n\n & mark {\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 35%, transparent)`};\n color: inherit;\n border-radius: 4px;\n padding: 0 1px;\n }\n`;\n\nconst StyledEmpty = styled.div<{ theme: Theme }>`\n padding: 20px 20px 12px;\n min-height: 40px;\n display: flex;\n align-items: center;\n justify-content: center;\n /* Separates the spinner from \"Searching documentation...\"; the whitespace\n between them in the markup collapses away as an anonymous flex item. */\n gap: 8px;\n text-align: center;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n color: ${({ theme }) => theme.colors.gray};\n`;\n\nconst StyledLiveStatus = styled.div`\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n border: 0;\n`;\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nfunction highlightMatch(snippet: string, query: string): string {\n const escaped = escapeHtml(snippet);\n if (!query.trim()) return escaped;\n const q = escapeHtml(query.trim());\n const regex = new RegExp(\n `(${q.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")})`,\n \"gi\",\n );\n return escaped.replace(regex, \"<mark>$1</mark>\");\n}\n\nexport function SearchModalContent({\n isClosing,\n closeSearch,\n onCloseAnimationEnd,\n query,\n setQuery,\n activeIndex,\n setActiveIndex,\n resultsRef,\n onKeyDown,\n merged,\n sectionLabels,\n isSearching,\n navigate,\n canAskAssistant,\n onAskAssistant,\n shouldRestoreFocus,\n returnFocusTo,\n}: SearchModalContentProps) {\n const dialogRef = React.useRef<HTMLDivElement | null>(null);\n const inputRef = React.useRef<HTMLInputElement | null>(null);\n const previouslyFocusedRef = React.useRef<HTMLElement | null>(\n returnFocusTo?.isConnected === true\n ? returnFocusTo\n : typeof document === \"undefined\"\n ? null\n : (document.activeElement as HTMLElement | null),\n );\n const listboxId = React.useId();\n const optionId = (index: number) => listboxId + \"-option-\" + index;\n const t = useStrings();\n\n React.useEffect(() => {\n const previouslyFocused = previouslyFocusedRef.current;\n const containFocus = (event: FocusEvent) => {\n if (\n event.target instanceof Node &&\n !dialogRef.current?.contains(event.target)\n ) {\n inputRef.current?.focus();\n }\n };\n\n document.addEventListener(\"focusin\", containFocus);\n inputRef.current?.focus();\n\n return () => {\n document.removeEventListener(\"focusin\", containFocus);\n if (shouldRestoreFocus() && previouslyFocused?.isConnected) {\n previouslyFocused.focus();\n }\n };\n }, [shouldRestoreFocus]);\n\n const handleDialogKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (event.key === \"Escape\") {\n event.preventDefault();\n event.stopPropagation();\n closeSearch();\n return;\n }\n\n if (event.key !== \"Tab\") return;\n\n const focusable = Array.from(\n dialogRef.current?.querySelectorAll<HTMLElement>(\n 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex=\"-1\"])',\n ) ?? [],\n ).filter(\n (element) =>\n element.offsetParent !== null &&\n element.getAttribute(\"aria-hidden\") !== \"true\",\n );\n\n if (focusable.length === 0) {\n event.preventDefault();\n return;\n }\n\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n // Measure the active item so the sliding highlight can be placed over it.\n // useLayoutEffect runs before paint, so the first position is committed\n // without a transition (no slide-in on open); later activeIndex/hover\n // changes glide because only the transform + height differ.\n const [indicator, setIndicator] = React.useState<{\n top: number;\n height: number;\n } | null>(null);\n\n React.useLayoutEffect(() => {\n const list = resultsRef.current;\n if (!list) {\n setIndicator(null);\n return;\n }\n const items = list.querySelectorAll(\"li\");\n const active = items[activeIndex] as HTMLElement | undefined;\n if (!active) {\n setIndicator(null);\n return;\n }\n setIndicator({ top: active.offsetTop, height: active.offsetHeight });\n\n // Keep the active row inside the scroll viewport in the SAME pre-paint pass\n // that positions the highlight, so the two never desync into a one-frame\n // flicker. merged is a dependency, so re-filtering (a new query) also\n // re-scrolls the reset active row into view even when its index is\n // unchanged. This list is flat (no group headers), so no header inclusion\n // is needed; a small margin keeps rows off the container's hard edges.\n // Adjust scrollTop directly (never scrollIntoView, which can also pan\n // ancestors).\n const margin = 8;\n const viewTop = active.offsetTop - margin;\n const viewBottom = active.offsetTop + active.offsetHeight + margin;\n\n if (viewTop < list.scrollTop) {\n list.scrollTop = viewTop;\n } else if (viewBottom > list.scrollTop + list.clientHeight) {\n list.scrollTop = viewBottom - list.clientHeight;\n }\n }, [activeIndex, merged, resultsRef]);\n\n return (\n <StyledBackdrop\n $isClosing={isClosing}\n onClick={closeSearch}\n onAnimationEnd={(e) => {\n // animationend bubbles, so this handler also fires for animations\n // completing on descendants (the inner modal, icons, result items).\n // Only the backdrop's own exit animation should trigger the unmount -\n // otherwise a child finishing its animation first tears the modal down\n // before the close animation plays, making it vanish instantly.\n if (e.target === e.currentTarget) onCloseAnimationEnd();\n }}\n >\n <StyledModal\n ref={dialogRef}\n $isClosing={isClosing}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={t.searchDialog}\n data-search-dialog\n onKeyDownCapture={handleDialogKeyDown}\n onClick={(e) => e.stopPropagation()}\n >\n <StyledInputWrapper>\n <Search size={18} />\n <StyledInput\n ref={inputRef}\n type=\"search\"\n value={query}\n onChange={(e) => {\n setQuery(e.target.value);\n setActiveIndex(0);\n }}\n onKeyDown={onKeyDown}\n placeholder={t.searchPlaceholder}\n autoComplete=\"off\"\n spellCheck={false}\n aria-label={t.searchDialog}\n role=\"combobox\"\n aria-autocomplete=\"list\"\n aria-haspopup=\"listbox\"\n aria-expanded=\"true\"\n aria-controls={listboxId}\n aria-activedescendant={\n merged[activeIndex] ? optionId(activeIndex) : undefined\n }\n />\n {canAskAssistant && (\n <StyledAskAssistant\n type=\"button\"\n onClick={onAskAssistant}\n disabled={!query.trim()}\n aria-label={t.askAi}\n title={t.askAi}\n >\n {t.askAi}\n <StyledAskKeys aria-hidden=\"true\">\n <StyledAskKbd>&#8997;</StyledAskKbd>\n <StyledAskKbd>\n <StyledReturnGlyph>&#8629;</StyledReturnGlyph>\n </StyledAskKbd>\n </StyledAskKeys>\n </StyledAskAssistant>\n )}\n <IconButton\n onClick={closeSearch}\n aria-label={t.closeSearch}\n title={t.closeSearch}\n >\n <X />\n </IconButton>\n </StyledInputWrapper>\n <StyledLiveStatus role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">\n {isSearching\n ? t.searching\n : merged.length === 0\n ? t.noResults\n : merged.length === 1\n ? t.resultAvailable\n : withCount(t.resultsAvailable, merged.length)}\n </StyledLiveStatus>\n <StyledResults\n ref={resultsRef}\n id={listboxId}\n role=\"listbox\"\n aria-label={t.searchResults}\n aria-busy={isSearching}\n hidden={merged.length === 0}\n >\n {indicator && (\n <StyledHighlight\n aria-hidden=\"true\"\n $top={indicator.top}\n $height={indicator.height}\n />\n )}\n {merged.map((result, index) => (\n <StyledResultItem\n key={result.page.slug + result.page.section}\n id={optionId(index)}\n role=\"option\"\n aria-selected={index === activeIndex}\n $isActive={index === activeIndex}\n onClick={(e) => navigate(result.page.slug, e)}\n onMouseEnter={() => setActiveIndex(index)}\n >\n <StyledResultTitle>{result.page.title}</StyledResultTitle>\n <StyledResultMeta>\n {result.page.section\n ? `${sectionLabels[result.page.section] || result.page.section} / `\n : \"\"}\n {result.page.category}\n </StyledResultMeta>\n {result.snippet && (\n <StyledSnippet\n dangerouslySetInnerHTML={{\n __html: highlightMatch(result.snippet, query),\n }}\n />\n )}\n </StyledResultItem>\n ))}\n </StyledResults>\n {merged.length === 0 && (\n <StyledEmpty aria-hidden=\"true\">\n {isSearching ? (\n <>\n <Spinner size={18} /> {t.searching}...\n </>\n ) : (\n t.noResults\n )}\n </StyledEmpty>\n )}\n </StyledModal>\n </StyledBackdrop>\n );\n}\n";
@@ -5,6 +5,8 @@ import { Search, X } from "lucide-react";
5
5
  import { IconButton } from "cherry-styled-components";
6
6
  import { mq, Theme } from "@/app/theme";
7
7
  import { Spinner } from "@/components/Spinner";
8
+ import { useStrings } from "@/components/useStrings";
9
+ import { withCount } from "@/utils/strings";
8
10
  import {
9
11
  interactiveStyles,
10
12
  thinScrollbar,
@@ -16,6 +18,8 @@ export interface PageItem {
16
18
  description?: string;
17
19
  category: string;
18
20
  section?: string;
21
+ locale?: string;
22
+ version?: string;
19
23
  }
20
24
 
21
25
  export interface MergedResult {
@@ -124,6 +128,7 @@ const StyledInputWrapper = styled.div<{ theme: Theme }>\`
124
128
 
125
129
  const StyledInput = styled.input<{ theme: Theme }>\`
126
130
  flex: 1;
131
+ padding: 0;
127
132
  border: none;
128
133
  outline: none;
129
134
  background: transparent;
@@ -392,6 +397,7 @@ export function SearchModalContent({
392
397
  );
393
398
  const listboxId = React.useId();
394
399
  const optionId = (index: number) => listboxId + "-option-" + index;
400
+ const t = useStrings();
395
401
 
396
402
  React.useEffect(() => {
397
403
  const previouslyFocused = previouslyFocusedRef.current;
@@ -511,7 +517,7 @@ export function SearchModalContent({
511
517
  $isClosing={isClosing}
512
518
  role="dialog"
513
519
  aria-modal="true"
514
- aria-label="Search documentation"
520
+ aria-label={t.searchDialog}
515
521
  data-search-dialog
516
522
  onKeyDownCapture={handleDialogKeyDown}
517
523
  onClick={(e) => e.stopPropagation()}
@@ -527,10 +533,10 @@ export function SearchModalContent({
527
533
  setActiveIndex(0);
528
534
  }}
529
535
  onKeyDown={onKeyDown}
530
- placeholder="Search docs..."
536
+ placeholder={t.searchPlaceholder}
531
537
  autoComplete="off"
532
538
  spellCheck={false}
533
- aria-label="Search documentation"
539
+ aria-label={t.searchDialog}
534
540
  role="combobox"
535
541
  aria-autocomplete="list"
536
542
  aria-haspopup="listbox"
@@ -545,10 +551,10 @@ export function SearchModalContent({
545
551
  type="button"
546
552
  onClick={onAskAssistant}
547
553
  disabled={!query.trim()}
548
- aria-label="Ask AI"
549
- title="Ask AI"
554
+ aria-label={t.askAi}
555
+ title={t.askAi}
550
556
  >
551
- Ask AI
557
+ {t.askAi}
552
558
  <StyledAskKeys aria-hidden="true">
553
559
  <StyledAskKbd>&#8997;</StyledAskKbd>
554
560
  <StyledAskKbd>
@@ -559,24 +565,26 @@ export function SearchModalContent({
559
565
  )}
560
566
  <IconButton
561
567
  onClick={closeSearch}
562
- aria-label="Close search"
563
- title="Close search"
568
+ aria-label={t.closeSearch}
569
+ title={t.closeSearch}
564
570
  >
565
571
  <X />
566
572
  </IconButton>
567
573
  </StyledInputWrapper>
568
574
  <StyledLiveStatus role="status" aria-live="polite" aria-atomic="true">
569
575
  {isSearching
570
- ? "Searching documentation"
576
+ ? t.searching
571
577
  : merged.length === 0
572
- ? "No search results found"
573
- : \`\${merged.length} search \${merged.length === 1 ? "result" : "results"} available\`}
578
+ ? t.noResults
579
+ : merged.length === 1
580
+ ? t.resultAvailable
581
+ : withCount(t.resultsAvailable, merged.length)}
574
582
  </StyledLiveStatus>
575
583
  <StyledResults
576
584
  ref={resultsRef}
577
585
  id={listboxId}
578
586
  role="listbox"
579
- aria-label="Search results"
587
+ aria-label={t.searchResults}
580
588
  aria-busy={isSearching}
581
589
  hidden={merged.length === 0}
582
590
  >
@@ -618,10 +626,10 @@ export function SearchModalContent({
618
626
  <StyledEmpty aria-hidden="true">
619
627
  {isSearching ? (
620
628
  <>
621
- <Spinner size={18} /> Searching documentation...
629
+ <Spinner size={18} /> {t.searching}...
622
630
  </>
623
631
  ) : (
624
- "No results found"
632
+ t.noResults
625
633
  )}
626
634
  </StyledEmpty>
627
635
  )}
@@ -1 +1 @@
1
- export declare const sectionNavProviderTemplate = "\"use client\";\nimport { useMemo } from \"react\";\nimport { usePathname } from \"next/navigation\";\nimport { SideBar } from \"@/components/SideBar\";\nimport { DocsNavigation } from \"@/components/layout/DocsNavigation\";\nimport { SectionBarProvider } from \"@/components/layout/DocsComponents\";\nimport { Footer } from \"@/components/layout/Footer\";\nimport { StaticLinks } from \"@/components/layout/StaticLinks\";\nimport {\n transformPagesToGroupedStructure,\n type PagesProps,\n} from \"@/utils/orderNavItems\";\nimport rawNavigation from \"@/navigation.json\";\n\n// navigation.json can be an array (root section only) or an object keyed by section slug\ntype NavLink = {\n slug?: string;\n title: string;\n icon?: string;\n links?: NavLink[];\n};\ntype NavItem = { label: string; icon?: string; links: NavLink[] };\ntype NavigationConfig = NavItem[] | Record<string, NavItem[]>;\n\nconst navigation = rawNavigation as NavigationConfig;\n\nfunction getNavigationForSection(\n nav: NavigationConfig,\n sectionSlug: string,\n): NavItem[] | null {\n if (Array.isArray(nav)) {\n return sectionSlug === \"\" && nav.length ? nav : null;\n }\n const sectionNav = nav[sectionSlug];\n return sectionNav && sectionNav.length ? sectionNav : null;\n}\n\ninterface SectionConfig {\n label: string;\n slug: string;\n directory?: string;\n}\n\ninterface SectionNavProviderProps {\n sections: SectionConfig[];\n allPages: PagesProps[];\n hideBranding: boolean;\n children: React.ReactNode;\n}\n\nfunction SectionNavProvider({\n sections,\n allPages,\n hideBranding,\n children,\n}: SectionNavProviderProps) {\n const pathname = usePathname();\n const currentPath = pathname.replace(/^\\//, \"\").replace(/\\/$/, \"\");\n\n const activeSectionSlug = useMemo(() => {\n const match = sections.find((section) => {\n if (section.slug === \"\") return false;\n return (\n currentPath === section.slug ||\n currentPath.startsWith(section.slug + \"/\")\n );\n });\n return match ? match.slug : \"\";\n }, [sections, currentPath]);\n\n const result = useMemo(() => {\n const sectionNav = getNavigationForSection(navigation, activeSectionSlug);\n if (sectionNav) return sectionNav;\n const filtered = allPages.filter(\n (page) => (page.section || \"\") === activeSectionSlug,\n );\n return transformPagesToGroupedStructure(filtered);\n }, [allPages, activeSectionSlug]);\n\n // Fallback when no pages exist yet (also defined in layout.tsx for the non-sections path)\n const defaultPages = [\n {\n slug: \"\",\n title: \"Getting Started\",\n description:\n \"Doccupine is a free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.\",\n date: \"2025-01-15\",\n category: \"Introduction\",\n categoryOrder: 0,\n categoryIcon: \"rocket\",\n order: 0,\n },\n ];\n\n const defaultResults = transformPagesToGroupedStructure(defaultPages);\n\n return (\n <SectionBarProvider hasSectionBar={true}>\n <SideBar result={result.length ? result : defaultResults} />\n {children}\n <DocsNavigation result={result.length ? result : defaultResults} />\n <StaticLinks />\n <Footer hideBranding={hideBranding} />\n </SectionBarProvider>\n );\n}\n\nexport { SectionNavProvider };\n";
1
+ export declare const sectionNavProviderTemplate = "\"use client\";\nimport { useMemo } from \"react\";\nimport { SideBar } from \"@/components/SideBar\";\nimport { useVariant } from \"@/components/useVariant\";\nimport { DocsNavigation } from \"@/components/layout/DocsNavigation\";\nimport { SectionBarProvider } from \"@/components/layout/DocsComponents\";\nimport { Footer } from \"@/components/layout/Footer\";\nimport { StaticLinks } from \"@/components/layout/StaticLinks\";\nimport {\n transformPagesToGroupedStructure,\n type PagesProps,\n} from \"@/utils/orderNavItems\";\nimport { navigationScopeKey, pageVariantPrefix } from \"@/utils/variants\";\nimport rawNavigation from \"@/navigation.json\";\n\n// navigation.json can be an array (root scope only) or an object keyed by the\n// URL prefix of each scope: a section slug (\"api\"), a language or version\n// prefix (\"de\", \"v1\", \"de/v1\"), or both (\"de/api\").\ntype NavLink = {\n slug?: string;\n title: string;\n icon?: string;\n links?: NavLink[];\n};\ntype NavItem = { label: string; icon?: string; links: NavLink[] };\ntype NavigationConfig = NavItem[] | Record<string, NavItem[]>;\n\nconst navigation = rawNavigation as NavigationConfig;\n\nfunction getNavigationForScope(\n nav: NavigationConfig,\n scopeKey: string,\n): NavItem[] | null {\n if (Array.isArray(nav)) {\n return scopeKey === \"\" && nav.length ? nav : null;\n }\n const scopeNav = nav[scopeKey];\n return scopeNav && scopeNav.length ? scopeNav : null;\n}\n\ninterface SectionConfig {\n label: string;\n slug: string;\n directory?: string;\n}\n\ninterface SectionNavProviderProps {\n sections: SectionConfig[];\n allPages: PagesProps[];\n hideBranding: boolean;\n /** False when the site has no section bar (languages or versions only). */\n hasSectionBar?: boolean;\n children: React.ReactNode;\n}\n\nfunction SectionNavProvider({\n sections,\n allPages,\n hideBranding,\n hasSectionBar = true,\n children,\n}: SectionNavProviderProps) {\n // Sections and pages are matched inside the current language/version, so\n // the sidebar of /de/api lists the German API pages only.\n const { prefix, rest } = useVariant();\n\n const activeSectionSlug = useMemo(() => {\n const match = sections.find((section) => {\n if (section.slug === \"\") return false;\n return rest === section.slug || rest.startsWith(section.slug + \"/\");\n });\n return match ? match.slug : \"\";\n }, [sections, rest]);\n\n const result = useMemo(() => {\n const scopeNav = getNavigationForScope(\n navigation,\n navigationScopeKey(prefix, activeSectionSlug),\n );\n if (scopeNav) return scopeNav;\n const filtered = allPages.filter(\n (page) =>\n pageVariantPrefix(page) === prefix &&\n (page.section || \"\") === activeSectionSlug,\n );\n return transformPagesToGroupedStructure(filtered);\n }, [allPages, activeSectionSlug, prefix]);\n\n // Fallback when no pages exist yet (also defined in layout.tsx for the non-sections path)\n const defaultPages = [\n {\n slug: \"\",\n title: \"Getting Started\",\n description:\n \"Doccupine is a free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.\",\n date: \"2025-01-15\",\n category: \"Introduction\",\n categoryOrder: 0,\n categoryIcon: \"rocket\",\n order: 0,\n },\n ];\n\n const defaultResults = transformPagesToGroupedStructure(defaultPages);\n\n return (\n <SectionBarProvider hasSectionBar={hasSectionBar}>\n <SideBar\n result={result.length ? result : defaultResults}\n pages={allPages}\n />\n {children}\n <DocsNavigation result={result.length ? result : defaultResults} />\n <StaticLinks />\n <Footer hideBranding={hideBranding} />\n </SectionBarProvider>\n );\n}\n\nexport { SectionNavProvider };\n";
@@ -1,8 +1,8 @@
1
1
  import { DEFAULT_DESCRIPTION } from "../../lib/constants.js";
2
2
  export const sectionNavProviderTemplate = `"use client";
3
3
  import { useMemo } from "react";
4
- import { usePathname } from "next/navigation";
5
4
  import { SideBar } from "@/components/SideBar";
5
+ import { useVariant } from "@/components/useVariant";
6
6
  import { DocsNavigation } from "@/components/layout/DocsNavigation";
7
7
  import { SectionBarProvider } from "@/components/layout/DocsComponents";
8
8
  import { Footer } from "@/components/layout/Footer";
@@ -11,9 +11,12 @@ import {
11
11
  transformPagesToGroupedStructure,
12
12
  type PagesProps,
13
13
  } from "@/utils/orderNavItems";
14
+ import { navigationScopeKey, pageVariantPrefix } from "@/utils/variants";
14
15
  import rawNavigation from "@/navigation.json";
15
16
 
16
- // navigation.json can be an array (root section only) or an object keyed by section slug
17
+ // navigation.json can be an array (root scope only) or an object keyed by the
18
+ // URL prefix of each scope: a section slug ("api"), a language or version
19
+ // prefix ("de", "v1", "de/v1"), or both ("de/api").
17
20
  type NavLink = {
18
21
  slug?: string;
19
22
  title: string;
@@ -25,15 +28,15 @@ type NavigationConfig = NavItem[] | Record<string, NavItem[]>;
25
28
 
26
29
  const navigation = rawNavigation as NavigationConfig;
27
30
 
28
- function getNavigationForSection(
31
+ function getNavigationForScope(
29
32
  nav: NavigationConfig,
30
- sectionSlug: string,
33
+ scopeKey: string,
31
34
  ): NavItem[] | null {
32
35
  if (Array.isArray(nav)) {
33
- return sectionSlug === "" && nav.length ? nav : null;
36
+ return scopeKey === "" && nav.length ? nav : null;
34
37
  }
35
- const sectionNav = nav[sectionSlug];
36
- return sectionNav && sectionNav.length ? sectionNav : null;
38
+ const scopeNav = nav[scopeKey];
39
+ return scopeNav && scopeNav.length ? scopeNav : null;
37
40
  }
38
41
 
39
42
  interface SectionConfig {
@@ -46,6 +49,8 @@ interface SectionNavProviderProps {
46
49
  sections: SectionConfig[];
47
50
  allPages: PagesProps[];
48
51
  hideBranding: boolean;
52
+ /** False when the site has no section bar (languages or versions only). */
53
+ hasSectionBar?: boolean;
49
54
  children: React.ReactNode;
50
55
  }
51
56
 
@@ -53,30 +58,34 @@ function SectionNavProvider({
53
58
  sections,
54
59
  allPages,
55
60
  hideBranding,
61
+ hasSectionBar = true,
56
62
  children,
57
63
  }: SectionNavProviderProps) {
58
- const pathname = usePathname();
59
- const currentPath = pathname.replace(/^\\//, "").replace(/\\/$/, "");
64
+ // Sections and pages are matched inside the current language/version, so
65
+ // the sidebar of /de/api lists the German API pages only.
66
+ const { prefix, rest } = useVariant();
60
67
 
61
68
  const activeSectionSlug = useMemo(() => {
62
69
  const match = sections.find((section) => {
63
70
  if (section.slug === "") return false;
64
- return (
65
- currentPath === section.slug ||
66
- currentPath.startsWith(section.slug + "/")
67
- );
71
+ return rest === section.slug || rest.startsWith(section.slug + "/");
68
72
  });
69
73
  return match ? match.slug : "";
70
- }, [sections, currentPath]);
74
+ }, [sections, rest]);
71
75
 
72
76
  const result = useMemo(() => {
73
- const sectionNav = getNavigationForSection(navigation, activeSectionSlug);
74
- if (sectionNav) return sectionNav;
77
+ const scopeNav = getNavigationForScope(
78
+ navigation,
79
+ navigationScopeKey(prefix, activeSectionSlug),
80
+ );
81
+ if (scopeNav) return scopeNav;
75
82
  const filtered = allPages.filter(
76
- (page) => (page.section || "") === activeSectionSlug,
83
+ (page) =>
84
+ pageVariantPrefix(page) === prefix &&
85
+ (page.section || "") === activeSectionSlug,
77
86
  );
78
87
  return transformPagesToGroupedStructure(filtered);
79
- }, [allPages, activeSectionSlug]);
88
+ }, [allPages, activeSectionSlug, prefix]);
80
89
 
81
90
  // Fallback when no pages exist yet (also defined in layout.tsx for the non-sections path)
82
91
  const defaultPages = [
@@ -96,8 +105,11 @@ function SectionNavProvider({
96
105
  const defaultResults = transformPagesToGroupedStructure(defaultPages);
97
106
 
98
107
  return (
99
- <SectionBarProvider hasSectionBar={true}>
100
- <SideBar result={result.length ? result : defaultResults} />
108
+ <SectionBarProvider hasSectionBar={hasSectionBar}>
109
+ <SideBar
110
+ result={result.length ? result : defaultResults}
111
+ pages={allPages}
112
+ />
101
113
  {children}
102
114
  <DocsNavigation result={result.length ? result : defaultResults} />
103
115
  <StaticLinks />
@@ -1 +1 @@
1
- export declare const sideBarTemplate = "\"use client\";\nimport { useContext, useEffect, useId, useRef, useState } from \"react\";\nimport { usePathname } from \"next/navigation\";\nimport { Flex, Space, ThemeToggle } from \"cherry-styled-components\";\nimport { httpMethodBadgeColor } from \"@/components/layout/Badge\";\nimport {\n DocsSidebar,\n SectionBarContext,\n StyledSidebar,\n StyledSidebarList,\n StyledSidebarListItem,\n StyledStrong,\n StyledSidebarListItemLink,\n StyledSidebarMethodTag,\n StyledSidebarGroupButton,\n StyledSidebarGroupRow,\n StyledSidebarGroupLink,\n StyledSidebarGroupChevron,\n StyledSidebarGroupContent,\n StyledSidebarFooter,\n StyleMobileBar,\n StyledMobileBurger,\n} from \"@/components/layout/DocsComponents\";\nimport { FocusModeToggle } from \"@/components/layout/FocusModeToggle\";\nimport { Icon } from \"@/components/layout/Icon\";\nimport { useLockBodyScroll } from \"@/components/LockBodyScroll\";\n\n// A link can be a leaf (slug + title) or a group with nested children. Both the\n// category icon and the per-link icon are optional Lucide names.\ntype NavItemLink = {\n slug?: string;\n title: string;\n icon?: string;\n httpMethod?: string;\n links?: NavItemLink[];\n};\n\ntype NavItem = {\n label: string;\n icon?: string;\n links: NavItemLink[];\n};\n\ninterface SideBarProps {\n result: NavItem[];\n}\n\nfunction linkContainsActivePath(link: NavItemLink, pathname: string): boolean {\n if (link.slug !== undefined && pathname === `/${link.slug}`) {\n return true;\n }\n return (link.links ?? []).some((child) =>\n linkContainsActivePath(child, pathname),\n );\n}\n\nfunction SidebarNavLink({\n link,\n depth,\n pathname,\n onNavigate,\n}: {\n link: NavItemLink;\n depth: number;\n pathname: string;\n onNavigate: () => void;\n}) {\n const children = link.links ?? [];\n const hasChildren = children.length > 0;\n const href = link.slug !== undefined ? `/${link.slug}` : undefined;\n const isActive = href !== undefined && pathname === href;\n const indent = { paddingLeft: `${20 + depth * 14}px` };\n const groupContentId = useId();\n\n // Open collapsible groups that contain the active page so deep links land\n // with their ancestors already expanded.\n const [isOpen, setIsOpen] = useState(\n hasChildren\n ? children.some((child) => linkContainsActivePath(child, pathname))\n : false,\n );\n\n if (!hasChildren) {\n return (\n <StyledSidebarListItem>\n <StyledSidebarListItemLink\n href={href ?? \"#\"}\n $isActive={isActive}\n aria-current={isActive ? \"page\" : undefined}\n onClick={onNavigate}\n style={indent}\n >\n {link.httpMethod && (\n <StyledSidebarMethodTag\n mono\n solid={isActive}\n size=\"xs\"\n color={httpMethodBadgeColor(link.httpMethod)}\n >\n {link.httpMethod}\n </StyledSidebarMethodTag>\n )}\n {link.icon && <Icon name={link.icon} size={16} />}\n {link.title}\n </StyledSidebarListItemLink>\n </StyledSidebarListItem>\n );\n }\n\n const toggle = () => setIsOpen((prev) => !prev);\n const toggleLabel = isOpen\n ? `Collapse ${link.title}`\n : `Expand ${link.title}`;\n const groupActive = linkContainsActivePath(link, pathname);\n\n return (\n <li>\n {href !== undefined ? (\n <StyledSidebarGroupRow\n $isActive={groupActive}\n $isOpen={isOpen}\n style={indent}\n >\n <StyledSidebarGroupLink\n href={href}\n aria-current={pathname === href ? \"page\" : undefined}\n onClick={onNavigate}\n >\n {link.icon && <Icon name={link.icon} size={16} />}\n {link.title}\n </StyledSidebarGroupLink>\n <StyledSidebarGroupChevron\n type=\"button\"\n onClick={toggle}\n aria-expanded={isOpen}\n aria-controls={groupContentId}\n aria-label={toggleLabel}\n >\n <Icon name=\"chevron-right\" size={16} />\n </StyledSidebarGroupChevron>\n </StyledSidebarGroupRow>\n ) : (\n <StyledSidebarGroupButton\n type=\"button\"\n onClick={toggle}\n $isActive={groupActive}\n $isOpen={isOpen}\n style={indent}\n aria-expanded={isOpen}\n aria-controls={groupContentId}\n aria-label={toggleLabel}\n >\n {link.icon && <Icon name={link.icon} size={16} />}\n {link.title}\n <Icon name=\"chevron-right\" size={16} />\n </StyledSidebarGroupButton>\n )}\n <StyledSidebarGroupContent id={groupContentId} $isOpen={isOpen}>\n {children.map((child: NavItemLink, index: number) => (\n <SidebarNavLink\n key={index}\n link={child}\n depth={depth + 1}\n pathname={pathname}\n onNavigate={onNavigate}\n />\n ))}\n </StyledSidebarGroupContent>\n </li>\n );\n}\n\nfunction SideBar({ result }: SideBarProps) {\n const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);\n const hasSectionBar = useContext(SectionBarContext);\n const pathname = usePathname();\n const sidebarId = useId();\n const navRef = useRef<HTMLElement>(null);\n const footerRef = useRef<HTMLDivElement>(null);\n\n useLockBodyScroll(isMobileMenuOpen);\n\n // Bring the current page's link into view within the sidebar's own scroll\n // area when it starts off-screen (deep pages, in-content links, search).\n // Scoped to the nav via scrollTo so the main document never jumps.\n useEffect(() => {\n const nav = navRef.current;\n if (!nav) return;\n const active = nav.querySelector<HTMLElement>('[aria-current=\"page\"]');\n if (!active) return;\n\n const navRect = nav.getBoundingClientRect();\n const activeRect = active.getBoundingClientRect();\n\n // The theme-toggle footer is sticky over the bottom of the scroll area\n // (~60px tall), so links underneath it are covered rather than visible.\n // Clamp the visible bottom to the footer's top edge when it's pinned.\n const footerRect = footerRef.current?.getBoundingClientRect();\n const visibleBottom = footerRect\n ? Math.min(navRect.bottom, footerRect.top)\n : navRect.bottom;\n\n const isOutOfView =\n activeRect.top < navRect.top || activeRect.bottom > visibleBottom;\n if (!isOutOfView) return;\n\n // Center within the visible band (nav top .. footer top), not the full\n // nav height, so the link never settles behind the footer.\n const visibleHeight = visibleBottom - navRect.top;\n const target =\n nav.scrollTop +\n (activeRect.top - navRect.top) -\n (visibleHeight - active.clientHeight) / 2;\n\n // Animate the scroll, but honor users who opt out of motion.\n const prefersReducedMotion = window.matchMedia(\n \"(prefers-reduced-motion: reduce)\",\n ).matches;\n nav.scrollTo({\n top: Math.max(0, target),\n behavior: prefersReducedMotion ? \"auto\" : \"smooth\",\n });\n }, [pathname]);\n\n return (\n <DocsSidebar>\n <StyleMobileBar\n onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}\n $isActive={isMobileMenuOpen}\n aria-label={\n isMobileMenuOpen ? \"Close navigation menu\" : \"Open navigation menu\"\n }\n aria-expanded={isMobileMenuOpen}\n aria-controls={sidebarId}\n >\n <StyledMobileBurger $isActive={isMobileMenuOpen} />\n </StyleMobileBar>\n\n <StyledSidebar\n id={sidebarId}\n ref={navRef}\n $isActive={isMobileMenuOpen}\n $hasSectionBar={hasSectionBar}\n >\n {result &&\n result.map((item: NavItem, index: number) => {\n return (\n <StyledSidebarList key={index}>\n <StyledSidebarListItem>\n <StyledStrong>\n {item.icon && <Icon name={item.icon} size={16} />}\n {item.label}\n </StyledStrong>{\" \"}\n </StyledSidebarListItem>\n <li>\n <Space $size={20} />\n </li>\n {item.links &&\n item.links.map((link: NavItemLink, indexChild: number) => (\n <SidebarNavLink\n key={indexChild}\n link={link}\n depth={0}\n pathname={pathname}\n onNavigate={() => setIsMobileMenuOpen(false)}\n />\n ))}\n <li aria-hidden=\"true\">\n <Space $size={20} />\n </li>\n </StyledSidebarList>\n );\n })}\n <StyledSidebarFooter ref={footerRef}>\n <Flex $xsJustifyContent=\"flex-start\" $lgJustifyContent=\"flex-end\">\n <ThemeToggle $shortcut />\n </Flex>\n </StyledSidebarFooter>\n </StyledSidebar>\n\n {/* Outside StyledSidebar on purpose: focus mode slides that whole\n column away, and the toggle has to survive it. */}\n <FocusModeToggle />\n </DocsSidebar>\n );\n}\n\nexport { SideBar };\n";
1
+ export declare const sideBarTemplate = "\"use client\";\nimport { useContext, useEffect, useId, useRef, useState } from \"react\";\nimport { usePathname } from \"next/navigation\";\nimport { useStrings } from \"@/components/useStrings\";\nimport { Space, ThemeToggle } from \"cherry-styled-components\";\nimport { httpMethodBadgeColor } from \"@/components/layout/Badge\";\nimport {\n DocsSidebar,\n SectionBarContext,\n StyledSidebar,\n StyledSidebarList,\n StyledSidebarListItem,\n StyledStrong,\n StyledSidebarListItemLink,\n StyledSidebarMethodTag,\n StyledSidebarGroupButton,\n StyledSidebarGroupRow,\n StyledSidebarGroupLink,\n StyledSidebarGroupChevron,\n StyledSidebarGroupContent,\n StyledSidebarFooter,\n StyledSidebarFooterToggle,\n StyleMobileBar,\n StyledMobileBurger,\n} from \"@/components/layout/DocsComponents\";\nimport { FocusModeToggle } from \"@/components/layout/FocusModeToggle\";\nimport { Icon } from \"@/components/layout/Icon\";\nimport { VariantSwitchers } from \"@/components/layout/VariantSwitchers\";\nimport { useLockBodyScroll } from \"@/components/LockBodyScroll\";\nimport type { PagesProps } from \"@/utils/orderNavItems\";\n\n// A link can be a leaf (slug + title) or a group with nested children. Both the\n// category icon and the per-link icon are optional Lucide names.\ntype NavItemLink = {\n slug?: string;\n title: string;\n icon?: string;\n httpMethod?: string;\n links?: NavItemLink[];\n};\n\ntype NavItem = {\n label: string;\n icon?: string;\n links: NavItemLink[];\n};\n\ninterface SideBarProps {\n result: NavItem[];\n /** Every page of the site. The language and version switchers in the footer\n resolve the current page's counterpart from it; sites without\n languages.json or versions.json never render them. */\n pages?: PagesProps[];\n}\n\nfunction linkContainsActivePath(link: NavItemLink, pathname: string): boolean {\n if (link.slug !== undefined && pathname === `/${link.slug}`) {\n return true;\n }\n return (link.links ?? []).some((child) =>\n linkContainsActivePath(child, pathname),\n );\n}\n\nfunction SidebarNavLink({\n link,\n depth,\n pathname,\n onNavigate,\n}: {\n link: NavItemLink;\n depth: number;\n pathname: string;\n onNavigate: () => void;\n}) {\n const children = link.links ?? [];\n const hasChildren = children.length > 0;\n const href = link.slug !== undefined ? `/${link.slug}` : undefined;\n const isActive = href !== undefined && pathname === href;\n const indent = { paddingLeft: `${20 + depth * 14}px` };\n const groupContentId = useId();\n const t = useStrings();\n\n // Open collapsible groups that contain the active page so deep links land\n // with their ancestors already expanded.\n const [isOpen, setIsOpen] = useState(\n hasChildren\n ? children.some((child) => linkContainsActivePath(child, pathname))\n : false,\n );\n\n if (!hasChildren) {\n return (\n <StyledSidebarListItem>\n <StyledSidebarListItemLink\n href={href ?? \"#\"}\n $isActive={isActive}\n aria-current={isActive ? \"page\" : undefined}\n onClick={onNavigate}\n style={indent}\n >\n {link.httpMethod && (\n <StyledSidebarMethodTag\n mono\n solid={isActive}\n size=\"xs\"\n color={httpMethodBadgeColor(link.httpMethod)}\n >\n {link.httpMethod}\n </StyledSidebarMethodTag>\n )}\n {link.icon && <Icon name={link.icon} size={16} />}\n {link.title}\n </StyledSidebarListItemLink>\n </StyledSidebarListItem>\n );\n }\n\n const toggle = () => setIsOpen((prev) => !prev);\n const toggleLabel = (isOpen ? t.collapseGroup : t.expandGroup).replace(\n \"{title}\",\n link.title,\n );\n const groupActive = linkContainsActivePath(link, pathname);\n\n return (\n <li>\n {href !== undefined ? (\n <StyledSidebarGroupRow\n $isActive={groupActive}\n $isOpen={isOpen}\n style={indent}\n >\n <StyledSidebarGroupLink\n href={href}\n aria-current={pathname === href ? \"page\" : undefined}\n onClick={onNavigate}\n >\n {link.icon && <Icon name={link.icon} size={16} />}\n {link.title}\n </StyledSidebarGroupLink>\n <StyledSidebarGroupChevron\n type=\"button\"\n onClick={toggle}\n aria-expanded={isOpen}\n aria-controls={groupContentId}\n aria-label={toggleLabel}\n >\n <Icon name=\"chevron-right\" size={16} />\n </StyledSidebarGroupChevron>\n </StyledSidebarGroupRow>\n ) : (\n <StyledSidebarGroupButton\n type=\"button\"\n onClick={toggle}\n $isActive={groupActive}\n $isOpen={isOpen}\n style={indent}\n aria-expanded={isOpen}\n aria-controls={groupContentId}\n aria-label={toggleLabel}\n >\n {link.icon && <Icon name={link.icon} size={16} />}\n {link.title}\n <Icon name=\"chevron-right\" size={16} />\n </StyledSidebarGroupButton>\n )}\n <StyledSidebarGroupContent id={groupContentId} $isOpen={isOpen}>\n {children.map((child: NavItemLink, index: number) => (\n <SidebarNavLink\n key={index}\n link={child}\n depth={depth + 1}\n pathname={pathname}\n onNavigate={onNavigate}\n />\n ))}\n </StyledSidebarGroupContent>\n </li>\n );\n}\n\nfunction SideBar({ result, pages = [] }: SideBarProps) {\n const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);\n const hasSectionBar = useContext(SectionBarContext);\n const pathname = usePathname();\n const t = useStrings();\n const sidebarId = useId();\n const navRef = useRef<HTMLElement>(null);\n const footerRef = useRef<HTMLDivElement>(null);\n\n useLockBodyScroll(isMobileMenuOpen);\n\n // Bring the current page's link into view within the sidebar's own scroll\n // area when it starts off-screen (deep pages, in-content links, search).\n // Scoped to the nav via scrollTo so the main document never jumps.\n useEffect(() => {\n const nav = navRef.current;\n if (!nav) return;\n const active = nav.querySelector<HTMLElement>('[aria-current=\"page\"]');\n if (!active) return;\n\n const navRect = nav.getBoundingClientRect();\n const activeRect = active.getBoundingClientRect();\n\n // The sidebar footer - theme toggle plus the language and version\n // switchers - is sticky over the bottom of the scroll area, so links\n // underneath it are covered rather than visible.\n // Clamp the visible bottom to the footer's top edge when it's pinned.\n const footerRect = footerRef.current?.getBoundingClientRect();\n const visibleBottom = footerRect\n ? Math.min(navRect.bottom, footerRect.top)\n : navRect.bottom;\n\n const isOutOfView =\n activeRect.top < navRect.top || activeRect.bottom > visibleBottom;\n if (!isOutOfView) return;\n\n // Center within the visible band (nav top .. footer top), not the full\n // nav height, so the link never settles behind the footer.\n const visibleHeight = visibleBottom - navRect.top;\n const target =\n nav.scrollTop +\n (activeRect.top - navRect.top) -\n (visibleHeight - active.clientHeight) / 2;\n\n // Animate the scroll, but honor users who opt out of motion.\n const prefersReducedMotion = window.matchMedia(\n \"(prefers-reduced-motion: reduce)\",\n ).matches;\n nav.scrollTo({\n top: Math.max(0, target),\n behavior: prefersReducedMotion ? \"auto\" : \"smooth\",\n });\n }, [pathname]);\n\n return (\n <DocsSidebar>\n <StyleMobileBar\n onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}\n $isActive={isMobileMenuOpen}\n aria-label={isMobileMenuOpen ? t.closeNavigation : t.openNavigation}\n aria-expanded={isMobileMenuOpen}\n aria-controls={sidebarId}\n >\n <StyledMobileBurger $isActive={isMobileMenuOpen} />\n </StyleMobileBar>\n\n <StyledSidebar\n id={sidebarId}\n ref={navRef}\n $isActive={isMobileMenuOpen}\n $hasSectionBar={hasSectionBar}\n >\n {result &&\n result.map((item: NavItem, index: number) => {\n return (\n <StyledSidebarList key={index}>\n <StyledSidebarListItem>\n <StyledStrong>\n {item.icon && <Icon name={item.icon} size={16} />}\n {item.label}\n </StyledStrong>{\" \"}\n </StyledSidebarListItem>\n <li>\n <Space $size={20} />\n </li>\n {item.links &&\n item.links.map((link: NavItemLink, indexChild: number) => (\n <SidebarNavLink\n key={indexChild}\n link={link}\n depth={0}\n pathname={pathname}\n onNavigate={() => setIsMobileMenuOpen(false)}\n />\n ))}\n <li aria-hidden=\"true\">\n <Space $size={20} />\n </li>\n </StyledSidebarList>\n );\n })}\n {/* One row of 30px controls. The focus-mode toggle is fixed over its\n left end, the switchers follow, and the theme toggle holds the\n right end of the rail. */}\n <StyledSidebarFooter ref={footerRef}>\n <VariantSwitchers pages={pages} />\n <StyledSidebarFooterToggle>\n <ThemeToggle $shortcut />\n </StyledSidebarFooterToggle>\n </StyledSidebarFooter>\n </StyledSidebar>\n\n {/* Outside StyledSidebar on purpose: focus mode slides that whole\n column away, and the toggle has to survive it. */}\n <FocusModeToggle />\n </DocsSidebar>\n );\n}\n\nexport { SideBar };\n";