doccupine 0.0.150 → 0.0.152
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/dist/lib/layout.js +21 -26
- package/dist/lib/structures.js +2 -0
- package/dist/templates/app/manifest.d.ts +1 -0
- package/dist/templates/app/manifest.js +26 -0
- package/dist/templates/components/SearchDocs.d.ts +1 -1
- package/dist/templates/components/SearchDocs.js +5 -1
- package/dist/templates/components/layout/Header.d.ts +1 -1
- package/dist/templates/components/layout/Header.js +103 -42
- package/dist/templates/mdx/globals.mdx.d.ts +1 -1
- package/dist/templates/mdx/globals.mdx.js +2 -0
- package/dist/templates/package.js +1 -1
- package/dist/templates/utils/icons.d.ts +1 -1
- package/dist/templates/utils/icons.js +13 -0
- package/package.json +1 -1
package/dist/lib/layout.js
CHANGED
|
@@ -90,21 +90,28 @@ function fontDeclLine(fontConfig) {
|
|
|
90
90
|
// and seeding the cookie so Cherry's ClientThemeProvider reconciles against
|
|
91
91
|
// the same answer on mount instead of flipping the class back.
|
|
92
92
|
//
|
|
93
|
-
// The script also
|
|
94
|
-
//
|
|
95
|
-
// tints reliably from a tag
|
|
96
|
-
//
|
|
97
|
-
// content updates to
|
|
98
|
-
//
|
|
93
|
+
// The script also emits the theme-color meta for the resolved mode through
|
|
94
|
+
// document.write, which hands the tag to the HTML parser itself: Safari only
|
|
95
|
+
// tints its chrome reliably from a parser-inserted tag - one created through
|
|
96
|
+
// the DOM APIs is honored inconsistently or not at all - though it does track
|
|
97
|
+
// content updates to such a tag, which is how Cherry's post-hydration sync
|
|
98
|
+
// and theme toggles keep it current. The meta cannot be rendered from the
|
|
99
|
+
// layout instead: pages are static, so the server would emit one mode's color
|
|
100
|
+
// and this script would have to correct it before paint, and React 19
|
|
101
|
+
// hydration treats a head meta whose attributes differ from its props as
|
|
102
|
+
// missing and inserts a duplicate with the stale light color beside it -
|
|
103
|
+
// suppressHydrationWarning does not cover hoisted metas, and a meta emitted
|
|
104
|
+
// through Next's viewport export hydrates the same way (both verified against
|
|
105
|
+
// Next 16.3; the duplicate is what broke the chrome tint on iPad Safari).
|
|
106
|
+
// OS-scheme-scoped SSR metas are no answer either: the site's mode is
|
|
99
107
|
// cookie-based, so a dark site on a light-OS device would show the wrong
|
|
100
|
-
// browser chrome until hydration - a visible flash on every load.
|
|
101
|
-
//
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
|
|
107
|
-
const THEME_INIT_SCRIPT = `(function(){try{var c=document.cookie.split(";").map(function(s){return s.trim();}).find(function(s){return s.indexOf("theme=")===0;});var v=c?c.split("=")[1]:null;var d=v?v==="dark":(window.matchMedia&&window.matchMedia("(prefers-color-scheme:dark)").matches);if(!v){document.cookie="theme="+(d?"dark":"light")+";path=/;max-age=31536000;SameSite=Lax";}var r=document.documentElement;r.dataset.theme=d?"dark":"light";if(d){r.classList.add("dark");}var m=document.querySelector('meta[name="theme-color"]');if(!m){m=document.createElement("meta");m.name="theme-color";document.head.appendChild(m);}m.content=d?"\${colorsDark.primary}":"\${colorsLight.primary}";}catch(e){}})();`;
|
|
108
|
+
// browser chrome until hydration - a visible flash on every load. Keeping the
|
|
109
|
+
// tag out of React leaves exactly one meta that nothing ever re-inserts. The
|
|
110
|
+
// \${...} palette interpolations below are escaped so they resolve in the
|
|
111
|
+
// generated layout, at app build time, from the imported theme palettes. The
|
|
112
|
+
// token must match the provider's $themeColor (primary), so the pre-paint
|
|
113
|
+
// chrome color equals what Cherry syncs after hydration.
|
|
114
|
+
const THEME_INIT_SCRIPT = `(function(){try{var c=document.cookie.split(";").map(function(s){return s.trim();}).find(function(s){return s.indexOf("theme=")===0;});var v=c?c.split("=")[1]:null;var d=v?v==="dark":(window.matchMedia&&window.matchMedia("(prefers-color-scheme:dark)").matches);if(!v){document.cookie="theme="+(d?"dark":"light")+";path=/;max-age=31536000;SameSite=Lax";}var r=document.documentElement;r.dataset.theme=d?"dark":"light";if(d){r.classList.add("dark");}document.write('<meta name="theme-color" content="'+(d?"\${colorsDark.primary}":"\${colorsLight.primary}")+'">');}catch(e){}})();`;
|
|
108
115
|
/**
|
|
109
116
|
* Root layout ("app/layout.tsx"). Minimal shell: html/body, fonts, the theme
|
|
110
117
|
* provider stack, and (optionally) PostHog. It renders `children` directly so
|
|
@@ -159,18 +166,6 @@ export default function RootLayout({
|
|
|
159
166
|
return (
|
|
160
167
|
<html lang="en" suppressHydrationWarning>
|
|
161
168
|
<head>
|
|
162
|
-
{/* Server-rendered so Safari has a real tag to tint from: WebKit
|
|
163
|
-
honors a theme-color meta created by script inconsistently, but
|
|
164
|
-
reliably tracks content updates to an existing one. Pages are
|
|
165
|
-
static, so the value is the light primary; the blocking script
|
|
166
|
-
below corrects it before first paint and Cherry keeps it in sync
|
|
167
|
-
after hydration. suppressHydrationWarning: the script edits
|
|
168
|
-
content before React hydrates. */}
|
|
169
|
-
<meta
|
|
170
|
-
name="theme-color"
|
|
171
|
-
content={colorsLight.primary}
|
|
172
|
-
suppressHydrationWarning
|
|
173
|
-
/>
|
|
174
169
|
{/* Resolves dark mode before the first paint by stamping data-theme
|
|
175
170
|
on <html>, which flips the CSS variables in GlobalStyles.
|
|
176
171
|
Inlined as a plain <script> (not next/script) so it ships in the
|
package/dist/lib/structures.js
CHANGED
|
@@ -12,6 +12,7 @@ import { mcpRoutesTemplate } from "../templates/app/api/mcp/route.js";
|
|
|
12
12
|
import { ragRoutesTemplate } from "../templates/app/api/rag/route.js";
|
|
13
13
|
import { searchRoutesTemplate } from "../templates/app/api/search/route.js";
|
|
14
14
|
import { notFoundTemplate } from "../templates/app/not-found.js";
|
|
15
|
+
import { manifestTemplate } from "../templates/app/manifest.js";
|
|
15
16
|
import { themeTemplate } from "../templates/app/theme.js";
|
|
16
17
|
import { chatTemplate } from "../templates/components/Chat.js";
|
|
17
18
|
import { lockBodyScrollTemplate } from "../templates/components/LockBodyScroll.js";
|
|
@@ -173,6 +174,7 @@ export const appStructure = {
|
|
|
173
174
|
"tsconfig.json": tsconfigTemplate,
|
|
174
175
|
"app/not-found.tsx": notFoundTemplate,
|
|
175
176
|
"app/gate/page.tsx": gatePageTemplate,
|
|
177
|
+
"app/manifest.ts": manifestTemplate,
|
|
176
178
|
"app/theme.ts": themeTemplate,
|
|
177
179
|
"app/api/gate/route.ts": gateRoutesTemplate,
|
|
178
180
|
"app/api/mcp/route.ts": mcpRoutesTemplate,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const manifestTemplate = "import type { MetadataRoute } from \"next\";\nimport { colorsLight } from \"@/app/theme\";\nimport { config } from \"@/utils/config\";\nimport { manifestIcons } from \"@/utils/icons\";\n\n// Served by Next as /manifest.webmanifest and linked from every page's head\n// automatically. theme_color and background_color come from the light\n// palette: the manifest is static, so it cannot follow the cookie-based\n// mode - the pre-paint script and Cherry's provider own the live chrome\n// color through the theme-color meta.\nexport default function manifest(): MetadataRoute.Manifest {\n return {\n name: config.name || \"Doccupine\",\n short_name: config.name || \"Doccupine\",\n description:\n config.description ||\n \"Doccupine is a free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.\",\n start_url: \"/\",\n display: \"standalone\",\n background_color: colorsLight.light,\n theme_color: colorsLight.primary,\n ...(manifestIcons.length > 0 ? { icons: manifestIcons } : {}),\n };\n}\n";
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { DEFAULT_DESCRIPTION, DEFAULT_SITE_NAME } from "../../lib/constants.js";
|
|
2
|
+
export const manifestTemplate = `import type { MetadataRoute } from "next";
|
|
3
|
+
import { colorsLight } from "@/app/theme";
|
|
4
|
+
import { config } from "@/utils/config";
|
|
5
|
+
import { manifestIcons } from "@/utils/icons";
|
|
6
|
+
|
|
7
|
+
// Served by Next as /manifest.webmanifest and linked from every page's head
|
|
8
|
+
// automatically. theme_color and background_color come from the light
|
|
9
|
+
// palette: the manifest is static, so it cannot follow the cookie-based
|
|
10
|
+
// mode - the pre-paint script and Cherry's provider own the live chrome
|
|
11
|
+
// color through the theme-color meta.
|
|
12
|
+
export default function manifest(): MetadataRoute.Manifest {
|
|
13
|
+
return {
|
|
14
|
+
name: config.name || "${DEFAULT_SITE_NAME}",
|
|
15
|
+
short_name: config.name || "${DEFAULT_SITE_NAME}",
|
|
16
|
+
description:
|
|
17
|
+
config.description ||
|
|
18
|
+
"${DEFAULT_DESCRIPTION}",
|
|
19
|
+
start_url: "/",
|
|
20
|
+
display: "standalone",
|
|
21
|
+
background_color: colorsLight.light,
|
|
22
|
+
theme_color: colorsLight.primary,
|
|
23
|
+
...(manifestIcons.length > 0 ? { icons: manifestIcons } : {}),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const searchDocsTemplate = "\"use client\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport dynamic from \"next/dynamic\";\nimport styled from \"styled-components\";\nimport { useChat } from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { interactiveStyles } from \"@/components/layout/SharedStyled\";\nimport { ChatContext } from \"@/components/Chat\";\nimport type { PageItem, MergedResult } from \"@/components/SearchModalContent\";\n\nconst SearchModalContent = dynamic(\n () =>\n import(\"@/components/SearchModalContent\").then(\n (mod) => mod.SearchModalContent,\n ),\n { ssr: false },\n);\n\ninterface SectionItem {\n label: string;\n slug: string;\n}\n\n// Stable empty array so the derived contentResults keeps the same identity\n// across renders when there are no hits (memo deps stay stable).\nconst EMPTY_RESULTS: ContentHit[] = [];\n\ninterface ContentHit {\n slug: string;\n snippet: string;\n}\n\ninterface SearchContextValue {\n openSearch: () => void;\n}\n\nconst SearchContext = createContext<SearchContextValue>({\n openSearch: () => {},\n});\n\nconst StyledKbd = styled.kbd<{ theme: Theme }>`\n font-size: 11px;\n font-family: inherit;\n background: ${({ theme }) => theme.colors.grayLight};\n color: ${({ theme }) => theme.colors.grayDark};\n padding: 2px 6px;\n border-radius: 4px;\n margin-left: auto;\n font-weight: 600;\n display: none;\n\n ${mq(\"lg\")} {\n display: initial;\n }\n`;\n\nconst StyledSearchButton = styled.button<{ theme: Theme }>`\n ${interactiveStyles};\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n display: flex;\n align-items: center;\n gap: 6px;\n /* Pinned to the 30px compact header-control tier, matching Cherry's\n ChatLauncher, so the height cannot drift with platform font metrics\n and the header controls always align exactly. */\n box-sizing: border-box;\n height: 30px;\n background: ${({ theme }) => theme.colors.light};\n color: ${({ theme }) => theme.colors.primary};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n padding: 0 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";
|
|
1
|
+
export declare const searchDocsTemplate = "\"use client\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useRouter } from \"next/navigation\";\nimport dynamic from \"next/dynamic\";\nimport styled from \"styled-components\";\nimport { useChat } from \"cherry-styled-components\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { interactiveStyles } from \"@/components/layout/SharedStyled\";\nimport { ChatContext } from \"@/components/Chat\";\nimport type { PageItem, MergedResult } from \"@/components/SearchModalContent\";\n\nconst SearchModalContent = dynamic(\n () =>\n import(\"@/components/SearchModalContent\").then(\n (mod) => mod.SearchModalContent,\n ),\n { ssr: false },\n);\n\ninterface SectionItem {\n label: string;\n slug: string;\n}\n\n// Stable empty array so the derived contentResults keeps the same identity\n// across renders when there are no hits (memo deps stay stable).\nconst EMPTY_RESULTS: ContentHit[] = [];\n\ninterface ContentHit {\n slug: string;\n snippet: string;\n}\n\ninterface SearchContextValue {\n openSearch: () => void;\n}\n\nconst SearchContext = createContext<SearchContextValue>({\n openSearch: () => {},\n});\n\nconst StyledKbd = styled.kbd<{ theme: Theme }>`\n font-size: 11px;\n font-family: inherit;\n background: ${({ theme }) => theme.colors.grayLight};\n color: ${({ theme }) => theme.colors.grayDark};\n padding: 2px 6px;\n border-radius: 4px;\n margin-left: auto;\n font-weight: 600;\n display: none;\n\n ${mq(\"lg\")} {\n display: initial;\n }\n`;\n\nconst StyledSearchButton = styled.button<{ theme: Theme }>`\n ${interactiveStyles};\n border: solid 1px ${({ theme }) => theme.colors.grayLight};\n display: flex;\n align-items: center;\n gap: 6px;\n /* Pinned to the 30px compact header-control tier, matching Cherry's\n ChatLauncher, so the height cannot drift with platform font metrics\n and the header controls always align exactly. */\n box-sizing: border-box;\n height: 30px;\n background: ${({ theme }) => theme.colors.light};\n color: ${({ theme }) => theme.colors.primary};\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n padding: 0 8px;\n font-family: inherit;\n cursor: pointer;\n\n & svg.lucide {\n color: inherit;\n min-width: 14px;\n }\n\n ${mq(\"lg\")} {\n padding: 0 4px 0 8px;\n }\n`;\n\nfunction SearchProvider({\n pages,\n sections,\n children,\n}: {\n pages: PageItem[];\n sections?: SectionItem[];\n children: React.ReactNode;\n}) {\n const [isVisible, setIsVisible] = useState(false);\n const [isClosing, setIsClosing] = useState(false);\n const [query, setQuery] = useState(\"\");\n const [activeIndex, setActiveIndex] = useState(0);\n const [returnFocusTo, setReturnFocusTo] = useState<HTMLElement | null>(null);\n // Latest completed content search, keyed by the query that produced it.\n // contentResults and isSearching are derived from it at render time, so\n // the debounced-search effect never sets state synchronously (which would\n // trigger cascading renders \u2014 react-hooks/set-state-in-effect).\n const [fetched, setFetched] = useState<{\n q: string;\n results: ContentHit[];\n } | null>(null);\n const resultsRef = useRef<HTMLUListElement>(null);\n const closingRef = useRef(false);\n const isVisibleRef = useRef(false);\n const searchOpenerRef = useRef<HTMLElement | null>(null);\n const restoreSearchFocusRef = useRef(true);\n const abortRef = useRef<AbortController | null>(null);\n const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);\n const router = useRouter();\n const { isChatActive } = useContext(ChatContext);\n const { ask, close: closeChat, isOpen: isChatOpen } = useChat();\n\n const sectionLabels = useMemo(() => {\n const map: Record<string, string> = {};\n sections?.forEach((s) => {\n map[s.slug] = s.label;\n });\n return map;\n }, [sections]);\n\n const openSearch = useCallback(() => {\n const previousOverlayOpener = closeChat(false);\n closingRef.current = false;\n restoreSearchFocusRef.current = true;\n const activeElement = document.activeElement;\n const opener =\n previousOverlayOpener?.isConnected === true\n ? previousOverlayOpener\n : activeElement instanceof HTMLElement &&\n activeElement !== document.body\n ? activeElement\n : null;\n searchOpenerRef.current = opener;\n setReturnFocusTo(opener);\n isVisibleRef.current = true;\n setIsClosing(false);\n setIsVisible(true);\n }, [closeChat]);\n\n const closeSearch = useCallback(() => {\n closingRef.current = true;\n setIsClosing(true);\n if (abortRef.current) abortRef.current.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n }, []);\n\n const shouldRestoreSearchFocus = useCallback(\n () => restoreSearchFocusRef.current,\n [],\n );\n\n const handleCloseAnimationEnd = useCallback(() => {\n if (!closingRef.current) return;\n closingRef.current = false;\n isVisibleRef.current = false;\n setIsVisible(false);\n setIsClosing(false);\n setQuery(\"\");\n setActiveIndex(0);\n setFetched(null);\n searchOpenerRef.current = null;\n setReturnFocusTo(null);\n }, []);\n\n const closeSearchImmediately = useCallback((restoreFocus = true) => {\n if (!isVisibleRef.current) return null;\n restoreSearchFocusRef.current = restoreFocus;\n const opener = searchOpenerRef.current;\n searchOpenerRef.current = null;\n setReturnFocusTo(null);\n closingRef.current = false;\n isVisibleRef.current = false;\n if (abortRef.current) abortRef.current.abort();\n if (debounceRef.current) clearTimeout(debounceRef.current);\n const activeElement = document.activeElement;\n if (\n activeElement instanceof HTMLElement &&\n activeElement.closest(\"[data-search-dialog]\")\n ) {\n activeElement.blur();\n }\n setIsVisible(false);\n setIsClosing(false);\n setQuery(\"\");\n setActiveIndex(0);\n setFetched(null);\n return opener;\n }, []);\n\n // Only one overlay at a time: the chat panel opening (launcher, Cmd+I, or\n // `ask`) dismisses the search modal without restoring focus, since focus\n // has already moved into the chat composer.\n useEffect(() => {\n if (isChatOpen) closeSearchImmediately(false);\n }, [isChatOpen, closeSearchImmediately]);\n\n const trimmedQuery = query.trim();\n const contentResults =\n trimmedQuery.length >= 2 && fetched?.q === trimmedQuery\n ? fetched.results\n : EMPTY_RESULTS;\n const isSearching = trimmedQuery.length >= 2 && fetched?.q !== trimmedQuery;\n\n // Instant title/description filtering\n const titleFiltered = useMemo(() => {\n if (!query.trim()) return pages;\n const q = query.toLowerCase();\n return pages.filter(\n (p) =>\n p.title.toLowerCase().includes(q) ||\n p.description?.toLowerCase().includes(q),\n );\n }, [pages, query]);\n\n // Merge title matches with content matches\n const merged = useMemo<MergedResult[]>(() => {\n if (!query.trim()) {\n return pages.map((p) => ({ page: p }));\n }\n\n const titleMatchSlugs = new Set(titleFiltered.map((p) => p.slug));\n const titleMatches: MergedResult[] = titleFiltered.map((p) => {\n const hit = contentResults.find((cr) => cr.slug === p.slug);\n return { page: p, snippet: hit?.snippet };\n });\n\n const pageMap = new Map(pages.map((p) => [p.slug, p]));\n const contentOnly: MergedResult[] = [];\n for (const cr of contentResults) {\n if (!titleMatchSlugs.has(cr.slug)) {\n const page = pageMap.get(cr.slug);\n if (page) {\n contentOnly.push({ page, snippet: cr.snippet });\n }\n }\n }\n\n return [...titleMatches, ...contentOnly];\n }, [pages, query, titleFiltered, contentResults]);\n\n // Debounced content search. State updates happen only inside the timeout's\n // async callback; short queries need no reset because the derived values\n // above ignore results whose query no longer matches.\n useEffect(() => {\n if (debounceRef.current) clearTimeout(debounceRef.current);\n if (abortRef.current) abortRef.current.abort();\n\n const q = query.trim();\n if (q.length < 2) return;\n\n debounceRef.current = setTimeout(async () => {\n const controller = new AbortController();\n abortRef.current = controller;\n try {\n const res = await fetch(\n `/api/search?q=${encodeURIComponent(q)}&limit=15`,\n { signal: controller.signal },\n );\n if (!res.ok) throw new Error(\"Search failed\");\n const data = await res.json();\n setFetched({ q, results: data.results ?? [] });\n } catch (err: unknown) {\n if (err instanceof DOMException && err.name === \"AbortError\") return;\n setFetched({ q, results: [] });\n }\n }, 300);\n\n return () => {\n if (debounceRef.current) clearTimeout(debounceRef.current);\n };\n }, [query]);\n\n const navigate = useCallback(\n (\n slug: string,\n modifiers?: { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean },\n ) => {\n const url = `/${slug}`;\n\n // Shift+Enter / Shift+Click: open in a separate browser window. Window\n // features (dimensions) are what make the browser spawn a window instead\n // of a tab; noopener/noreferrer keep the new window from reaching back\n // into this one via window.opener.\n if (modifiers?.shiftKey) {\n const width = Math.min(1024, window.screen.availWidth);\n const height = Math.min(800, window.screen.availHeight);\n const left = Math.round((window.screen.availWidth - width) / 2);\n const top = Math.round((window.screen.availHeight - height) / 2);\n window.open(\n url,\n \"_blank\",\n `popup=yes,noopener,noreferrer,width=${width},height=${height},left=${left},top=${top}`,\n );\n return;\n }\n\n // Cmd+Enter / Ctrl+Enter / Cmd+Click: open in a new background tab. With\n // no dimension features the browser keeps this as a tab.\n if (modifiers?.metaKey || modifiers?.ctrlKey) {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n return;\n }\n\n // Plain Enter / Click: navigate in place within the app.\n closeSearch();\n router.push(url);\n },\n [closeSearch, router],\n );\n\n // Hand the current query to the AI assistant, then dismiss the search modal.\n // `ask` opens the chat and either submits the question or (if a response is\n // already streaming) pre-fills it, ready to send.\n const askAssistantWithQuery = useCallback(() => {\n const q = query.trim();\n if (!q) return;\n const opener = closeSearchImmediately(false);\n ask(q, opener);\n }, [query, ask, closeSearchImmediately]);\n\n // Global Cmd+K / Ctrl+K listener\n useEffect(() => {\n function handleKeyDown(e: KeyboardEvent) {\n if ((e.metaKey || e.ctrlKey) && e.key === \"k\") {\n e.preventDefault();\n if (isVisibleRef.current) {\n closeSearch();\n } else {\n openSearch();\n }\n }\n }\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => document.removeEventListener(\"keydown\", handleKeyDown);\n }, [closeSearch, openSearch]);\n\n // Active-row scrolling now lives in SearchModalContent's layout effect,\n // alongside the highlight measurement, so highlight + scroll update together\n // before paint (no flicker) and stay in sync on query changes.\n\n function handleKeyDown(e: React.KeyboardEvent) {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n setActiveIndex((i) => (i < merged.length - 1 ? i + 1 : 0));\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n setActiveIndex((i) => (i > 0 ? i - 1 : merged.length - 1));\n } else if (e.key === \"Enter\") {\n e.preventDefault();\n // Option/Alt+Enter is reserved for handing the query to the AI assistant.\n if (e.altKey) {\n if (isChatActive) askAssistantWithQuery();\n return;\n }\n if (merged[activeIndex]) {\n navigate(merged[activeIndex].page.slug, e);\n }\n } else if (e.key === \"Escape\") {\n closeSearch();\n }\n }\n\n return (\n <SearchContext.Provider value={{ openSearch }}>\n {children}\n {isVisible && (\n <SearchModalContent\n isClosing={isClosing}\n closeSearch={closeSearch}\n onCloseAnimationEnd={handleCloseAnimationEnd}\n query={query}\n setQuery={setQuery}\n activeIndex={activeIndex}\n setActiveIndex={setActiveIndex}\n resultsRef={resultsRef}\n onKeyDown={handleKeyDown}\n merged={merged}\n sectionLabels={sectionLabels}\n isSearching={isSearching}\n navigate={navigate}\n canAskAssistant={isChatActive}\n onAskAssistant={askAssistantWithQuery}\n shouldRestoreFocus={shouldRestoreSearchFocus}\n returnFocusTo={returnFocusTo}\n />\n )}\n </SearchContext.Provider>\n );\n}\n\nexport {\n SearchProvider,\n SearchContext,\n StyledKbd as SearchKbd,\n StyledSearchButton,\n};\n";
|
|
@@ -77,7 +77,7 @@ const StyledSearchButton = styled.button<{ theme: Theme }>\`
|
|
|
77
77
|
background: \${({ theme }) => theme.colors.light};
|
|
78
78
|
color: \${({ theme }) => theme.colors.primary};
|
|
79
79
|
border-radius: \${({ theme }) => theme.spacing.radius.xs};
|
|
80
|
-
padding: 0
|
|
80
|
+
padding: 0 8px;
|
|
81
81
|
font-family: inherit;
|
|
82
82
|
cursor: pointer;
|
|
83
83
|
|
|
@@ -85,6 +85,10 @@ const StyledSearchButton = styled.button<{ theme: Theme }>\`
|
|
|
85
85
|
color: inherit;
|
|
86
86
|
min-width: 14px;
|
|
87
87
|
}
|
|
88
|
+
|
|
89
|
+
\${mq("lg")} {
|
|
90
|
+
padding: 0 4px 0 8px;
|
|
91
|
+
}
|
|
88
92
|
\`;
|
|
89
93
|
|
|
90
94
|
function SearchProvider({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const headerTemplate = "\"use client\";\nimport React from \"react\";\nimport { useCallback, useContext, useRef, useState } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport Link from \"next/link\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { ChatLauncher, useOnClickOutside } from \"cherry-styled-components\";\nimport { Search } from \"lucide-react\";\nimport { Logo } from \"@/components/layout/Pictograms\";\nimport { ChatContext } from \"@/components/Chat\";\nimport {\n SearchContext,\n SearchKbd,\n StyledSearchButton,\n} from \"@/components/SearchDocs\";\nimport themeJson from \"@/theme.json\";\n\nconst customThemeJson = themeJson as typeof themeJson & {\n logo?: { dark: string; light: string };\n};\n\nconst StyledHeader = styled.header<{
|
|
1
|
+
export declare const headerTemplate = "\"use client\";\nimport React from \"react\";\nimport { useCallback, useContext, useEffect, useRef, useState } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport Link from \"next/link\";\nimport { mq, Theme } from \"@/app/theme\";\nimport { ChatLauncher, useOnClickOutside } from \"cherry-styled-components\";\nimport { Search } from \"lucide-react\";\nimport { Logo } from \"@/components/layout/Pictograms\";\nimport { ChatContext } from \"@/components/Chat\";\nimport {\n SearchContext,\n SearchKbd,\n StyledSearchButton,\n} from \"@/components/SearchDocs\";\nimport themeJson from \"@/theme.json\";\n\nconst customThemeJson = themeJson as typeof themeJson & {\n logo?: { dark: string; light: string };\n};\n\nconst StyledHeader = styled.header<{\n theme: Theme;\n $hasChildren: boolean;\n $pinned: boolean;\n}>`\n /* In normal flow at the top of the page, fixed only once the page scrolls.\n iOS Safari refuses to color its toolbar from the theme-color meta while\n a sticky or fixed element touches the top edge - whatever that element's\n background (transparent, frosted, or opaque; the Doccupine platform\n site's header is position: relative on its app pages for the same\n reason). At scroll position zero an in-flow header occupies exactly the\n place a sticky one would, so the swap is invisible; while scrolled, the\n toolbar is collapsed anyway. StyledHeaderShell holds the header's\n measured height while it is fixed, so pinning never shifts the page. */\n position: relative;\n top: 0;\n margin: 0;\n z-index: 1000;\n width: 100%;\n border-bottom: solid 1px ${({ theme }) => theme.colors.grayLight};\n\n ${({ $pinned }) =>\n $pinned &&\n css`\n position: fixed;\n left: 0;\n `}\n\n ${({ $hasChildren }) =>\n !$hasChildren &&\n css`\n ${mq(\"lg\")} {\n padding-bottom: 16px;\n padding-top: 16px;\n }\n `}\n\n &::before,\n &::after {\n display: block;\n content: \"\";\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n background: ${({ theme }) => theme.colors.light};\n z-index: -2;\n }\n\n &::after {\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 5%, transparent)`};\n z-index: -1;\n }\n\n & .logo {\n display: flex;\n min-width: max-content;\n\n & svg,\n & img {\n margin: auto;\n height: auto;\n width: fit-content;\n min-width: fit-content;\n max-width: 182px;\n max-height: 30px;\n\n & [fill]:not(.ignore-fill) {\n fill: ${({ theme }) => theme.colors.primary};\n }\n }\n }\n`;\n\n/**\n * In-flow placeholder that owns the header's space. While the header is\n * pinned (position: fixed, out of flow), the shell keeps the header's\n * measured height so pinning never shifts the page; at the top of the page\n * it collapses to its content.\n */\nconst StyledHeaderShell = styled.div<{ $pinned: boolean; $height: number }>`\n ${({ $pinned, $height }) =>\n $pinned &&\n $height > 0 &&\n css`\n height: ${$height}px;\n `}\n`;\n\nconst StyledHeaderInner = styled.div<{ $hasChildren: boolean }>`\n display: flex;\n align-items: center;\n justify-content: space-between;\n flex-wrap: wrap;\n padding: 16px 0 0 20px;\n\n ${({ $hasChildren }) =>\n !$hasChildren &&\n css`\n padding-bottom: 16px;\n `}\n\n ${mq(\"lg\")} {\n flex-wrap: nowrap;\n padding: 0 20px;\n }\n`;\n\nconst StyledLeftWrapper = styled.div`\n display: flex;\n align-items: center;\n gap: 10px;\n min-width: fit-content;\n padding-right: 20px;\n\n ${mq(\"lg\")} {\n padding-right: 0;\n }\n`;\n\ninterface HeaderProps {\n children?: React.ReactNode;\n}\n\nfunction Header({ children }: HeaderProps) {\n const [isOptionActive, setIsOptionActive] = useState(false);\n const [isLangActive, setIsLangActive] = useState(false);\n const [isPinned, setIsPinned] = useState(false);\n const [headerHeight, setHeaderHeight] = useState(0);\n const headerRef = useRef<HTMLElement>(null);\n\n useEffect(() => {\n const onScroll = () => {\n if (headerRef.current) {\n setHeaderHeight(headerRef.current.getBoundingClientRect().height);\n }\n setIsPinned(window.scrollY > 0);\n };\n onScroll();\n window.addEventListener(\"scroll\", onScroll, { passive: true });\n window.addEventListener(\"resize\", onScroll);\n return () => {\n window.removeEventListener(\"scroll\", onScroll);\n window.removeEventListener(\"resize\", onScroll);\n };\n }, []);\n\n const wrapperRef = useRef<HTMLSpanElement>(null);\n const elmRef = useRef<HTMLDivElement>(null);\n const langRef = useRef<HTMLSpanElement>(null);\n const closeMenu = useCallback(() => {\n setIsOptionActive(false);\n setIsLangActive(false);\n }, []);\n\n useOnClickOutside(\n [elmRef, wrapperRef],\n isOptionActive ? closeMenu : () => {},\n );\n useOnClickOutside([langRef, wrapperRef], isLangActive ? closeMenu : () => {});\n const { isChatActive } = useContext(ChatContext);\n const { openSearch } = useContext(SearchContext);\n\n return (\n <StyledHeaderShell $pinned={isPinned} $height={headerHeight}>\n <StyledHeader\n $hasChildren={children ? true : false}\n $pinned={isPinned}\n id=\"header\"\n ref={headerRef}\n >\n <StyledHeaderInner $hasChildren={children ? true : false}>\n <Link href=\"/\" className=\"logo\" aria-label=\"Logo\">\n {customThemeJson.logo ? (\n <>\n {/* Both logos render; .light-only and .dark-only classes in\n GlobalStyles hide the inactive one based on the \"dark\" class\n on <html>. Avoids a JS-driven swap so no flash on first load. */}\n {/* eslint-disable-next-line @next/next/no-img-element */}\n <img\n className=\"light-only\"\n src={customThemeJson.logo.light}\n alt=\"Logo\"\n width=\"100\"\n height=\"100\"\n />\n {/* eslint-disable-next-line @next/next/no-img-element */}\n <img\n className=\"dark-only\"\n src={customThemeJson.logo.dark}\n alt=\"Logo\"\n width=\"100\"\n height=\"100\"\n />\n </>\n ) : (\n <Logo />\n )}\n </Link>\n {children}\n <StyledLeftWrapper>\n <StyledSearchButton onClick={openSearch} aria-label=\"Search docs\">\n <Search size={14} />\n <SearchKbd>⌘K</SearchKbd>\n </StyledSearchButton>\n {isChatActive && <ChatLauncher $glow />}\n </StyledLeftWrapper>\n </StyledHeaderInner>\n </StyledHeader>\n </StyledHeaderShell>\n );\n}\n\nexport { Header };\n";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export const headerTemplate = `"use client";
|
|
2
2
|
import React from "react";
|
|
3
|
-
import { useCallback, useContext, useRef, useState } from "react";
|
|
3
|
+
import { useCallback, useContext, useEffect, useRef, useState } from "react";
|
|
4
4
|
import styled, { css } from "styled-components";
|
|
5
5
|
import Link from "next/link";
|
|
6
6
|
import { mq, Theme } from "@/app/theme";
|
|
@@ -19,14 +19,34 @@ const customThemeJson = themeJson as typeof themeJson & {
|
|
|
19
19
|
logo?: { dark: string; light: string };
|
|
20
20
|
};
|
|
21
21
|
|
|
22
|
-
const StyledHeader = styled.header<{
|
|
23
|
-
|
|
22
|
+
const StyledHeader = styled.header<{
|
|
23
|
+
theme: Theme;
|
|
24
|
+
$hasChildren: boolean;
|
|
25
|
+
$pinned: boolean;
|
|
26
|
+
}>\`
|
|
27
|
+
/* In normal flow at the top of the page, fixed only once the page scrolls.
|
|
28
|
+
iOS Safari refuses to color its toolbar from the theme-color meta while
|
|
29
|
+
a sticky or fixed element touches the top edge - whatever that element's
|
|
30
|
+
background (transparent, frosted, or opaque; the Doccupine platform
|
|
31
|
+
site's header is position: relative on its app pages for the same
|
|
32
|
+
reason). At scroll position zero an in-flow header occupies exactly the
|
|
33
|
+
place a sticky one would, so the swap is invisible; while scrolled, the
|
|
34
|
+
toolbar is collapsed anyway. StyledHeaderShell holds the header's
|
|
35
|
+
measured height while it is fixed, so pinning never shifts the page. */
|
|
36
|
+
position: relative;
|
|
24
37
|
top: 0;
|
|
25
38
|
margin: 0;
|
|
26
39
|
z-index: 1000;
|
|
27
40
|
width: 100%;
|
|
28
41
|
border-bottom: solid 1px \${({ theme }) => theme.colors.grayLight};
|
|
29
42
|
|
|
43
|
+
\${({ $pinned }) =>
|
|
44
|
+
$pinned &&
|
|
45
|
+
css\`
|
|
46
|
+
position: fixed;
|
|
47
|
+
left: 0;
|
|
48
|
+
\`}
|
|
49
|
+
|
|
30
50
|
\${({ $hasChildren }) =>
|
|
31
51
|
!$hasChildren &&
|
|
32
52
|
css\`
|
|
@@ -76,6 +96,21 @@ const StyledHeader = styled.header<{ theme: Theme; $hasChildren: boolean }>\`
|
|
|
76
96
|
}
|
|
77
97
|
\`;
|
|
78
98
|
|
|
99
|
+
/**
|
|
100
|
+
* In-flow placeholder that owns the header's space. While the header is
|
|
101
|
+
* pinned (position: fixed, out of flow), the shell keeps the header's
|
|
102
|
+
* measured height so pinning never shifts the page; at the top of the page
|
|
103
|
+
* it collapses to its content.
|
|
104
|
+
*/
|
|
105
|
+
const StyledHeaderShell = styled.div<{ $pinned: boolean; $height: number }>\`
|
|
106
|
+
\${({ $pinned, $height }) =>
|
|
107
|
+
$pinned &&
|
|
108
|
+
$height > 0 &&
|
|
109
|
+
css\`
|
|
110
|
+
height: \${$height}px;
|
|
111
|
+
\`}
|
|
112
|
+
\`;
|
|
113
|
+
|
|
79
114
|
const StyledHeaderInner = styled.div<{ $hasChildren: boolean }>\`
|
|
80
115
|
display: flex;
|
|
81
116
|
align-items: center;
|
|
@@ -114,6 +149,25 @@ interface HeaderProps {
|
|
|
114
149
|
function Header({ children }: HeaderProps) {
|
|
115
150
|
const [isOptionActive, setIsOptionActive] = useState(false);
|
|
116
151
|
const [isLangActive, setIsLangActive] = useState(false);
|
|
152
|
+
const [isPinned, setIsPinned] = useState(false);
|
|
153
|
+
const [headerHeight, setHeaderHeight] = useState(0);
|
|
154
|
+
const headerRef = useRef<HTMLElement>(null);
|
|
155
|
+
|
|
156
|
+
useEffect(() => {
|
|
157
|
+
const onScroll = () => {
|
|
158
|
+
if (headerRef.current) {
|
|
159
|
+
setHeaderHeight(headerRef.current.getBoundingClientRect().height);
|
|
160
|
+
}
|
|
161
|
+
setIsPinned(window.scrollY > 0);
|
|
162
|
+
};
|
|
163
|
+
onScroll();
|
|
164
|
+
window.addEventListener("scroll", onScroll, { passive: true });
|
|
165
|
+
window.addEventListener("resize", onScroll);
|
|
166
|
+
return () => {
|
|
167
|
+
window.removeEventListener("scroll", onScroll);
|
|
168
|
+
window.removeEventListener("resize", onScroll);
|
|
169
|
+
};
|
|
170
|
+
}, []);
|
|
117
171
|
|
|
118
172
|
const wrapperRef = useRef<HTMLSpanElement>(null);
|
|
119
173
|
const elmRef = useRef<HTMLDivElement>(null);
|
|
@@ -132,45 +186,52 @@ function Header({ children }: HeaderProps) {
|
|
|
132
186
|
const { openSearch } = useContext(SearchContext);
|
|
133
187
|
|
|
134
188
|
return (
|
|
135
|
-
<
|
|
136
|
-
<
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
</
|
|
170
|
-
{
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
189
|
+
<StyledHeaderShell $pinned={isPinned} $height={headerHeight}>
|
|
190
|
+
<StyledHeader
|
|
191
|
+
$hasChildren={children ? true : false}
|
|
192
|
+
$pinned={isPinned}
|
|
193
|
+
id="header"
|
|
194
|
+
ref={headerRef}
|
|
195
|
+
>
|
|
196
|
+
<StyledHeaderInner $hasChildren={children ? true : false}>
|
|
197
|
+
<Link href="/" className="logo" aria-label="Logo">
|
|
198
|
+
{customThemeJson.logo ? (
|
|
199
|
+
<>
|
|
200
|
+
{/* Both logos render; .light-only and .dark-only classes in
|
|
201
|
+
GlobalStyles hide the inactive one based on the "dark" class
|
|
202
|
+
on <html>. Avoids a JS-driven swap so no flash on first load. */}
|
|
203
|
+
{/* eslint-disable-next-line @next/next/no-img-element */}
|
|
204
|
+
<img
|
|
205
|
+
className="light-only"
|
|
206
|
+
src={customThemeJson.logo.light}
|
|
207
|
+
alt="Logo"
|
|
208
|
+
width="100"
|
|
209
|
+
height="100"
|
|
210
|
+
/>
|
|
211
|
+
{/* eslint-disable-next-line @next/next/no-img-element */}
|
|
212
|
+
<img
|
|
213
|
+
className="dark-only"
|
|
214
|
+
src={customThemeJson.logo.dark}
|
|
215
|
+
alt="Logo"
|
|
216
|
+
width="100"
|
|
217
|
+
height="100"
|
|
218
|
+
/>
|
|
219
|
+
</>
|
|
220
|
+
) : (
|
|
221
|
+
<Logo />
|
|
222
|
+
)}
|
|
223
|
+
</Link>
|
|
224
|
+
{children}
|
|
225
|
+
<StyledLeftWrapper>
|
|
226
|
+
<StyledSearchButton onClick={openSearch} aria-label="Search docs">
|
|
227
|
+
<Search size={14} />
|
|
228
|
+
<SearchKbd>⌘K</SearchKbd>
|
|
229
|
+
</StyledSearchButton>
|
|
230
|
+
{isChatActive && <ChatLauncher $glow />}
|
|
231
|
+
</StyledLeftWrapper>
|
|
232
|
+
</StyledHeaderInner>
|
|
233
|
+
</StyledHeader>
|
|
234
|
+
</StyledHeaderShell>
|
|
174
235
|
);
|
|
175
236
|
}
|
|
176
237
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const globalsMdxTemplate = "---\ntitle: \"Globals\"\ndescription: \"Configure global settings for your documentation.\"\ndate: \"2026-02-19\"\nupdated: \"2026-08-04\"\ncategory: \"Configuration\"\ncategoryOrder: 2\ncategoryIcon: \"settings\"\norder: 1\n---\n# Global Configuration\n\nUse a `config.json` file to define project\u2011wide metadata for your documentation site. These values are applied to every generated page unless a page overrides them in its own frontmatter.\n\n## config.json\n\nPlace a `config.json` at your project root (the same directory where you execute `npx doccupine`) to define global metadata for your documentation site.\n\n```json\n{\n \"name\": \"Doccupine\",\n \"description\": \"Doccupine is a free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.\",\n \"icon\": \"/icon.png\",\n \"image\": \"https://docs.doccupine.com/preview.png\",\n \"url\": \"https://docs.doccupine.com\"\n}\n```\n\n## Fields\n\nAll fields are optional. Doccupine uses sensible defaults when a field is not set.\n\n- **name**: The primary name of your documentation website. Displayed in the site title and used in various UI elements.\n- **description**: A concise summary of your project, used in site metadata (e.g., HTML meta description) and social previews when not overridden.\n- **icon**: The favicon for your site. You can provide a full URL or a relative path to an asset in your project. Dropping an `icon.png` file at the project root (see [Icon files](#icon-files)) takes precedence over this field.\n- **image**: The Open Graph image used when links to your docs are shared on social platforms. Accepts a full URL or a relative path.\n- **url**: The public URL of your deployed site. Used as the base URL for `sitemap.xml` and `robots.txt`. When omitted, `/sitemap.xml` is served but empty and `robots.txt` omits its sitemap reference. Can be overridden at deploy time with the `NEXT_PUBLIC_SITE_URL` environment variable.\n\n## Icon files\n\nInstead of pointing `icon` at a URL, you can drop conventional icon files next to `config.json` at your project root:\n\n| File | Purpose |\n| ----------------- | ---------------------------------------------------------- |\n| `icon.png` | Favicon shown in browser tabs |\n| `icon-dark.png` | Favicon variant for dark interfaces (requires `icon.png`) |\n| `apple-icon.png` | Home-screen icon for iOS devices |\n\nDoccupine copies the files into the generated site and wires them into every page's metadata. Each icon URL carries a content hash, so replacing an icon busts browser caches automatically. The light and dark favicons are selected by the operating system's color scheme, because browser tab chrome follows the OS theme rather than the site's theme toggle.\n\nPrecedence: a page's frontmatter `icon` wins for that page, then root icon files, then `icon` in `config.json`, then the Doccupine default.\n\n<Callout type=\"warning\">\n A root icon file and a file with the same name in your `public/` directory would publish the same URL, so Doccupine reports a validation error instead of letting one silently overwrite the other.\n</Callout>\n\n<Callout type=\"note\">\n Some legacy tools request `/favicon.ico` directly instead of reading the page's icon links. If you need that path covered, place a `favicon.ico` in your `public/` directory and it is copied through as-is.\n</Callout>\n\n## Per-page overrides\n\nAny page can override global values by defining the matching key in its frontmatter. When present, the page's value takes precedence over `config.json` for that page only.\n\n| Frontmatter field | Overrides | Effect |\n| ----------------- | ------------- | ------------------------------------------------------------------- |\n| **title** | - | Page title in metadata and Open Graph |\n| **description** | `description` | Meta description and Open Graph description |\n| **name** | `name` | Site name shown in the title suffix (e.g. \"Page - My Docs\") |\n| **icon** | `icon` | Favicon for this page |\n| **image** | `image` | Open Graph preview image |\n| **date** | - | Publication date, used for JSON-LD `datePublished` |\n| **updated** | - | Last-modified date, used for JSON-LD `dateModified` and the sitemap |\n| **section** | - | Assigns the page to a [section](/sections) |\n| **sectionOrder** | - | Controls section position in the tab bar |\n| **sectionLabel** | - | Renames the default \"Docs\" tab (use on `index.mdx`) |\n\n<Callout type=\"note\">\n If a key is not specified in a page's frontmatter, Doccupine falls back to the corresponding value in `config.json`.\n</Callout>\n\nExample frontmatter in an `.mdx` file:\n\n```text\n---\ntitle: \"My Feature\"\ndescription: \"A focused description just for this page.\"\nname: \"My Product Docs\"\nicon: \"/custom-favicon.png\"\nimage: \"/custom-preview.png\"\ndate: \"2026-02-19\"\nupdated: \"2026-03-04\"\ncategory: \"Guides\"\n---\n```";
|
|
1
|
+
export declare const globalsMdxTemplate = "---\ntitle: \"Globals\"\ndescription: \"Configure global settings for your documentation.\"\ndate: \"2026-02-19\"\nupdated: \"2026-08-04\"\ncategory: \"Configuration\"\ncategoryOrder: 2\ncategoryIcon: \"settings\"\norder: 1\n---\n# Global Configuration\n\nUse a `config.json` file to define project\u2011wide metadata for your documentation site. These values are applied to every generated page unless a page overrides them in its own frontmatter.\n\n## config.json\n\nPlace a `config.json` at your project root (the same directory where you execute `npx doccupine`) to define global metadata for your documentation site.\n\n```json\n{\n \"name\": \"Doccupine\",\n \"description\": \"Doccupine is a free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.\",\n \"icon\": \"/icon.png\",\n \"image\": \"https://docs.doccupine.com/preview.png\",\n \"url\": \"https://docs.doccupine.com\"\n}\n```\n\n## Fields\n\nAll fields are optional. Doccupine uses sensible defaults when a field is not set.\n\n- **name**: The primary name of your documentation website. Displayed in the site title and used in various UI elements.\n- **description**: A concise summary of your project, used in site metadata (e.g., HTML meta description) and social previews when not overridden.\n- **icon**: The favicon for your site. You can provide a full URL or a relative path to an asset in your project. Dropping an `icon.png` file at the project root (see [Icon files](#icon-files)) takes precedence over this field.\n- **image**: The Open Graph image used when links to your docs are shared on social platforms. Accepts a full URL or a relative path.\n- **url**: The public URL of your deployed site. Used as the base URL for `sitemap.xml` and `robots.txt`. When omitted, `/sitemap.xml` is served but empty and `robots.txt` omits its sitemap reference. Can be overridden at deploy time with the `NEXT_PUBLIC_SITE_URL` environment variable.\n\n## Icon files\n\nInstead of pointing `icon` at a URL, you can drop conventional icon files next to `config.json` at your project root:\n\n| File | Purpose |\n| ----------------- | ---------------------------------------------------------- |\n| `icon.png` | Favicon shown in browser tabs |\n| `icon-dark.png` | Favicon variant for dark interfaces (requires `icon.png`) |\n| `apple-icon.png` | Home-screen icon for iOS devices |\n\nDoccupine copies the files into the generated site and wires them into every page's metadata. Each icon URL carries a content hash, so replacing an icon busts browser caches automatically. The light and dark favicons are selected by the operating system's color scheme, because browser tab chrome follows the OS theme rather than the site's theme toggle.\n\nPrecedence: a page's frontmatter `icon` wins for that page, then root icon files, then `icon` in `config.json`, then the Doccupine default.\n\nThe generated site also serves a web app manifest at `/manifest.webmanifest`, linked from every page automatically. It carries your site's `name` and `description` from `config.json`, the light palette's `primary` as `theme_color`, and the root icon files as its icon entries, so browsers that install or pin the site pick up your branding.\n\n<Callout type=\"warning\">\n A root icon file and a file with the same name in your `public/` directory would publish the same URL, so Doccupine reports a validation error instead of letting one silently overwrite the other.\n</Callout>\n\n<Callout type=\"note\">\n Some legacy tools request `/favicon.ico` directly instead of reading the page's icon links. If you need that path covered, place a `favicon.ico` in your `public/` directory and it is copied through as-is.\n</Callout>\n\n## Per-page overrides\n\nAny page can override global values by defining the matching key in its frontmatter. When present, the page's value takes precedence over `config.json` for that page only.\n\n| Frontmatter field | Overrides | Effect |\n| ----------------- | ------------- | ------------------------------------------------------------------- |\n| **title** | - | Page title in metadata and Open Graph |\n| **description** | `description` | Meta description and Open Graph description |\n| **name** | `name` | Site name shown in the title suffix (e.g. \"Page - My Docs\") |\n| **icon** | `icon` | Favicon for this page |\n| **image** | `image` | Open Graph preview image |\n| **date** | - | Publication date, used for JSON-LD `datePublished` |\n| **updated** | - | Last-modified date, used for JSON-LD `dateModified` and the sitemap |\n| **section** | - | Assigns the page to a [section](/sections) |\n| **sectionOrder** | - | Controls section position in the tab bar |\n| **sectionLabel** | - | Renames the default \"Docs\" tab (use on `index.mdx`) |\n\n<Callout type=\"note\">\n If a key is not specified in a page's frontmatter, Doccupine falls back to the corresponding value in `config.json`.\n</Callout>\n\nExample frontmatter in an `.mdx` file:\n\n```text\n---\ntitle: \"My Feature\"\ndescription: \"A focused description just for this page.\"\nname: \"My Product Docs\"\nicon: \"/custom-favicon.png\"\nimage: \"/custom-preview.png\"\ndate: \"2026-02-19\"\nupdated: \"2026-03-04\"\ncategory: \"Guides\"\n---\n```";
|
|
@@ -51,6 +51,8 @@ Doccupine copies the files into the generated site and wires them into every pag
|
|
|
51
51
|
|
|
52
52
|
Precedence: a page's frontmatter \`icon\` wins for that page, then root icon files, then \`icon\` in \`config.json\`, then the Doccupine default.
|
|
53
53
|
|
|
54
|
+
The generated site also serves a web app manifest at \`/manifest.webmanifest\`, linked from every page automatically. It carries your site's \`name\` and \`description\` from \`config.json\`, the light palette's \`primary\` as \`theme_color\`, and the root icon files as its icon entries, so browsers that install or pin the site pick up your branding.
|
|
55
|
+
|
|
54
56
|
<Callout type="warning">
|
|
55
57
|
A root icon file and a file with the same name in your \`public/\` directory would publish the same URL, so Doccupine reports a validation error instead of letting one silently overwrite the other.
|
|
56
58
|
</Callout>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const iconsTemplate = "import type { Metadata } from \"next\";\nimport iconsData from \"@/icons.json\";\nimport { config } from \"@/utils/config\";\n\n// icons.json is written by the Doccupine CLI from icon files at the project\n// root (icon.png, icon-dark.png, apple-icon.png). Every URL carries a\n// content-hash query so a replaced icon busts browser caches.\ninterface IconManifest {\n icon?: string;\n iconDark?: string;\n appleIcon?: string;\n}\n\nconst icons = iconsData as IconManifest;\n\nconst fallbackIcon = config.icon || \"https://docs.doccupine.com/favicon.ico\";\n\n/** Single icon URL for JSON-LD logos and other one-value consumers. */\nexport const primaryIconUrl: string = icons.icon ?? fallbackIcon;\n\nfunction buildSiteIcons(): Metadata[\"icons\"] {\n if (!icons.icon && !icons.appleIcon) return fallbackIcon;\n const iconEntries: { url: string; media?: string }[] = [];\n if (icons.icon && icons.iconDark) {\n iconEntries.push({\n url: icons.icon,\n media: \"(prefers-color-scheme: light)\",\n });\n iconEntries.push({\n url: icons.iconDark,\n media: \"(prefers-color-scheme: dark)\",\n });\n } else if (icons.icon) {\n iconEntries.push({ url: icons.icon });\n }\n return {\n icon: iconEntries.length > 0 ? iconEntries : fallbackIcon,\n ...(icons.appleIcon ? { apple: icons.appleIcon } : {}),\n };\n}\n\nexport const siteIcons: Metadata[\"icons\"] = buildSiteIcons();\n";
|
|
1
|
+
export declare const iconsTemplate = "import type { Metadata } from \"next\";\nimport iconsData from \"@/icons.json\";\nimport { config } from \"@/utils/config\";\n\n// icons.json is written by the Doccupine CLI from icon files at the project\n// root (icon.png, icon-dark.png, apple-icon.png). Every URL carries a\n// content-hash query so a replaced icon busts browser caches.\ninterface IconManifest {\n icon?: string;\n iconDark?: string;\n appleIcon?: string;\n}\n\nconst icons = iconsData as IconManifest;\n\nconst fallbackIcon = config.icon || \"https://docs.doccupine.com/favicon.ico\";\n\n/** Single icon URL for JSON-LD logos and other one-value consumers. */\nexport const primaryIconUrl: string = icons.icon ?? fallbackIcon;\n\nfunction buildSiteIcons(): Metadata[\"icons\"] {\n if (!icons.icon && !icons.appleIcon) return fallbackIcon;\n const iconEntries: { url: string; media?: string }[] = [];\n if (icons.icon && icons.iconDark) {\n iconEntries.push({\n url: icons.icon,\n media: \"(prefers-color-scheme: light)\",\n });\n iconEntries.push({\n url: icons.iconDark,\n media: \"(prefers-color-scheme: dark)\",\n });\n } else if (icons.icon) {\n iconEntries.push({ url: icons.icon });\n }\n return {\n icon: iconEntries.length > 0 ? iconEntries : fallbackIcon,\n ...(icons.appleIcon ? { apple: icons.appleIcon } : {}),\n };\n}\n\nexport const siteIcons: Metadata[\"icons\"] = buildSiteIcons();\n\n/**\n * Icon entries for the web app manifest. Only the root icon files are\n * listed - their true pixel dimensions are unknown to the generator, so the\n * spec's \"any\" stands in - and a site without them gets a manifest without\n * icons rather than a guessed format.\n */\nexport const manifestIcons: { src: string; sizes: string; type: string }[] = [\n ...(icons.icon ? [{ src: icons.icon, sizes: \"any\", type: \"image/png\" }] : []),\n ...(icons.appleIcon\n ? [{ src: icons.appleIcon, sizes: \"any\", type: \"image/png\" }]\n : []),\n];\n";
|
|
@@ -41,4 +41,17 @@ function buildSiteIcons(): Metadata["icons"] {
|
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
export const siteIcons: Metadata["icons"] = buildSiteIcons();
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Icon entries for the web app manifest. Only the root icon files are
|
|
47
|
+
* listed - their true pixel dimensions are unknown to the generator, so the
|
|
48
|
+
* spec's "any" stands in - and a site without them gets a manifest without
|
|
49
|
+
* icons rather than a guessed format.
|
|
50
|
+
*/
|
|
51
|
+
export const manifestIcons: { src: string; sizes: string; type: string }[] = [
|
|
52
|
+
...(icons.icon ? [{ src: icons.icon, sizes: "any", type: "image/png" }] : []),
|
|
53
|
+
...(icons.appleIcon
|
|
54
|
+
? [{ src: icons.appleIcon, sizes: "any", type: "image/png" }]
|
|
55
|
+
: []),
|
|
56
|
+
];
|
|
44
57
|
`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "doccupine",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.152",
|
|
4
4
|
"description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|