doccupine 0.0.146 → 0.0.148
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.
- package/README.md +11 -2
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +41 -0
- package/dist/generator/mdx-reconciliation-coordinator.d.ts +83 -0
- package/dist/generator/mdx-reconciliation-coordinator.js +471 -0
- package/dist/generator/page-renderer.js +18 -13
- package/dist/generator/secure-source-fs.js +5 -4
- package/dist/generator/site-artifacts.js +2 -2
- package/dist/generator/watch-coordinator.js +3 -2
- package/dist/index.js +8 -2
- package/dist/lib/layout.js +18 -10
- package/dist/lib/openapi-rendering.d.ts +17 -0
- package/dist/lib/openapi-rendering.js +193 -0
- package/dist/lib/openapi.d.ts +1 -7
- package/dist/lib/openapi.js +2 -192
- package/dist/lib/structures.js +2 -0
- package/dist/lib/utils.d.ts +14 -0
- package/dist/lib/utils.js +30 -8
- package/dist/mdx-to-nextjs-generator.d.ts +2 -41
- package/dist/mdx-to-nextjs-generator.js +37 -469
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +226 -1457
- package/dist/templates/components/SearchDocs.d.ts +1 -1
- package/dist/templates/components/SearchDocs.js +20 -15
- package/dist/templates/components/SearchModalContent.d.ts +1 -1
- package/dist/templates/components/SearchModalContent.js +7 -1
- package/dist/templates/components/layout/ApiPlayground.d.ts +1 -1
- package/dist/templates/components/layout/ApiPlayground.js +14 -148
- package/dist/templates/components/layout/DocsComponents.d.ts +1 -1
- package/dist/templates/components/layout/DocsComponents.js +3 -3
- package/dist/templates/components/layout/DocsNavigation.d.ts +1 -1
- package/dist/templates/components/layout/DocsNavigation.js +2 -3
- package/dist/templates/components/layout/Footer.d.ts +1 -1
- package/dist/templates/components/layout/Footer.js +2 -4
- package/dist/templates/components/layout/Header.d.ts +1 -1
- package/dist/templates/components/layout/Header.js +3 -3
- package/dist/templates/components/layout/StaticLinks.d.ts +1 -1
- package/dist/templates/components/layout/StaticLinks.js +2 -3
- package/dist/templates/env.example.d.ts +1 -1
- package/dist/templates/env.example.js +8 -0
- package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/analytics.mdx.js +13 -0
- package/dist/templates/mdx/platform/fonts-settings.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/fonts-settings.mdx.js +16 -0
- package/dist/templates/mdx/platform/publishing.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/publishing.mdx.js +16 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/self-updating-docs.mdx.js +17 -5
- package/dist/templates/next.config.js +40 -0
- package/dist/templates/package.js +11 -10
- package/dist/templates/prettierignore.d.ts +1 -1
- package/dist/templates/prettierignore.js +11 -0
- package/dist/templates/utils/apiPlayground.d.ts +1 -0
- package/dist/templates/utils/apiPlayground.js +149 -0
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const searchDocsTemplate = "\"use client\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport dynamic from \"next/dynamic\";\nimport styled from \"styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { interactiveStyles } from \"@/components/layout/SharedStyled\";\nimport { ChatContext } from \"@/components/Chat\";\nimport type { PageItem, MergedResult } from \"@/components/SearchModalContent\";\n\nconst SearchModalContent = dynamic(\n () =>\n import(\"@/components/SearchModalContent\").then(\n (mod) => mod.SearchModalContent,\n ),\n { ssr: false },\n);\n\ninterface SectionItem {\n label: string;\n slug: string;\n}\n\n// Stable empty array so the derived contentResults keeps the same identity\n// across renders when there are no hits (memo deps stay stable).\nconst EMPTY_RESULTS: ContentHit[] = [];\n\ninterface ContentHit {\n slug: string;\n snippet: string;\n}\n\ninterface SearchContextValue {\n openSearch: () => void;\n}\n\nconst SearchContext = createContext<SearchContextValue>({\n openSearch: () => {},\n});\n\nconst StyledKbd = styled.kbd<{ theme: Theme }>`\n font-size: 11px;\n font-family: inherit;\n background: ${({ theme }) => theme.colors.grayLight};\n color: ${({ theme }) => theme.colors.grayDark};\n padding: 2px 6px;\n border-radius: 4px;\n margin-left: auto;\n font-weight: 600;\n display: none;\n\n ${mq(\"lg\")} {\n display: initial;\n }\n`;\n\nconst StyledSearchButton = styled.button<{ theme: Theme }>`\n ${interactiveStyles};\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n display: flex;\n align-items: center;\n gap: 6px;\n background: ${({ theme }) => theme.colors.light};\n color: ${({ theme }) => theme.colors.primary};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n padding: 7px 8px;\n font-family: inherit;\n cursor: pointer;\n\n ${mq(\"lg\")} {\n padding: 5px 8px;\n }\n\n & svg.lucide {\n color: inherit;\n }\n`;\n\nfunction SearchProvider({\n pages,\n sections,\n children,\n}: {\n pages: PageItem[];\n sections?: SectionItem[];\n children: React.ReactNode;\n}) {\n const [isVisible, setIsVisible] = useState(false);\n const [isClosing, setIsClosing] = useState(false);\n const [query, setQuery] = useState(\"\");\n const [activeIndex, setActiveIndex] = useState(0);\n const [returnFocusTo, setReturnFocusTo] = useState<HTMLElement | null>(null);\n // Latest completed content search, keyed by the query that produced it.\n // contentResults and isSearching are derived from it at render time, so\n // the debounced-search effect never sets state synchronously (which would\n // trigger cascading renders \u2014 react-hooks/set-state-in-effect).\n const [fetched, setFetched] = useState<{\n q: string;\n results: ContentHit[];\n } | null>(null);\n const resultsRef = useRef<HTMLUListElement>(null);\n const closingRef = useRef(false);\n const isVisibleRef = useRef(false);\n const searchOpenerRef = useRef<HTMLElement | null>(null);\n const restoreSearchFocusRef = useRef(true);\n const abortRef = useRef<AbortController | null>(null);\n const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);\n const router = useRouter();\n const { isChatActive, askAssistant, closeChat, registerSearchClose } =\n useContext(ChatContext);\n\n const sectionLabels = useMemo(() => {\n const map: Record<string, string> = {};\n sections?.forEach((s) => {\n map[s.slug] = s.label;\n });\n return map;\n }, [sections]);\n\n const openSearch = useCallback(() => {\n const previousOverlayOpener = closeChat(false);\n closingRef.current = false;\n restoreSearchFocusRef.current = true;\n const activeElement = document.activeElement;\n const opener =\n previousOverlayOpener?.isConnected === true\n ? previousOverlayOpener\n : activeElement instanceof HTMLElement &&\n activeElement !== document.body\n ? activeElement\n : null;\n searchOpenerRef.current = opener;\n setReturnFocusTo(opener);\n isVisibleRef.current = true;\n setIsClosing(false);\n setIsVisible(true);\n }, [closeChat]);\n\n const closeSearch = useCallback(() => {\n closingRef.current = true;\n setIsClosing(true);\n if (abortRef.current) abortRef.current.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n }, []);\n\n const shouldRestoreSearchFocus = useCallback(\n () => restoreSearchFocusRef.current,\n [],\n );\n\n const handleCloseAnimationEnd = useCallback(() => {\n if (!closingRef.current) return;\n closingRef.current = false;\n isVisibleRef.current = false;\n setIsVisible(false);\n setIsClosing(false);\n setQuery(\"\");\n setActiveIndex(0);\n setFetched(null);\n searchOpenerRef.current = null;\n setReturnFocusTo(null);\n }, []);\n\n const closeSearchImmediately = useCallback((restoreFocus = true) => {\n if (!isVisibleRef.current) return null;\n restoreSearchFocusRef.current = restoreFocus;\n const opener = searchOpenerRef.current;\n searchOpenerRef.current = null;\n setReturnFocusTo(null);\n closingRef.current = false;\n isVisibleRef.current = false;\n if (abortRef.current) abortRef.current.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n const activeElement = document.activeElement;\n if (\n activeElement instanceof HTMLElement &&\n activeElement.closest(\"[data-search-dialog]\")\n ) {\n activeElement.blur();\n }\n setIsVisible(false);\n setIsClosing(false);\n setQuery(\"\");\n setActiveIndex(0);\n setFetched(null);\n return opener;\n }, []);\n\n useEffect(\n () => registerSearchClose(closeSearchImmediately),\n [closeSearchImmediately, registerSearchClose],\n );\n\n const trimmedQuery = query.trim();\n const contentResults =\n trimmedQuery.length >= 2 && fetched?.q === trimmedQuery\n ? fetched.results\n : EMPTY_RESULTS;\n const isSearching = trimmedQuery.length >= 2 && fetched?.q !== trimmedQuery;\n\n // Instant title/description filtering\n const titleFiltered = useMemo(() => {\n if (!query.trim()) return pages;\n const q = query.toLowerCase();\n return pages.filter(\n (p) =>\n p.title.toLowerCase().includes(q) ||\n p.description?.toLowerCase().includes(q),\n );\n }, [pages, query]);\n\n // Merge title matches with content matches\n const merged = useMemo<MergedResult[]>(() => {\n if (!query.trim()) {\n return pages.map((p) => ({ page: p }));\n }\n\n const titleMatchSlugs = new Set(titleFiltered.map((p) => p.slug));\n const titleMatches: MergedResult[] = titleFiltered.map((p) => {\n const hit = contentResults.find((cr) => cr.slug === p.slug);\n return { page: p, snippet: hit?.snippet };\n });\n\n const pageMap = new Map(pages.map((p) => [p.slug, p]));\n const contentOnly: MergedResult[] = [];\n for (const cr of contentResults) {\n if (!titleMatchSlugs.has(cr.slug)) {\n const page = pageMap.get(cr.slug);\n if (page) {\n contentOnly.push({ page, snippet: cr.snippet });\n }\n }\n }\n\n return [...titleMatches, ...contentOnly];\n }, [pages, query, titleFiltered, contentResults]);\n\n // Debounced content search. State updates happen only inside the timeout's\n // async callback; short queries need no reset because the derived values\n // above ignore results whose query no longer matches.\n useEffect(() => {\n if (debounceRef.current) clearTimeout(debounceRef.current);\n if (abortRef.current) abortRef.current.abort();\n\n const q = query.trim();\n if (q.length < 2) return;\n\n debounceRef.current = setTimeout(async () => {\n const controller = new AbortController();\n abortRef.current = controller;\n try {\n const res = await fetch(\n `/api/search?q=${encodeURIComponent(q)}&limit=15`,\n { signal: controller.signal },\n );\n if (!res.ok) throw new Error(\"Search failed\");\n const data = await res.json();\n setFetched({ q, results: data.results ?? [] });\n } catch (err: unknown) {\n if (err instanceof DOMException && err.name === \"AbortError\") return;\n setFetched({ q, results: [] });\n }\n }, 300);\n\n return () => {\n if (debounceRef.current) clearTimeout(debounceRef.current);\n };\n }, [query]);\n\n const navigate = useCallback(\n (\n slug: string,\n modifiers?: { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean },\n ) => {\n const url = `/${slug}`;\n\n // Shift+Enter / Shift+Click: open in a separate browser window. Window\n // features (dimensions) are what make the browser spawn a window instead\n // of a tab; noopener/noreferrer keep the new window from reaching back\n // into this one via window.opener.\n if (modifiers?.shiftKey) {\n const width = Math.min(1024, window.screen.availWidth);\n const height = Math.min(800, window.screen.availHeight);\n const left = Math.round((window.screen.availWidth - width) / 2);\n const top = Math.round((window.screen.availHeight - height) / 2);\n window.open(\n url,\n \"_blank\",\n `popup=yes,noopener,noreferrer,width=${width},height=${height},left=${left},top=${top}`,\n );\n return;\n }\n\n // Cmd+Enter / Ctrl+Enter / Cmd+Click: open in a new background tab. With\n // no dimension features the browser keeps this as a tab.\n if (modifiers?.metaKey || modifiers?.ctrlKey) {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n return;\n }\n\n // Plain Enter / Click: navigate in place within the app.\n closeSearch();\n router.push(url);\n },\n [closeSearch, router],\n );\n\n // Hand the current query to the AI assistant, then dismiss the search modal.\n // `askAssistant` opens the chat and either submits the question or (if a\n // response is already streaming) pre-fills it, ready to send.\n const askAssistantWithQuery = useCallback(() => {\n const q = query.trim();\n if (!q) return;\n const opener = closeSearchImmediately(false);\n askAssistant(q, opener);\n }, [query, askAssistant, closeSearchImmediately]);\n\n // Global Cmd+K / Ctrl+K listener\n useEffect(() => {\n function handleKeyDown(e: KeyboardEvent) {\n if ((e.metaKey || e.ctrlKey) && e.key === \"k\") {\n e.preventDefault();\n if (isVisibleRef.current) {\n closeSearch();\n } else {\n openSearch();\n }\n }\n }\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => document.removeEventListener(\"keydown\", handleKeyDown);\n }, [closeSearch, openSearch]);\n\n // Active-row scrolling now lives in SearchModalContent's layout effect,\n // alongside the highlight measurement, so highlight + scroll update together\n // before paint (no flicker) and stay in sync on query changes.\n\n function handleKeyDown(e: React.KeyboardEvent) {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n setActiveIndex((i) => (i < merged.length - 1 ? i + 1 : 0));\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n setActiveIndex((i) => (i > 0 ? i - 1 : merged.length - 1));\n } else if (e.key === \"Enter\") {\n e.preventDefault();\n // Option/Alt+Enter is reserved for handing the query to the AI assistant.\n if (e.altKey) {\n if (isChatActive) askAssistantWithQuery();\n return;\n }\n if (merged[activeIndex]) {\n navigate(merged[activeIndex].page.slug, e);\n }\n } else if (e.key === \"Escape\") {\n closeSearch();\n }\n }\n\n return (\n <SearchContext.Provider value={{ openSearch }}>\n {children}\n {isVisible && (\n <SearchModalContent\n isClosing={isClosing}\n closeSearch={closeSearch}\n onCloseAnimationEnd={handleCloseAnimationEnd}\n query={query}\n setQuery={setQuery}\n activeIndex={activeIndex}\n setActiveIndex={setActiveIndex}\n resultsRef={resultsRef}\n onKeyDown={handleKeyDown}\n merged={merged}\n sectionLabels={sectionLabels}\n isSearching={isSearching}\n navigate={navigate}\n canAskAssistant={isChatActive}\n onAskAssistant={askAssistantWithQuery}\n shouldRestoreFocus={shouldRestoreSearchFocus}\n returnFocusTo={returnFocusTo}\n />\n )}\n </SearchContext.Provider>\n );\n}\n\nexport {\n SearchProvider,\n SearchContext,\n StyledKbd as SearchKbd,\n StyledSearchButton,\n};\n";
|
|
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 4px 0 8px;\n font-family: inherit;\n cursor: pointer;\n\n & svg.lucide {\n color: inherit;\n min-width: 14px;\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";
|
|
@@ -11,6 +11,7 @@ import React, {
|
|
|
11
11
|
import { useRouter } from "next/navigation";
|
|
12
12
|
import dynamic from "next/dynamic";
|
|
13
13
|
import styled from "styled-components";
|
|
14
|
+
import { useChat } from "cherry-styled-components";
|
|
14
15
|
import { mq, Theme } from "@/app/theme";
|
|
15
16
|
import { interactiveStyles } from "@/components/layout/SharedStyled";
|
|
16
17
|
import { ChatContext } from "@/components/Chat";
|
|
@@ -68,19 +69,21 @@ const StyledSearchButton = styled.button<{ theme: Theme }>\`
|
|
|
68
69
|
display: flex;
|
|
69
70
|
align-items: center;
|
|
70
71
|
gap: 6px;
|
|
72
|
+
/* Pinned to the 30px compact header-control tier, matching Cherry's
|
|
73
|
+
ChatLauncher, so the height cannot drift with platform font metrics
|
|
74
|
+
and the header controls always align exactly. */
|
|
75
|
+
box-sizing: border-box;
|
|
76
|
+
height: 30px;
|
|
71
77
|
background: \${({ theme }) => theme.colors.light};
|
|
72
78
|
color: \${({ theme }) => theme.colors.primary};
|
|
73
79
|
border-radius: \${({ theme }) => theme.spacing.radius.xs};
|
|
74
|
-
padding:
|
|
80
|
+
padding: 0 4px 0 8px;
|
|
75
81
|
font-family: inherit;
|
|
76
82
|
cursor: pointer;
|
|
77
83
|
|
|
78
|
-
\${mq("lg")} {
|
|
79
|
-
padding: 5px 8px;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
84
|
& svg.lucide {
|
|
83
85
|
color: inherit;
|
|
86
|
+
min-width: 14px;
|
|
84
87
|
}
|
|
85
88
|
\`;
|
|
86
89
|
|
|
@@ -114,8 +117,8 @@ function SearchProvider({
|
|
|
114
117
|
const abortRef = useRef<AbortController | null>(null);
|
|
115
118
|
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);
|
|
116
119
|
const router = useRouter();
|
|
117
|
-
const { isChatActive
|
|
118
|
-
|
|
120
|
+
const { isChatActive } = useContext(ChatContext);
|
|
121
|
+
const { ask, close: closeChat, isOpen: isChatOpen } = useChat();
|
|
119
122
|
|
|
120
123
|
const sectionLabels = useMemo(() => {
|
|
121
124
|
const map: Record<string, string> = {};
|
|
@@ -194,10 +197,12 @@ function SearchProvider({
|
|
|
194
197
|
return opener;
|
|
195
198
|
}, []);
|
|
196
199
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
)
|
|
200
|
+
// Only one overlay at a time: the chat panel opening (launcher, Cmd+I, or
|
|
201
|
+
// \`ask\`) dismisses the search modal without restoring focus, since focus
|
|
202
|
+
// has already moved into the chat composer.
|
|
203
|
+
useEffect(() => {
|
|
204
|
+
if (isChatOpen) closeSearchImmediately(false);
|
|
205
|
+
}, [isChatOpen, closeSearchImmediately]);
|
|
201
206
|
|
|
202
207
|
const trimmedQuery = query.trim();
|
|
203
208
|
const contentResults =
|
|
@@ -314,14 +319,14 @@ function SearchProvider({
|
|
|
314
319
|
);
|
|
315
320
|
|
|
316
321
|
// Hand the current query to the AI assistant, then dismiss the search modal.
|
|
317
|
-
// \`
|
|
318
|
-
//
|
|
322
|
+
// \`ask\` opens the chat and either submits the question or (if a response is
|
|
323
|
+
// already streaming) pre-fills it, ready to send.
|
|
319
324
|
const askAssistantWithQuery = useCallback(() => {
|
|
320
325
|
const q = query.trim();
|
|
321
326
|
if (!q) return;
|
|
322
327
|
const opener = closeSearchImmediately(false);
|
|
323
|
-
|
|
324
|
-
}, [query,
|
|
328
|
+
ask(q, opener);
|
|
329
|
+
}, [query, ask, closeSearchImmediately]);
|
|
325
330
|
|
|
326
331
|
// Global Cmd+K / Ctrl+K listener
|
|
327
332
|
useEffect(() => {
|
|
@@ -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 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\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, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\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>⌥</StyledAskKbd>\n <StyledAskKbd>\n <StyledReturnGlyph>↵</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 {\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, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\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>⌥</StyledAskKbd>\n <StyledAskKbd>\n <StyledReturnGlyph>↵</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";
|
|
@@ -158,7 +158,7 @@ const StyledAskAssistant = styled.button<{ theme: Theme }>\`
|
|
|
158
158
|
background: \${({ theme }) => theme.colors.light};
|
|
159
159
|
color: \${({ theme }) => theme.colors.grayDark};
|
|
160
160
|
border-radius: \${({ theme }) => theme.spacing.radius.xs};
|
|
161
|
-
padding: 5px 8px;
|
|
161
|
+
padding: 5px 4px 5px 8px;
|
|
162
162
|
font-family: inherit;
|
|
163
163
|
font-size: \${({ theme }) => theme.fontSizes.small.lg};
|
|
164
164
|
font-weight: 500;
|
|
@@ -173,6 +173,12 @@ const StyledAskAssistant = styled.button<{ theme: Theme }>\`
|
|
|
173
173
|
&:hover {
|
|
174
174
|
border-color: \${({ theme }) => theme.colors.grayLight};
|
|
175
175
|
}
|
|
176
|
+
|
|
177
|
+
&:focus,
|
|
178
|
+
&:active {
|
|
179
|
+
outline: none;
|
|
180
|
+
box-shadow: 0 0 0 0 \${({ theme }) => theme.colors.primaryLight};
|
|
181
|
+
}
|
|
176
182
|
}
|
|
177
183
|
|
|
178
184
|
\${mq("lg")} {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const apiPlaygroundTemplate = "\"use client\";\nimport React, { useCallback, useMemo, useRef, useState } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport {\n styledSmall,\n interactiveStyles,\n Input,\n Textarea,\n Modal,\n} from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { Code, CodeTabs } from \"@/components/layout/Code\";\nimport { Icon } from \"@/components/layout/Icon\";\nimport { Accordion } from \"@/components/layout/Accordion\";\nimport { Badge, httpMethodBadgeColor } from \"@/components/layout/Badge\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { CopyButton } from \"@/components/layout/CopyButton\";\nimport { Spinner } from \"@/components/Spinner\";\nimport { matchAllowlist, matchAllowlistIn } from \"@/utils/playgroundAllowlist\";\nimport type { AllowlistEntry } from \"@/utils/playgroundAllowlist\";\nimport { buildSnippets } from \"@/utils/apiSnippets\";\nimport type { SnippetLanguage } from \"@/utils/apiSnippets\";\nimport type {\n OperationDescriptor,\n ParameterDescriptor,\n ServerDescriptor,\n} from \"@/types/openapi\";\n\ninterface PlaygroundResponse {\n status: number;\n statusText: string;\n headers: Record<string, string>;\n contentType: string | null;\n bodyEncoding: \"utf8\" | \"base64\";\n body: string;\n truncated: boolean;\n byteLength: number;\n durationMs: number;\n}\n\ninterface BuiltRequest {\n url: string;\n headers: Record<string, string>;\n body: string | null;\n secretHeaderNames: string[];\n}\n\nexport interface ApiPlaygroundProps {\n operation: OperationDescriptor;\n defaultMode?: \"proxy\" | \"direct\";\n allowDirect?: boolean;\n // Extra client-side allowlist entries. The server proxy always enforces the\n // build-time allowlist regardless; this only relaxes the client pre-flight\n // (used by the docs demo to run in direct mode without a configured spec).\n allowlist?: AllowlistEntry[];\n snippetLanguages?: SnippetLanguage[];\n}\n\nfunction schemaTypeLabel(schema: unknown): string {\n if (schema && typeof schema === \"object\") {\n const record = schema as { type?: unknown; format?: unknown };\n if (typeof record.type === \"string\") {\n return typeof record.format === \"string\"\n ? record.type + \" (\" + record.format + \")\"\n : record.type;\n }\n }\n return \"string\";\n}\n\nfunction serverBase(server: ServerDescriptor | undefined): string {\n if (!server) return \"\";\n let url = server.url;\n const variables = server.variables;\n if (variables) {\n for (const key of Object.keys(variables)) {\n url = url.split(\"{\" + key + \"}\").join(variables[key].default);\n }\n }\n while (url.endsWith(\"/\")) url = url.slice(0, -1);\n return url;\n}\n\nfunction applyPathParams(\n template: string,\n values: Record<string, string>,\n): string {\n let result = template;\n for (const key of Object.keys(values)) {\n result = result\n .split(\"{\" + key + \"}\")\n .join(encodeURIComponent(values[key]));\n }\n return result;\n}\n\nfunction firstJsonExample(op: OperationDescriptor): {\n contentType: string;\n text: string;\n} | null {\n if (!op.requestBody || op.requestBody.content.length === 0) return null;\n const media =\n op.requestBody.content.find((m) => m.contentType.includes(\"json\")) ??\n op.requestBody.content[0];\n let text = \"\";\n if (media.example !== undefined) {\n try {\n text = JSON.stringify(media.example, null, 2);\n } catch {\n text = \"\";\n }\n }\n return { contentType: media.contentType, text };\n}\n\nfunction classifyResponse(\n contentType: string | null,\n): \"image\" | \"video\" | \"audio\" | \"text\" | \"binary\" {\n if (!contentType) return \"text\";\n const t = contentType.toLowerCase();\n if (t.startsWith(\"image/\") && !t.includes(\"svg\")) return \"image\";\n if (t.startsWith(\"video/\")) return \"video\";\n if (t.startsWith(\"audio/\")) return \"audio\";\n if (\n t.includes(\"json\") ||\n t.startsWith(\"text/\") ||\n t.includes(\"xml\") ||\n t.includes(\"svg\") ||\n t.includes(\"html\") ||\n t.includes(\"javascript\") ||\n t.includes(\"csv\")\n ) {\n return \"text\";\n }\n return \"binary\";\n}\n\nfunction codeLanguage(contentType: string | null): string {\n if (!contentType) return \"text\";\n const t = contentType.toLowerCase();\n if (t.includes(\"json\")) return \"json\";\n if (t.includes(\"html\")) return \"html\";\n if (t.includes(\"xml\") || t.includes(\"svg\")) return \"xml\";\n if (t.includes(\"javascript\")) return \"javascript\";\n return \"text\";\n}\n\nfunction prettyBody(contentType: string | null, body: string): string {\n if (contentType && contentType.toLowerCase().includes(\"json\")) {\n try {\n return JSON.stringify(JSON.parse(body), null, 2);\n } catch {\n return body;\n }\n }\n return body;\n}\n\nfunction bufferToBase64(buffer: ArrayBuffer): string {\n let binary = \"\";\n const bytes = new Uint8Array(buffer);\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk));\n }\n return btoa(binary);\n}\n\nfunction renderPath(path: string): React.ReactNode {\n return path\n .split(/(\\{[^}]+\\})/g)\n .map((part, index) =>\n part.startsWith(\"{\") ? (\n <PathParam key={index}>{part}</PathParam>\n ) : (\n <span key={index}>{part}</span>\n ),\n );\n}\n\nconst LOCATIONS: ParameterDescriptor[\"in\"][] = [\n \"path\",\n \"query\",\n \"header\",\n \"cookie\",\n];\n\nconst LOCATION_TITLES: Record<string, string> = {\n path: \"Path\",\n query: \"Query\",\n header: \"Headers\",\n cookie: \"Cookies\",\n};\n\n/* ---------- compact bar ---------- */\n\nconst CompactBar = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n margin: 0;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\n// The method chip is Badge's mono+solid variation; only bar-layout metrics\n// are adjusted here.\nconst MethodBadge = styled(Badge)`\n flex-shrink: 0;\n padding: 0 4px;\n border: none;\n`;\n\nconst PathText = styled.span`\n flex: 1;\n min-width: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n overflow-x: auto;\n white-space: nowrap;\n &::-webkit-scrollbar {\n display: none;\n }\n`;\n\nconst PathParam = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n overflow-wrap: anywhere;\n`;\n\nconst AccentButton = styled.button<{ theme: Theme }>`\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.text};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n background: ${({ theme }: { theme: Theme }) => theme.colors.primary};\n border: none;\n padding: 8px 14px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n & svg {\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n stroke: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n }\n\n &:hover {\n background: ${({ theme }: { theme: Theme }) => theme.colors.primaryDark};\n }\n &:disabled {\n opacity: 0.6;\n cursor: default;\n }\n`;\n\n/* ---------- modal ---------- */\n\nconst DialogHeader = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n flex-wrap: wrap;\n margin: 5px 0 0 0;\n`;\n\nconst PathBar = styled.div`\n flex: 1;\n min-width: 200px;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\nconst DialogBody = styled.div`\n display: grid;\n grid-template-columns: 1fr;\n gap: 20px;\n padding: 0;\n margin: 20px 0 0 0;\n\n ${mq(\"lg\")} {\n grid-template-columns: 1fr 1fr;\n }\n`;\n\nconst Column = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n min-width: 0;\n`;\n\nconst Description = styled.p`\n margin: 0;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n`;\n\nconst Toolbar = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n`;\n\nconst Toggle = styled.button<{ theme: Theme; $active?: boolean }>`\n position: relative;\n cursor: pointer;\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1;\n color: ${({ theme }) => theme.colors.accent};\n display: flex;\n gap: 6px;\n transition: all 0.3s ease;\n font-weight: 600;\n white-space: nowrap;\n min-width: fit-content;\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 10%, transparent)`};\n padding: 6px 8px;\n border: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n ${({ $active, theme }) =>\n $active &&\n css`\n background: ${theme.colors.primary};\n color: ${theme.colors.surface};\n `}\n`;\n\n/* ---------- collapsible card ---------- */\n\nconst Card = styled.div`\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n overflow: hidden;\n`;\n\nconst CardHead = styled.button`\n cursor: pointer;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 12px 20px;\n border: none;\n background: transparent;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst Inline = styled.span`\n display: inline-flex;\n align-items: center;\n gap: 8px;\n`;\n\nconst CardBody = styled.div`\n padding: 0 20px 20px;\n display: flex;\n flex-direction: column;\n gap: 16px;\n`;\n\n/* ---------- fields ---------- */\n\n// Wraps an accordion section's content and insets it, so full-width inputs'\n// focus rings (a 4px box-shadow) are not clipped by the accordion's own\n// overflow. Keeps the accordion component untouched.\nconst SectionInner = styled.div`\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 4px;\n`;\n\nconst Field = styled.div`\n display: flex;\n flex-direction: column;\n gap: 6px;\n`;\n\nconst FieldHead = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst FieldName = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n`;\n\nconst TypeChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.gray} 15%, transparent)`};\n padding: 0 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nconst RequiredChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.error};\n`;\n\nconst FieldDesc = styled.p`\n margin: 0;\n width: 100%;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n/* ---------- response ---------- */\n\nconst StatusPill = styled.span<{ theme: Theme; $ok: boolean }>`\n font-family: ${({ theme }) => theme.fonts.mono};\n font-weight: 700;\n color: ${({ theme }) => theme.colors.surface};\n background: ${({ theme, $ok }) =>\n $ok ? theme.colors.success : theme.colors.error};\n padding: 0 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n`;\n\nconst Meta = styled.span`\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\nconst Placeholder = styled.div`\n border: dashed 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n padding: 24px;\n min-height: 120px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n text-align: center;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n// Holds the response (or empty placeholder) and lets the loading spinner sit on\n// top of it, so a re-send keeps the previous content in place instead of\n// collapsing and jumping the layout.\nconst ResponseArea = styled.div`\n position: relative;\n`;\n\nconst LoadingOverlay = styled.div`\n position: absolute;\n inset: 0;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.light} 60%, transparent)`};\n backdrop-filter: blur(1px);\n`;\n\nconst ResponseMedia = styled.img`\n max-width: 100%;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nexport function ApiPlayground({\n operation,\n defaultMode = \"proxy\",\n allowDirect = true,\n allowlist,\n snippetLanguages = [\"curl\", \"javascript\", \"python\"],\n}: ApiPlaygroundProps) {\n const [open, setOpen] = useState(false);\n const [paramValues, setParamValues] = useState<Record<string, string>>({});\n const [authValues, setAuthValues] = useState<Record<string, string>>({});\n const initialBody = useMemo(() => firstJsonExample(operation), [operation]);\n const [bodyText, setBodyText] = useState(initialBody?.text ?? \"\");\n const [mode, setMode] = useState<\"proxy\" | \"direct\">(defaultMode);\n const [showSecrets, setShowSecrets] = useState(false);\n const [loading, setLoading] = useState(false);\n const [response, setResponse] = useState<PlaygroundResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [corsRetry, setCorsRetry] = useState(false);\n const abortRef = useRef<AbortController | null>(null);\n\n const paramKey = (p: ParameterDescriptor) => p.in + \":\" + p.name;\n\n const isAllowed = useCallback(\n (url: string) =>\n Boolean(\n matchAllowlist(url) ??\n (allowlist ? matchAllowlistIn(allowlist, url) : null),\n ),\n [allowlist],\n );\n\n const buildRequest = useCallback((): BuiltRequest => {\n const base = serverBase(operation.servers[0]);\n const pathValues: Record<string, string> = {};\n const queryParts: string[] = [];\n const headers: Record<string, string> = {};\n const secretHeaderNames: string[] = [];\n let cookie = \"\";\n\n for (const param of operation.parameters) {\n const value = paramValues[paramKey(param)];\n if (value === undefined || value === \"\") continue;\n if (param.in === \"path\") pathValues[param.name] = value;\n else if (param.in === \"query\")\n queryParts.push(\n encodeURIComponent(param.name) + \"=\" + encodeURIComponent(value),\n );\n else if (param.in === \"header\") headers[param.name] = value;\n else if (param.in === \"cookie\")\n cookie += (cookie ? \"; \" : \"\") + param.name + \"=\" + value;\n }\n\n for (const requirement of operation.security) {\n const scheme = requirement.scheme;\n if (!scheme) continue;\n if (scheme.type === \"apiKey\" && scheme.name) {\n const value = authValues[requirement.schemeName];\n if (!value) continue;\n if (scheme.in === \"header\") {\n headers[scheme.name] = value;\n secretHeaderNames.push(scheme.name);\n } else if (scheme.in === \"query\") {\n queryParts.push(\n encodeURIComponent(scheme.name) + \"=\" + encodeURIComponent(value),\n );\n } else if (scheme.in === \"cookie\") {\n cookie += (cookie ? \"; \" : \"\") + scheme.name + \"=\" + value;\n }\n } else if (scheme.type === \"http\" && scheme.scheme === \"basic\") {\n const user = authValues[requirement.schemeName + \":user\"] ?? \"\";\n const pass = authValues[requirement.schemeName + \":pass\"] ?? \"\";\n if (user || pass) {\n headers[\"Authorization\"] = \"Basic \" + btoa(user + \":\" + pass);\n secretHeaderNames.push(\"Authorization\");\n }\n } else {\n const token = authValues[requirement.schemeName];\n if (token) {\n headers[\"Authorization\"] = \"Bearer \" + token;\n secretHeaderNames.push(\"Authorization\");\n }\n }\n }\n\n if (cookie) headers[\"Cookie\"] = cookie;\n\n const hasBody =\n operation.requestBody !== undefined &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" &&\n bodyText.trim() !== \"\";\n if (hasBody && !headers[\"Content-Type\"] && initialBody) {\n headers[\"Content-Type\"] = initialBody.contentType;\n }\n\n const query = queryParts.join(\"&\");\n const url =\n base +\n applyPathParams(operation.path, pathValues) +\n (query ? \"?\" + query : \"\");\n\n return { url, headers, body: hasBody ? bodyText : null, secretHeaderNames };\n }, [operation, paramValues, authValues, bodyText, initialBody]);\n\n const snippets = useMemo(() => {\n const built = buildRequest();\n const headers: Record<string, string> = { ...built.headers };\n if (!showSecrets) {\n for (const name of built.secretHeaderNames) {\n headers[name] = \"<YOUR_CREDENTIALS>\";\n }\n }\n return buildSnippets(\n {\n method: operation.method.toUpperCase(),\n url: built.url || operation.path,\n headers,\n body: built.body,\n },\n snippetLanguages,\n );\n }, [buildRequest, showSecrets, operation, snippetLanguages]);\n\n const sendProxy = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const res = await fetch(\"/api/playground\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n signal,\n body: JSON.stringify({\n targetUrl: built.url,\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n bodyEncoding: \"utf8\",\n }),\n });\n const data = await res.json();\n if (!res.ok) {\n throw new Error(\n typeof data?.error === \"string\" ? data.error : \"Request failed\",\n );\n }\n return data as PlaygroundResponse;\n },\n [operation],\n );\n\n const sendDirect = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const start = Date.now();\n const res = await fetch(built.url, {\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n signal,\n });\n const buffer = await res.arrayBuffer();\n const contentType = res.headers.get(\"content-type\");\n const isText = classifyResponse(contentType) === \"text\";\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return {\n status: res.status,\n statusText: res.statusText,\n headers,\n contentType,\n bodyEncoding: isText ? \"utf8\" : \"base64\",\n body: isText\n ? new TextDecoder().decode(buffer)\n : bufferToBase64(buffer),\n truncated: false,\n byteLength: buffer.byteLength,\n durationMs: Date.now() - start,\n };\n },\n [operation],\n );\n\n const send = useCallback(async () => {\n setError(null);\n setCorsRetry(false);\n // Keep any previous response on screen; the loading overlay covers it so\n // the layout does not collapse and jump while the new request is in flight.\n\n const built = buildRequest();\n if (!built.url) {\n setError(\"No server URL is configured for this endpoint.\");\n return;\n }\n if (!isAllowed(built.url)) {\n setError(\"This endpoint's server is not in the allowed list.\");\n return;\n }\n if (\n mode === \"direct\" &&\n typeof window !== \"undefined\" &&\n window.location.protocol === \"https:\" &&\n built.url.startsWith(\"http:\")\n ) {\n setError(\n \"Browsers block HTTP requests from an HTTPS page. Use proxy mode.\",\n );\n return;\n }\n\n const controller = new AbortController();\n abortRef.current = controller;\n setLoading(true);\n try {\n const result =\n mode === \"direct\"\n ? await sendDirect(built, controller.signal)\n : await sendProxy(built, controller.signal);\n setResponse(result);\n } catch (err) {\n if (controller.signal.aborted) return;\n if (mode === \"direct\" && err instanceof TypeError) {\n setCorsRetry(true);\n setError(\n \"The browser blocked this cross-origin request (CORS). Run it server-side instead.\",\n );\n } else {\n setError(err instanceof Error ? err.message : \"Request failed\");\n }\n } finally {\n setLoading(false);\n abortRef.current = null;\n }\n }, [buildRequest, isAllowed, mode, sendDirect, sendProxy]);\n\n const retryViaProxy = useCallback(() => {\n setMode(\"proxy\");\n setCorsRetry(false);\n void send();\n }, [send]);\n\n const groupedParams = LOCATIONS.map((location) => ({\n location,\n params: operation.parameters.filter((p) => p.in === location),\n })).filter((group) => group.params.length > 0);\n // Only the first visible section starts expanded.\n const hasAuth = operation.security.length > 0;\n\n const responseKind = response ? classifyResponse(response.contentType) : null;\n const mediaSrc =\n response && responseKind && responseKind !== \"text\"\n ? \"data:\" +\n (response.contentType ?? \"application/octet-stream\") +\n \";base64,\" +\n response.body\n : \"\";\n\n const renderParamField = (param: ParameterDescriptor) => (\n <Field key={param.anchorId}>\n <FieldHead>\n <FieldName>{param.name}</FieldName>\n <TypeChip>{schemaTypeLabel(param.schema)}</TypeChip>\n {param.required ? <RequiredChip>required</RequiredChip> : null}\n </FieldHead>\n {param.description ? <FieldDesc>{param.description}</FieldDesc> : null}\n <Input\n $fullWidth\n type=\"text\"\n aria-label={param.name}\n placeholder={\n param.example !== undefined\n ? String(param.example)\n : \"enter \" + param.name\n }\n value={paramValues[paramKey(param)] ?? \"\"}\n onChange={(e) =>\n setParamValues((prev) => ({\n ...prev,\n [paramKey(param)]: e.target.value,\n }))\n }\n />\n </Field>\n );\n\n return (\n <>\n <CompactBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <CopyButton\n text={operation.method.toUpperCase() + \" \" + operation.path}\n label=\"Copy endpoint\"\n size={16}\n />\n <AccentButton type=\"button\" onClick={() => setOpen(true)}>\n Try it\n <Icon name=\"play\" size={14} />\n </AccentButton>\n </CompactBar>\n\n <Modal\n $isOpen={open}\n $onClose={() => setOpen(false)}\n $width={1120}\n $title={\n operation.summary ??\n operation.method.toUpperCase() + \" \" + operation.path\n }\n >\n <DialogHeader>\n <PathBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <AccentButton\n type=\"button\"\n onClick={() => void send()}\n disabled={loading}\n >\n Send\n {loading ? <Spinner size={14} /> : <Icon name=\"play\" size={14} />}\n </AccentButton>\n </PathBar>\n </DialogHeader>\n\n <DialogBody>\n <Column>\n {operation.description || operation.summary ? (\n <Description>\n {operation.description ?? operation.summary}\n </Description>\n ) : null}\n\n <Toolbar>\n {operation.servers.length > 0 ? (\n <Meta>{serverBase(operation.servers[0])}</Meta>\n ) : null}\n {allowDirect ? (\n <>\n <Toggle\n type=\"button\"\n $active={mode === \"proxy\"}\n onClick={() => setMode(\"proxy\")}\n >\n Proxy\n </Toggle>\n <Toggle\n type=\"button\"\n $active={mode === \"direct\"}\n onClick={() => setMode(\"direct\")}\n >\n Direct\n </Toggle>\n </>\n ) : null}\n <Toggle\n type=\"button\"\n $active={showSecrets}\n onClick={() => setShowSecrets((v) => !v)}\n >\n {showSecrets ? \"Hide secrets\" : \"Show secrets\"}\n </Toggle>\n </Toolbar>\n\n {operation.security.length > 0 ? (\n <Accordion title=\"Authorization\" defaultOpen>\n <SectionInner>\n {operation.security.map((requirement) => {\n const scheme = requirement.scheme;\n if (\n scheme &&\n scheme.type === \"http\" &&\n scheme.scheme === \"basic\"\n ) {\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>basic</TypeChip>\n </FieldHead>\n <Input\n $fullWidth\n type=\"text\"\n aria-label={requirement.schemeName + \" username\"}\n placeholder=\"username\"\n value={\n authValues[requirement.schemeName + \":user\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":user\"]:\n e.target.value,\n }))\n }\n />\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName + \" password\"}\n placeholder=\"password\"\n value={\n authValues[requirement.schemeName + \":pass\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":pass\"]:\n e.target.value,\n }))\n }\n />\n </Field>\n );\n }\n const chip =\n scheme?.type === \"apiKey\"\n ? \"apiKey\"\n : scheme?.scheme === \"bearer\"\n ? \"bearer\"\n : (scheme?.type ?? \"token\");\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>{chip}</TypeChip>\n <RequiredChip>required</RequiredChip>\n </FieldHead>\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName}\n placeholder={\n chip === \"bearer\"\n ? \"enter bearer token\"\n : \"enter value\"\n }\n value={authValues[requirement.schemeName] ?? \"\"}\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName]: e.target.value,\n }))\n }\n />\n </Field>\n );\n })}\n </SectionInner>\n </Accordion>\n ) : null}\n\n {groupedParams.map((group, index) => (\n <Accordion\n key={group.location}\n title={LOCATION_TITLES[group.location]}\n defaultOpen={!hasAuth && index === 0}\n >\n <SectionInner>\n {group.params.map(renderParamField)}\n </SectionInner>\n </Accordion>\n ))}\n\n {operation.requestBody &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" ? (\n <Accordion\n title=\"Body\"\n defaultOpen={!hasAuth && groupedParams.length === 0}\n >\n <SectionInner>\n <Textarea\n $fullWidth\n rows={8}\n aria-label=\"Request body\"\n spellCheck={false}\n value={bodyText}\n onChange={(e) => setBodyText(e.target.value)}\n />\n </SectionInner>\n </Accordion>\n ) : null}\n\n {error ? (\n <Field>\n <Callout type=\"danger\">\n <p>{error}</p>\n </Callout>\n {corsRetry ? (\n <Toggle type=\"button\" onClick={retryViaProxy}>\n Retry via proxy\n </Toggle>\n ) : null}\n </Field>\n ) : null}\n </Column>\n\n <Column>\n <ResponseArea>\n {response ? (\n <Card>\n <CardHead as=\"div\">\n <Inline>\n <StatusPill\n $ok={response.status >= 200 && response.status < 400}\n >\n {response.status} {response.statusText}\n </StatusPill>\n <Meta>{response.durationMs}ms</Meta>\n <Meta>{response.byteLength} bytes</Meta>\n {response.truncated ? <Meta>(truncated)</Meta> : null}\n </Inline>\n </CardHead>\n <CardBody>\n {responseKind === \"image\" ? (\n <ResponseMedia src={mediaSrc} alt=\"Response\" />\n ) : responseKind === \"video\" ? (\n <video\n controls\n src={mediaSrc}\n style={{ maxWidth: \"100%\" }}\n />\n ) : responseKind === \"audio\" ? (\n <audio controls src={mediaSrc} />\n ) : responseKind === \"binary\" ? (\n <a href={mediaSrc} download>\n Download response ({response.byteLength} bytes)\n </a>\n ) : (\n <Code\n language={codeLanguage(response.contentType)}\n code={prettyBody(response.contentType, response.body)}\n />\n )}\n </CardBody>\n </Card>\n ) : (\n <Placeholder>\n Send the request to see the live response here.\n </Placeholder>\n )}\n {loading ? (\n <LoadingOverlay>\n <Spinner size={22} />\n </LoadingOverlay>\n ) : null}\n </ResponseArea>\n\n {snippets.length > 0 ? <CodeTabs tabs={snippets} /> : null}\n </Column>\n </DialogBody>\n </Modal>\n </>\n );\n}\n";
|
|
1
|
+
export declare const apiPlaygroundTemplate = "\"use client\";\nimport React, { useCallback, useMemo, useRef, useState } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport {\n styledSmall,\n interactiveStyles,\n Input,\n Textarea,\n Modal,\n} from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { Code, CodeTabs } from \"@/components/layout/Code\";\nimport { Icon } from \"@/components/layout/Icon\";\nimport { Accordion } from \"@/components/layout/Accordion\";\nimport { Badge, httpMethodBadgeColor } from \"@/components/layout/Badge\";\nimport { Callout } from \"@/components/layout/Callout\";\nimport { CopyButton } from \"@/components/layout/CopyButton\";\nimport { Spinner } from \"@/components/Spinner\";\nimport { matchAllowlist, matchAllowlistIn } from \"@/utils/playgroundAllowlist\";\nimport type { AllowlistEntry } from \"@/utils/playgroundAllowlist\";\nimport { buildSnippets } from \"@/utils/apiSnippets\";\nimport type { SnippetLanguage } from \"@/utils/apiSnippets\";\nimport {\n LOCATIONS,\n LOCATION_TITLES,\n applyPathParams,\n bufferToBase64,\n classifyResponse,\n codeLanguage,\n firstJsonExample,\n prettyBody,\n schemaTypeLabel,\n serverBase,\n} from \"@/utils/apiPlayground\";\nimport type { BuiltRequest, PlaygroundResponse } from \"@/utils/apiPlayground\";\nimport type { OperationDescriptor, ParameterDescriptor } from \"@/types/openapi\";\n\nexport interface ApiPlaygroundProps {\n operation: OperationDescriptor;\n defaultMode?: \"proxy\" | \"direct\";\n allowDirect?: boolean;\n // Extra client-side allowlist entries. The server proxy always enforces the\n // build-time allowlist regardless; this only relaxes the client pre-flight\n // (used by the docs demo to run in direct mode without a configured spec).\n allowlist?: AllowlistEntry[];\n snippetLanguages?: SnippetLanguage[];\n}\n\nfunction renderPath(path: string): React.ReactNode {\n return path\n .split(/(\\{[^}]+\\})/g)\n .map((part, index) =>\n part.startsWith(\"{\") ? (\n <PathParam key={index}>{part}</PathParam>\n ) : (\n <span key={index}>{part}</span>\n ),\n );\n}\n\n/* ---------- compact bar ---------- */\n\nconst CompactBar = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n margin: 0;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\n// The method chip is Badge's mono+solid variation; only bar-layout metrics\n// are adjusted here.\nconst MethodBadge = styled(Badge)`\n flex-shrink: 0;\n padding: 0 4px;\n border: none;\n`;\n\nconst PathText = styled.span`\n flex: 1;\n min-width: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n overflow-x: auto;\n white-space: nowrap;\n &::-webkit-scrollbar {\n display: none;\n }\n`;\n\nconst PathParam = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n overflow-wrap: anywhere;\n`;\n\nconst AccentButton = styled.button<{ theme: Theme }>`\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.text};\n font-weight: 600;\n font-size: 14px;\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n background: ${({ theme }: { theme: Theme }) => theme.colors.primary};\n border: none;\n padding: 8px 14px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n & svg {\n color: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n stroke: ${({ theme }: { theme: Theme }) => theme.colors.surface};\n }\n\n &:hover {\n background: ${({ theme }: { theme: Theme }) => theme.colors.primaryDark};\n }\n &:disabled {\n opacity: 0.6;\n cursor: default;\n }\n`;\n\n/* ---------- modal ---------- */\n\nconst DialogHeader = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n flex-wrap: wrap;\n margin: 5px 0 0 0;\n`;\n\nconst PathBar = styled.div`\n flex: 1;\n min-width: 200px;\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 8px 8px 12px;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n background: ${({ theme }: { theme: Theme }) => theme.colors.light};\n`;\n\nconst DialogBody = styled.div`\n display: grid;\n grid-template-columns: 1fr;\n gap: 20px;\n padding: 0;\n margin: 20px 0 0 0;\n\n ${mq(\"lg\")} {\n grid-template-columns: 1fr 1fr;\n }\n`;\n\nconst Column = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n min-width: 0;\n`;\n\nconst Description = styled.p`\n margin: 0;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n`;\n\nconst Toolbar = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n`;\n\nconst Toggle = styled.button<{ theme: Theme; $active?: boolean }>`\n position: relative;\n cursor: pointer;\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1;\n color: ${({ theme }) => theme.colors.accent};\n display: flex;\n gap: 6px;\n transition: all 0.3s ease;\n font-weight: 600;\n white-space: nowrap;\n min-width: fit-content;\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 10%, transparent)`};\n padding: 6px 8px;\n border: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n ${interactiveStyles};\n\n ${({ $active, theme }) =>\n $active &&\n css`\n background: ${theme.colors.primary};\n color: ${theme.colors.surface};\n `}\n`;\n\n/* ---------- collapsible card ---------- */\n\nconst Card = styled.div`\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n overflow: hidden;\n`;\n\nconst CardHead = styled.button`\n cursor: pointer;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n padding: 12px 20px;\n border: none;\n background: transparent;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst Inline = styled.span`\n display: inline-flex;\n align-items: center;\n gap: 8px;\n`;\n\nconst CardBody = styled.div`\n padding: 0 20px 20px;\n display: flex;\n flex-direction: column;\n gap: 16px;\n`;\n\n/* ---------- fields ---------- */\n\n// Wraps an accordion section's content and insets it, so full-width inputs'\n// focus rings (a 4px box-shadow) are not clipped by the accordion's own\n// overflow. Keeps the accordion component untouched.\nconst SectionInner = styled.div`\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 4px;\n`;\n\nconst Field = styled.div`\n display: flex;\n flex-direction: column;\n gap: 6px;\n`;\n\nconst FieldHead = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n`;\n\nconst FieldName = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n font-weight: 600;\n color: ${({ theme }: { theme: Theme }) => theme.colors.dark};\n`;\n\nconst TypeChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.gray} 15%, transparent)`};\n padding: 0 4px;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nconst RequiredChip = styled.span`\n font-family: ${({ theme }: { theme: Theme }) => theme.fonts.mono};\n color: ${({ theme }: { theme: Theme }) => theme.colors.error};\n`;\n\nconst FieldDesc = styled.p`\n margin: 0;\n width: 100%;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n/* ---------- response ---------- */\n\nconst StatusPill = styled.span<{ theme: Theme; $ok: boolean }>`\n font-family: ${({ theme }) => theme.fonts.mono};\n font-weight: 700;\n color: ${({ theme }) => theme.colors.surface};\n background: ${({ theme, $ok }) =>\n $ok ? theme.colors.success : theme.colors.error};\n padding: 0 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n`;\n\nconst Meta = styled.span`\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\nconst Placeholder = styled.div`\n border: dashed 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n padding: 24px;\n min-height: 120px;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 10px;\n text-align: center;\n ${({ theme }: { theme: Theme }) => styledSmall(theme)};\n color: ${({ theme }: { theme: Theme }) => theme.colors.gray};\n`;\n\n// Holds the response (or empty placeholder) and lets the loading spinner sit on\n// top of it, so a re-send keeps the previous content in place instead of\n// collapsing and jumping the layout.\nconst ResponseArea = styled.div`\n position: relative;\n`;\n\nconst LoadingOverlay = styled.div`\n position: absolute;\n inset: 0;\n z-index: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n border: solid 1px ${({ theme }: { theme: Theme }) => theme.colors.grayLight};\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.lg};\n color: ${({ theme }: { theme: Theme }) => theme.colors.grayDark};\n background: ${({ theme }: { theme: Theme }) =>\n `color-mix(in srgb, ${theme.colors.light} 60%, transparent)`};\n backdrop-filter: blur(1px);\n`;\n\nconst ResponseMedia = styled.img`\n max-width: 100%;\n border-radius: ${({ theme }: { theme: Theme }) => theme.spacing.radius.xs};\n`;\n\nexport function ApiPlayground({\n operation,\n defaultMode = \"proxy\",\n allowDirect = true,\n allowlist,\n snippetLanguages = [\"curl\", \"javascript\", \"python\"],\n}: ApiPlaygroundProps) {\n const [open, setOpen] = useState(false);\n const [paramValues, setParamValues] = useState<Record<string, string>>({});\n const [authValues, setAuthValues] = useState<Record<string, string>>({});\n const initialBody = useMemo(() => firstJsonExample(operation), [operation]);\n const [bodyText, setBodyText] = useState(initialBody?.text ?? \"\");\n const [mode, setMode] = useState<\"proxy\" | \"direct\">(defaultMode);\n const [showSecrets, setShowSecrets] = useState(false);\n const [loading, setLoading] = useState(false);\n const [response, setResponse] = useState<PlaygroundResponse | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [corsRetry, setCorsRetry] = useState(false);\n const abortRef = useRef<AbortController | null>(null);\n\n const paramKey = (p: ParameterDescriptor) => p.in + \":\" + p.name;\n\n const isAllowed = useCallback(\n (url: string) =>\n Boolean(\n matchAllowlist(url) ??\n (allowlist ? matchAllowlistIn(allowlist, url) : null),\n ),\n [allowlist],\n );\n\n const buildRequest = useCallback((): BuiltRequest => {\n const base = serverBase(operation.servers[0]);\n const pathValues: Record<string, string> = {};\n const queryParts: string[] = [];\n const headers: Record<string, string> = {};\n const secretHeaderNames: string[] = [];\n let cookie = \"\";\n\n for (const param of operation.parameters) {\n const value = paramValues[paramKey(param)];\n if (value === undefined || value === \"\") continue;\n if (param.in === \"path\") pathValues[param.name] = value;\n else if (param.in === \"query\")\n queryParts.push(\n encodeURIComponent(param.name) + \"=\" + encodeURIComponent(value),\n );\n else if (param.in === \"header\") headers[param.name] = value;\n else if (param.in === \"cookie\")\n cookie += (cookie ? \"; \" : \"\") + param.name + \"=\" + value;\n }\n\n for (const requirement of operation.security) {\n const scheme = requirement.scheme;\n if (!scheme) continue;\n if (scheme.type === \"apiKey\" && scheme.name) {\n const value = authValues[requirement.schemeName];\n if (!value) continue;\n if (scheme.in === \"header\") {\n headers[scheme.name] = value;\n secretHeaderNames.push(scheme.name);\n } else if (scheme.in === \"query\") {\n queryParts.push(\n encodeURIComponent(scheme.name) + \"=\" + encodeURIComponent(value),\n );\n } else if (scheme.in === \"cookie\") {\n cookie += (cookie ? \"; \" : \"\") + scheme.name + \"=\" + value;\n }\n } else if (scheme.type === \"http\" && scheme.scheme === \"basic\") {\n const user = authValues[requirement.schemeName + \":user\"] ?? \"\";\n const pass = authValues[requirement.schemeName + \":pass\"] ?? \"\";\n if (user || pass) {\n headers[\"Authorization\"] = \"Basic \" + btoa(user + \":\" + pass);\n secretHeaderNames.push(\"Authorization\");\n }\n } else {\n const token = authValues[requirement.schemeName];\n if (token) {\n headers[\"Authorization\"] = \"Bearer \" + token;\n secretHeaderNames.push(\"Authorization\");\n }\n }\n }\n\n if (cookie) headers[\"Cookie\"] = cookie;\n\n const hasBody =\n operation.requestBody !== undefined &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" &&\n bodyText.trim() !== \"\";\n if (hasBody && !headers[\"Content-Type\"] && initialBody) {\n headers[\"Content-Type\"] = initialBody.contentType;\n }\n\n const query = queryParts.join(\"&\");\n const url =\n base +\n applyPathParams(operation.path, pathValues) +\n (query ? \"?\" + query : \"\");\n\n return { url, headers, body: hasBody ? bodyText : null, secretHeaderNames };\n }, [operation, paramValues, authValues, bodyText, initialBody]);\n\n const snippets = useMemo(() => {\n const built = buildRequest();\n const headers: Record<string, string> = { ...built.headers };\n if (!showSecrets) {\n for (const name of built.secretHeaderNames) {\n headers[name] = \"<YOUR_CREDENTIALS>\";\n }\n }\n return buildSnippets(\n {\n method: operation.method.toUpperCase(),\n url: built.url || operation.path,\n headers,\n body: built.body,\n },\n snippetLanguages,\n );\n }, [buildRequest, showSecrets, operation, snippetLanguages]);\n\n const sendProxy = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const res = await fetch(\"/api/playground\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n signal,\n body: JSON.stringify({\n targetUrl: built.url,\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n bodyEncoding: \"utf8\",\n }),\n });\n const data = await res.json();\n if (!res.ok) {\n throw new Error(\n typeof data?.error === \"string\" ? data.error : \"Request failed\",\n );\n }\n return data as PlaygroundResponse;\n },\n [operation],\n );\n\n const sendDirect = useCallback(\n async (\n built: BuiltRequest,\n signal: AbortSignal,\n ): Promise<PlaygroundResponse> => {\n const start = Date.now();\n const res = await fetch(built.url, {\n method: operation.method.toUpperCase(),\n headers: built.headers,\n body: built.body ?? undefined,\n signal,\n });\n const buffer = await res.arrayBuffer();\n const contentType = res.headers.get(\"content-type\");\n const isText = classifyResponse(contentType) === \"text\";\n const headers: Record<string, string> = {};\n res.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return {\n status: res.status,\n statusText: res.statusText,\n headers,\n contentType,\n bodyEncoding: isText ? \"utf8\" : \"base64\",\n body: isText\n ? new TextDecoder().decode(buffer)\n : bufferToBase64(buffer),\n truncated: false,\n byteLength: buffer.byteLength,\n durationMs: Date.now() - start,\n };\n },\n [operation],\n );\n\n const send = useCallback(async () => {\n setError(null);\n setCorsRetry(false);\n // Keep any previous response on screen; the loading overlay covers it so\n // the layout does not collapse and jump while the new request is in flight.\n\n const built = buildRequest();\n if (!built.url) {\n setError(\"No server URL is configured for this endpoint.\");\n return;\n }\n if (!isAllowed(built.url)) {\n setError(\"This endpoint's server is not in the allowed list.\");\n return;\n }\n if (\n mode === \"direct\" &&\n typeof window !== \"undefined\" &&\n window.location.protocol === \"https:\" &&\n built.url.startsWith(\"http:\")\n ) {\n setError(\n \"Browsers block HTTP requests from an HTTPS page. Use proxy mode.\",\n );\n return;\n }\n\n const controller = new AbortController();\n abortRef.current = controller;\n setLoading(true);\n try {\n const result =\n mode === \"direct\"\n ? await sendDirect(built, controller.signal)\n : await sendProxy(built, controller.signal);\n setResponse(result);\n } catch (err) {\n if (controller.signal.aborted) return;\n if (mode === \"direct\" && err instanceof TypeError) {\n setCorsRetry(true);\n setError(\n \"The browser blocked this cross-origin request (CORS). Run it server-side instead.\",\n );\n } else {\n setError(err instanceof Error ? err.message : \"Request failed\");\n }\n } finally {\n setLoading(false);\n abortRef.current = null;\n }\n }, [buildRequest, isAllowed, mode, sendDirect, sendProxy]);\n\n const retryViaProxy = useCallback(() => {\n setMode(\"proxy\");\n setCorsRetry(false);\n void send();\n }, [send]);\n\n const groupedParams = LOCATIONS.map((location) => ({\n location,\n params: operation.parameters.filter((p) => p.in === location),\n })).filter((group) => group.params.length > 0);\n // Only the first visible section starts expanded.\n const hasAuth = operation.security.length > 0;\n\n const responseKind = response ? classifyResponse(response.contentType) : null;\n const mediaSrc =\n response && responseKind && responseKind !== \"text\"\n ? \"data:\" +\n (response.contentType ?? \"application/octet-stream\") +\n \";base64,\" +\n response.body\n : \"\";\n\n const renderParamField = (param: ParameterDescriptor) => (\n <Field key={param.anchorId}>\n <FieldHead>\n <FieldName>{param.name}</FieldName>\n <TypeChip>{schemaTypeLabel(param.schema)}</TypeChip>\n {param.required ? <RequiredChip>required</RequiredChip> : null}\n </FieldHead>\n {param.description ? <FieldDesc>{param.description}</FieldDesc> : null}\n <Input\n $fullWidth\n type=\"text\"\n aria-label={param.name}\n placeholder={\n param.example !== undefined\n ? String(param.example)\n : \"enter \" + param.name\n }\n value={paramValues[paramKey(param)] ?? \"\"}\n onChange={(e) =>\n setParamValues((prev) => ({\n ...prev,\n [paramKey(param)]: e.target.value,\n }))\n }\n />\n </Field>\n );\n\n return (\n <>\n <CompactBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <CopyButton\n text={operation.method.toUpperCase() + \" \" + operation.path}\n label=\"Copy endpoint\"\n size={16}\n />\n <AccentButton type=\"button\" onClick={() => setOpen(true)}>\n Try it\n <Icon name=\"play\" size={14} />\n </AccentButton>\n </CompactBar>\n\n <Modal\n $isOpen={open}\n $onClose={() => setOpen(false)}\n $width={1120}\n $title={\n operation.summary ??\n operation.method.toUpperCase() + \" \" + operation.path\n }\n >\n <DialogHeader>\n <PathBar>\n <MethodBadge\n mono\n solid\n size=\"sm\"\n color={httpMethodBadgeColor(operation.method)}\n >\n {operation.method}\n </MethodBadge>\n <PathText>{renderPath(operation.path)}</PathText>\n <AccentButton\n type=\"button\"\n onClick={() => void send()}\n disabled={loading}\n >\n Send\n {loading ? <Spinner size={14} /> : <Icon name=\"play\" size={14} />}\n </AccentButton>\n </PathBar>\n </DialogHeader>\n\n <DialogBody>\n <Column>\n {operation.description || operation.summary ? (\n <Description>\n {operation.description ?? operation.summary}\n </Description>\n ) : null}\n\n <Toolbar>\n {operation.servers.length > 0 ? (\n <Meta>{serverBase(operation.servers[0])}</Meta>\n ) : null}\n {allowDirect ? (\n <>\n <Toggle\n type=\"button\"\n $active={mode === \"proxy\"}\n onClick={() => setMode(\"proxy\")}\n >\n Proxy\n </Toggle>\n <Toggle\n type=\"button\"\n $active={mode === \"direct\"}\n onClick={() => setMode(\"direct\")}\n >\n Direct\n </Toggle>\n </>\n ) : null}\n <Toggle\n type=\"button\"\n $active={showSecrets}\n onClick={() => setShowSecrets((v) => !v)}\n >\n {showSecrets ? \"Hide secrets\" : \"Show secrets\"}\n </Toggle>\n </Toolbar>\n\n {operation.security.length > 0 ? (\n <Accordion title=\"Authorization\" defaultOpen>\n <SectionInner>\n {operation.security.map((requirement) => {\n const scheme = requirement.scheme;\n if (\n scheme &&\n scheme.type === \"http\" &&\n scheme.scheme === \"basic\"\n ) {\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>basic</TypeChip>\n </FieldHead>\n <Input\n $fullWidth\n type=\"text\"\n aria-label={requirement.schemeName + \" username\"}\n placeholder=\"username\"\n value={\n authValues[requirement.schemeName + \":user\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":user\"]:\n e.target.value,\n }))\n }\n />\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName + \" password\"}\n placeholder=\"password\"\n value={\n authValues[requirement.schemeName + \":pass\"] ?? \"\"\n }\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName + \":pass\"]:\n e.target.value,\n }))\n }\n />\n </Field>\n );\n }\n const chip =\n scheme?.type === \"apiKey\"\n ? \"apiKey\"\n : scheme?.scheme === \"bearer\"\n ? \"bearer\"\n : (scheme?.type ?? \"token\");\n return (\n <Field key={requirement.schemeName}>\n <FieldHead>\n <FieldName>{requirement.schemeName}</FieldName>\n <TypeChip>{chip}</TypeChip>\n <RequiredChip>required</RequiredChip>\n </FieldHead>\n <Input\n $fullWidth\n type={showSecrets ? \"text\" : \"password\"}\n aria-label={requirement.schemeName}\n placeholder={\n chip === \"bearer\"\n ? \"enter bearer token\"\n : \"enter value\"\n }\n value={authValues[requirement.schemeName] ?? \"\"}\n onChange={(e) =>\n setAuthValues((prev) => ({\n ...prev,\n [requirement.schemeName]: e.target.value,\n }))\n }\n />\n </Field>\n );\n })}\n </SectionInner>\n </Accordion>\n ) : null}\n\n {groupedParams.map((group, index) => (\n <Accordion\n key={group.location}\n title={LOCATION_TITLES[group.location]}\n defaultOpen={!hasAuth && index === 0}\n >\n <SectionInner>\n {group.params.map(renderParamField)}\n </SectionInner>\n </Accordion>\n ))}\n\n {operation.requestBody &&\n operation.method !== \"get\" &&\n operation.method !== \"head\" ? (\n <Accordion\n title=\"Body\"\n defaultOpen={!hasAuth && groupedParams.length === 0}\n >\n <SectionInner>\n <Textarea\n $fullWidth\n rows={8}\n aria-label=\"Request body\"\n spellCheck={false}\n value={bodyText}\n onChange={(e) => setBodyText(e.target.value)}\n />\n </SectionInner>\n </Accordion>\n ) : null}\n\n {error ? (\n <Field>\n <Callout type=\"danger\">\n <p>{error}</p>\n </Callout>\n {corsRetry ? (\n <Toggle type=\"button\" onClick={retryViaProxy}>\n Retry via proxy\n </Toggle>\n ) : null}\n </Field>\n ) : null}\n </Column>\n\n <Column>\n <ResponseArea>\n {response ? (\n <Card>\n <CardHead as=\"div\">\n <Inline>\n <StatusPill\n $ok={response.status >= 200 && response.status < 400}\n >\n {response.status} {response.statusText}\n </StatusPill>\n <Meta>{response.durationMs}ms</Meta>\n <Meta>{response.byteLength} bytes</Meta>\n {response.truncated ? <Meta>(truncated)</Meta> : null}\n </Inline>\n </CardHead>\n <CardBody>\n {responseKind === \"image\" ? (\n <ResponseMedia src={mediaSrc} alt=\"Response\" />\n ) : responseKind === \"video\" ? (\n <video\n controls\n src={mediaSrc}\n style={{ maxWidth: \"100%\" }}\n />\n ) : responseKind === \"audio\" ? (\n <audio controls src={mediaSrc} />\n ) : responseKind === \"binary\" ? (\n <a href={mediaSrc} download>\n Download response ({response.byteLength} bytes)\n </a>\n ) : (\n <Code\n language={codeLanguage(response.contentType)}\n code={prettyBody(response.contentType, response.body)}\n />\n )}\n </CardBody>\n </Card>\n ) : (\n <Placeholder>\n Send the request to see the live response here.\n </Placeholder>\n )}\n {loading ? (\n <LoadingOverlay>\n <Spinner size={22} />\n </LoadingOverlay>\n ) : null}\n </ResponseArea>\n\n {snippets.length > 0 ? <CodeTabs tabs={snippets} /> : null}\n </Column>\n </DialogBody>\n </Modal>\n </>\n );\n}\n";
|
|
@@ -20,30 +20,20 @@ import { matchAllowlist, matchAllowlistIn } from "@/utils/playgroundAllowlist";
|
|
|
20
20
|
import type { AllowlistEntry } from "@/utils/playgroundAllowlist";
|
|
21
21
|
import { buildSnippets } from "@/utils/apiSnippets";
|
|
22
22
|
import type { SnippetLanguage } from "@/utils/apiSnippets";
|
|
23
|
-
import
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
byteLength: number;
|
|
38
|
-
durationMs: number;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
interface BuiltRequest {
|
|
42
|
-
url: string;
|
|
43
|
-
headers: Record<string, string>;
|
|
44
|
-
body: string | null;
|
|
45
|
-
secretHeaderNames: string[];
|
|
46
|
-
}
|
|
23
|
+
import {
|
|
24
|
+
LOCATIONS,
|
|
25
|
+
LOCATION_TITLES,
|
|
26
|
+
applyPathParams,
|
|
27
|
+
bufferToBase64,
|
|
28
|
+
classifyResponse,
|
|
29
|
+
codeLanguage,
|
|
30
|
+
firstJsonExample,
|
|
31
|
+
prettyBody,
|
|
32
|
+
schemaTypeLabel,
|
|
33
|
+
serverBase,
|
|
34
|
+
} from "@/utils/apiPlayground";
|
|
35
|
+
import type { BuiltRequest, PlaygroundResponse } from "@/utils/apiPlayground";
|
|
36
|
+
import type { OperationDescriptor, ParameterDescriptor } from "@/types/openapi";
|
|
47
37
|
|
|
48
38
|
export interface ApiPlaygroundProps {
|
|
49
39
|
operation: OperationDescriptor;
|
|
@@ -56,116 +46,6 @@ export interface ApiPlaygroundProps {
|
|
|
56
46
|
snippetLanguages?: SnippetLanguage[];
|
|
57
47
|
}
|
|
58
48
|
|
|
59
|
-
function schemaTypeLabel(schema: unknown): string {
|
|
60
|
-
if (schema && typeof schema === "object") {
|
|
61
|
-
const record = schema as { type?: unknown; format?: unknown };
|
|
62
|
-
if (typeof record.type === "string") {
|
|
63
|
-
return typeof record.format === "string"
|
|
64
|
-
? record.type + " (" + record.format + ")"
|
|
65
|
-
: record.type;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return "string";
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function serverBase(server: ServerDescriptor | undefined): string {
|
|
72
|
-
if (!server) return "";
|
|
73
|
-
let url = server.url;
|
|
74
|
-
const variables = server.variables;
|
|
75
|
-
if (variables) {
|
|
76
|
-
for (const key of Object.keys(variables)) {
|
|
77
|
-
url = url.split("{" + key + "}").join(variables[key].default);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
while (url.endsWith("/")) url = url.slice(0, -1);
|
|
81
|
-
return url;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function applyPathParams(
|
|
85
|
-
template: string,
|
|
86
|
-
values: Record<string, string>,
|
|
87
|
-
): string {
|
|
88
|
-
let result = template;
|
|
89
|
-
for (const key of Object.keys(values)) {
|
|
90
|
-
result = result
|
|
91
|
-
.split("{" + key + "}")
|
|
92
|
-
.join(encodeURIComponent(values[key]));
|
|
93
|
-
}
|
|
94
|
-
return result;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
function firstJsonExample(op: OperationDescriptor): {
|
|
98
|
-
contentType: string;
|
|
99
|
-
text: string;
|
|
100
|
-
} | null {
|
|
101
|
-
if (!op.requestBody || op.requestBody.content.length === 0) return null;
|
|
102
|
-
const media =
|
|
103
|
-
op.requestBody.content.find((m) => m.contentType.includes("json")) ??
|
|
104
|
-
op.requestBody.content[0];
|
|
105
|
-
let text = "";
|
|
106
|
-
if (media.example !== undefined) {
|
|
107
|
-
try {
|
|
108
|
-
text = JSON.stringify(media.example, null, 2);
|
|
109
|
-
} catch {
|
|
110
|
-
text = "";
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
return { contentType: media.contentType, text };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function classifyResponse(
|
|
117
|
-
contentType: string | null,
|
|
118
|
-
): "image" | "video" | "audio" | "text" | "binary" {
|
|
119
|
-
if (!contentType) return "text";
|
|
120
|
-
const t = contentType.toLowerCase();
|
|
121
|
-
if (t.startsWith("image/") && !t.includes("svg")) return "image";
|
|
122
|
-
if (t.startsWith("video/")) return "video";
|
|
123
|
-
if (t.startsWith("audio/")) return "audio";
|
|
124
|
-
if (
|
|
125
|
-
t.includes("json") ||
|
|
126
|
-
t.startsWith("text/") ||
|
|
127
|
-
t.includes("xml") ||
|
|
128
|
-
t.includes("svg") ||
|
|
129
|
-
t.includes("html") ||
|
|
130
|
-
t.includes("javascript") ||
|
|
131
|
-
t.includes("csv")
|
|
132
|
-
) {
|
|
133
|
-
return "text";
|
|
134
|
-
}
|
|
135
|
-
return "binary";
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function codeLanguage(contentType: string | null): string {
|
|
139
|
-
if (!contentType) return "text";
|
|
140
|
-
const t = contentType.toLowerCase();
|
|
141
|
-
if (t.includes("json")) return "json";
|
|
142
|
-
if (t.includes("html")) return "html";
|
|
143
|
-
if (t.includes("xml") || t.includes("svg")) return "xml";
|
|
144
|
-
if (t.includes("javascript")) return "javascript";
|
|
145
|
-
return "text";
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function prettyBody(contentType: string | null, body: string): string {
|
|
149
|
-
if (contentType && contentType.toLowerCase().includes("json")) {
|
|
150
|
-
try {
|
|
151
|
-
return JSON.stringify(JSON.parse(body), null, 2);
|
|
152
|
-
} catch {
|
|
153
|
-
return body;
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
return body;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
function bufferToBase64(buffer: ArrayBuffer): string {
|
|
160
|
-
let binary = "";
|
|
161
|
-
const bytes = new Uint8Array(buffer);
|
|
162
|
-
const chunk = 0x8000;
|
|
163
|
-
for (let i = 0; i < bytes.length; i += chunk) {
|
|
164
|
-
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
165
|
-
}
|
|
166
|
-
return btoa(binary);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
49
|
function renderPath(path: string): React.ReactNode {
|
|
170
50
|
return path
|
|
171
51
|
.split(/(\\{[^}]+\\})/g)
|
|
@@ -178,20 +58,6 @@ function renderPath(path: string): React.ReactNode {
|
|
|
178
58
|
);
|
|
179
59
|
}
|
|
180
60
|
|
|
181
|
-
const LOCATIONS: ParameterDescriptor["in"][] = [
|
|
182
|
-
"path",
|
|
183
|
-
"query",
|
|
184
|
-
"header",
|
|
185
|
-
"cookie",
|
|
186
|
-
];
|
|
187
|
-
|
|
188
|
-
const LOCATION_TITLES: Record<string, string> = {
|
|
189
|
-
path: "Path",
|
|
190
|
-
query: "Query",
|
|
191
|
-
header: "Headers",
|
|
192
|
-
cookie: "Cookies",
|
|
193
|
-
};
|
|
194
|
-
|
|
195
61
|
/* ---------- compact bar ---------- */
|
|
196
62
|
|
|
197
63
|
const CompactBar = styled.div\`
|