@graphql-markdown/nuxt-theme 0.1.2 → 0.2.0

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 CHANGED
@@ -25,7 +25,10 @@ import { defineContentConfig, defineCollection } from "@nuxt/content";
25
25
 
26
26
  export default defineContentConfig({
27
27
  collections: {
28
- content: defineCollection({ type: "page", source: "api-reference/**/*.md" }),
28
+ content: defineCollection({
29
+ type: "page",
30
+ source: "api-reference/**/*.md",
31
+ }),
29
32
  },
30
33
  });
31
34
  ```
@@ -50,20 +53,20 @@ Everything here is config- or CSS-driven — no file copying, and every value ke
50
53
  ```ts
51
54
  export default defineAppConfig({
52
55
  gqlmd: {
53
- siteTitle: "GraphQL API", // SiteHeader's link label
54
- githubUrl: undefined, // set to show a GitHub button in the header; omitted, the button doesn't render
55
- shikiTheme: "github-dark", // Shiki theme for the code column
56
- baseURL: "api-reference", // must match content.config.ts's glob prefix and every createGenerateDocs call's baseURL
56
+ siteTitle: "GraphQL API", // SiteHeader's link label
57
+ githubUrl: undefined, // set to show a GitHub button in the header; omitted, the button doesn't render
58
+ shikiTheme: "github-dark", // Shiki theme for the code column
59
+ baseURL: "api-reference", // must match content.config.ts's glob prefix and every createGenerateDocs call's baseURL
57
60
  },
58
61
  });
59
62
  ```
60
63
 
61
- | Key | Default | Description |
62
- | --- | --- | --- |
63
- | `gqlmd.siteTitle` | `'GraphQL API'` | Text shown in the header's home link. |
64
- | `gqlmd.githubUrl` | `undefined` | Repository URL for the header's GitHub button. Unset, the button is omitted entirely rather than rendered disabled. |
65
- | `gqlmd.shikiTheme` | `'github-dark'` | [Shiki](https://shiki.style/) theme name used to highlight the schema/example code column. |
66
- | `gqlmd.baseURL` | `'api-reference'` | The shared route prefix navigation, search, and the landing page all resolve against. See "Multi-schema setups" below — this must agree with `content.config.ts`'s glob and every `createGenerateDocs` call's own `baseURL`. |
64
+ | Key | Default | Description |
65
+ | ------------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
66
+ | `gqlmd.siteTitle` | `'GraphQL API'` | Text shown in the header's home link. |
67
+ | `gqlmd.githubUrl` | `undefined` | Repository URL for the header's GitHub button. Unset, the button is omitted entirely rather than rendered disabled. |
68
+ | `gqlmd.shikiTheme` | `'github-dark'` | [Shiki](https://shiki.style/) theme name used to highlight the schema/example code column. |
69
+ | `gqlmd.baseURL` | `'api-reference'` | The shared route prefix navigation, search, and the landing page all resolve against. See "Multi-schema setups" below — this must agree with `content.config.ts`'s glob and every `createGenerateDocs` call's own `baseURL`. |
67
70
 
68
71
  Your own `app.config.ts` deep-merges over these — Nuxt's built-in behavior across `extends` layers, nothing this package does itself. You can also set `ui.colors.primary`/`ui.colors.neutral` (Nuxt UI's own keys) the same way.
69
72
 
@@ -71,15 +74,16 @@ Your own `app.config.ts` deep-merges over these — Nuxt's built-in behavior acr
71
74
 
72
75
  Defined in the layer's `main.css`, overridable from your own project's stylesheet (imported after the layer's, or targeting `:root` directly):
73
76
 
74
- | Property | Default | Controls |
75
- | --- | --- | --- |
76
- | `--gqlmd-sidebar-width` | `20rem` | Reference page sidebar width. |
77
- | `--gqlmd-badge-bg` / `--gqlmd-badge-text` | neutral-tinted | Default schema badge (`scalar`, `object`, `non-null`, …) colors. |
78
- | `--gqlmd-badge-deprecated-bg` / `--gqlmd-badge-deprecated-text` | warning-tinted | The `deprecated` badge specifically. |
79
- | `--gqlmd-callout-deprecated-bg` / `--gqlmd-callout-deprecated-border` | error-tinted | The deprecation notice callout. |
80
- | `--gqlmd-code-text` | `#e4e4e7` | The code column's text color (its background comes from Nuxt UI's own `bg-accented`, not a `--gqlmd-*` token). |
77
+ | Property | Default | Controls |
78
+ | --------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------- |
79
+ | `--gqlmd-sidebar-width` | `20rem` | Reference page sidebar width. |
80
+ | `--gqlmd-footer-height` | `3.5rem` | Sticky reference footer height; the sidebar and pinned code columns stop above it. |
81
+ | `--gqlmd-badge-bg` / `--gqlmd-badge-text` | neutral-tinted | Default schema badge (`scalar`, `object`, `non-null`, …) colors. |
82
+ | `--gqlmd-badge-deprecated-bg` / `--gqlmd-badge-deprecated-text` | warning-tinted | The `deprecated` badge specifically. |
83
+ | `--gqlmd-callout-deprecated-bg` / `--gqlmd-callout-deprecated-border` | error-tinted | The deprecation notice callout. |
84
+ | `--gqlmd-code-text` | `#e4e4e7` | The code column's text color (its background comes from Nuxt UI's own `bg-accented`, not a `--gqlmd-*` token). |
81
85
 
82
- These style the classes the default formatter emits (`gqlmd-mdx-badge-*`, `api-deprecation-callout`) directly in the generated markdown — they don't reach every page, though: `app/utils/api-document.ts` promotes badges and the deprecation callout into `UBadge`/`UAlert` Nuxt UI components before render on the reference page itself, so those two properties style the *generated markdown* as parsed content, while the reference page's own badges/callouts follow Nuxt UI's own `color`/`variant` styling instead. Both code paths exist because the raw classes still matter for anything that renders the markdown directly (search results, raw content queries).
86
+ These style the classes the default formatter emits (`gqlmd-mdx-badge-*`, `api-deprecation-callout`) directly in the generated markdown — they don't reach every page, though: `app/utils/api-document.ts` promotes badges and the deprecation callout into `UBadge`/`UAlert` Nuxt UI components before render on the reference page itself, so those two properties style the _generated markdown_ as parsed content, while the reference page's own badges/callouts follow Nuxt UI's own `color`/`variant` styling instead. Both code paths exist because the raw classes still matter for anything that renders the markdown directly (search results, raw content queries).
83
87
 
84
88
  ### `printTypeOptions`
85
89
 
@@ -87,6 +91,10 @@ These style the classes the default formatter emits (`gqlmd-mdx-badge-*`, `api-d
87
91
 
88
92
  `hierarchy` (`"api"` default, `"entity"`, `"flat"`) controls the generated folder structure — and this layer's navigation and landing-page grid adapt to it automatically. Under `"flat"`, where there's no folder to group by at all, every generated page's frontmatter carries a `kind` field (the GraphQL entity kind — `objects`, `scalars`, `queries`, `directives`, …), and the sidebar/landing grid group by that instead, so the site stays organized whichever `hierarchy` value you choose.
89
93
 
94
+ ### Example variables
95
+
96
+ A section titled exactly `Example Variables` (for example emitted by a consumer decorator for an `@exampleVariables` directive, as a `### Example Variables` heading followed by a ` ```json ` code block) is moved to the code column on operation pages and stacked under the `Example` query card, with its own copy button. It is not a card of its own — unless the operation has no (or an empty) `Example`, in which case it is shown as a standalone `Variables` card. On non-operation types it is dropped: variables only apply to operations.
97
+
90
98
  ### Single-page reference
91
99
 
92
100
  Set `printTypeOptions.hierarchy: "flat"` in your `generate-docs.ts` (a `@graphql-markdown/core` option — see the `hierarchy` paragraph above) and this layer automatically shows the entire API as one continuous page at the base route (`<baseURL>`, e.g. `/api-reference`) instead of the per-type catalog: every query, mutation, and type grouped into Queries / Mutations / Subscriptions / Types (only non-empty groups shown), with a sidebar of in-page anchor links — modeled on references like [Anvil's GraphQL API docs](https://www.useanvil.com/docs/api/graphql/reference/). There's no separate flag or route for this: it's detected automatically from the generated content (every page having no folder nesting), and it replaces the multi-page catalog entirely rather than adding an alternative to it. Any direct link to an old per-type page (e.g. `<baseURL>/user`) still resolves — it redirects to that entry's anchor on the single page (`<baseURL>#<kind>-<slug>`) instead of 404ing.
@@ -95,6 +103,10 @@ Under `"api"`/`"entity"` hierarchy, nothing changes — you still get the per-ty
95
103
 
96
104
  This view isn't meant to scale indefinitely: every entry's definition and examples are Shiki-highlighted up front, and every entry hydrates its own copy-button state, so a schema with hundreds of types renders as hundreds of small interactive islands on one page. For a very large schema, prefer `"api"` or `"entity"` hierarchy instead of `"flat"`.
97
105
 
106
+ ### Homepage
107
+
108
+ `createGenerateDocs({ homepage })` accepts the path of a markdown template (or `false` to disable the homepage). Its frontmatter `title` / `description` set the page title and SEO metadata, and its body renders as the intro above the reference in both views; the sidebar's header link returns to it. Whatever the file is named, it is stored as `generated.md` in the generated content, which is how the theme finds it. GraphQL-Markdown replaces the `##baseURL##` and `##generated-date-time##` placeholders in the template.
109
+
98
110
  ## Customize by swizzling
99
111
 
100
112
  For changes config and CSS can't reach — different markup, different components entirely — eject a file into your own project with:
@@ -107,17 +119,17 @@ npx gqlmd-swizzle --component SiteHeader --force # overwrite without prompting
107
119
  npx gqlmd-swizzle --check # warn about swizzled files older than the installed layer version
108
120
  ```
109
121
 
110
- | id | Description |
111
- | --- | --- |
112
- | `SiteHeader` | Top navigation bar. |
113
- | `SiteFooter` | Bottom attribution bar. |
114
- | `SchemaCodeCard` | Highlighted code panel (schema definitions and examples). |
115
- | `ApiOverviewGrid` | Card grid for displaying API reference overview and namespace sections. |
116
- | `ApiNamespaceLanding` | Header and grid for API reference landing pages and namespace chooser. |
117
- | `ApiDocumentContent` | Document content with collapsible sections for API reference pages. |
118
- | `ApiCodeColumn` | Code column sidebar with highlighted schema definitions and examples. |
119
- | `ReferenceLayout` | Sidebar + header chrome around the reference page. |
120
- | `ReferencePage` | The two-column reference page itself. |
122
+ | id | Description |
123
+ | --------------------- | ----------------------------------------------------------------------- |
124
+ | `SiteHeader` | Top navigation bar. |
125
+ | `SiteFooter` | Bottom attribution bar. |
126
+ | `SchemaCodeCard` | Highlighted code panel (schema definitions and examples). |
127
+ | `ApiOverviewGrid` | Card grid for displaying API reference overview and namespace sections. |
128
+ | `ApiNamespaceLanding` | Header and grid for API reference landing pages and namespace chooser. |
129
+ | `ApiDocumentContent` | Document content with collapsible sections for API reference pages. |
130
+ | `ApiCodeColumn` | Code column sidebar with highlighted schema definitions and examples. |
131
+ | `ReferenceLayout` | Sidebar + header chrome around the reference page. |
132
+ | `ReferencePage` | The two-column reference page itself. |
121
133
 
122
134
  A swizzled file is copied into your project at the same relative path (Nuxt's own layer file-resolution then picks it up automatically — no config needed) and stamped with a comment recording the layer version it came from:
123
135
 
@@ -168,11 +180,11 @@ back to a "choose a namespace" page listing every top-level section.
168
180
  **These three settings are independent by design, not auto-synced — keep
169
181
  them in agreement yourself:**
170
182
 
171
- | Setting | Where | Purpose |
172
- | --- | --- | --- |
173
- | `createGenerateDocs({ baseURL })` | `generate-docs.ts`, once per schema | Where that schema's files get written. |
174
- | `gqlmd.baseURL` | `app.config.ts` | The shared prefix the UI resolves navigation/search/landing against. |
175
- | `source` glob prefix | `content.config.ts` | What Nuxt Content actually indexes. |
183
+ | Setting | Where | Purpose |
184
+ | --------------------------------- | ----------------------------------- | -------------------------------------------------------------------- |
185
+ | `createGenerateDocs({ baseURL })` | `generate-docs.ts`, once per schema | Where that schema's files get written. |
186
+ | `gqlmd.baseURL` | `app.config.ts` | The shared prefix the UI resolves navigation/search/landing against. |
187
+ | `source` glob prefix | `content.config.ts` | What Nuxt Content actually indexes. |
176
188
 
177
189
  They can't be synced automatically: `content.config.ts`'s glob is evaluated
178
190
  statically by Nuxt Content, in a context neither the build-time generator nor
@@ -186,7 +198,7 @@ set it to, and `content.config.ts`'s glob prefix needs to match.
186
198
  Two things remain load-bearing assumptions rather than options, by design for now:
187
199
 
188
200
  - **`content.config.ts` must exist in your own project**, not just the layer — Nuxt Content scopes each layer's own `content.config.ts` to that layer's directory, so a collection declared only in the layer would never see files your project generates. Copy the snippet under "Quick start" above.
189
- - **The reference page's code-column parsing (`app/utils/api-document.ts`) assumes graphql-markdown's default section/heading structure.** Custom `decorators`/`customSections` with unusual `position` values can render into the wrong column or go missing from it.
201
+ - **The reference page's code-column parsing (`app/utils/api-document.ts`) assumes graphql-markdown's default section/heading structure.** Custom `decorators`/`customSections` with unusual `position` values can render into the wrong column or go missing from it. The parsing relies on exact section titles (`Example`, `Example Response`, `Example Variables`).
190
202
 
191
203
  ## Design notes
192
204
 
@@ -3,6 +3,8 @@
3
3
 
4
4
  :root {
5
5
  --gqlmd-sidebar-width: 20rem;
6
+ /* Height of the sticky reference footer; the sidebar and pinned code columns stop above it. */
7
+ --gqlmd-footer-height: 3.5rem;
6
8
  --gqlmd-badge-bg: color-mix(
7
9
  in oklch,
8
10
  var(--ui-color-neutral-500) 15%,
@@ -1,42 +1,39 @@
1
1
  <template>
2
2
  <section
3
- class="space-y-6 bg-default p-8 lg:px-12 lg:py-16"
4
3
  :class="
5
- sticky
6
- ? 'lg:sticky lg:top-(--ui-header-height) lg:h-[calc(100vh-var(--ui-header-height))] lg:overflow-y-auto'
7
- : ''
4
+ variant === 'entry'
5
+ ? 'space-y-6 bg-default pt-6 lg:pt-0 lg:pl-8 self-start *:first:mt-0 lg:sticky lg:top-[calc(var(--ui-header-height)+1.5rem)] lg:max-h-[calc(100vh-var(--ui-header-height)-var(--gqlmd-footer-height)-3rem)] lg:overflow-y-auto'
6
+ : 'space-y-6 bg-default p-8 lg:px-12 lg:py-16 lg:sticky lg:top-(--ui-header-height) lg:h-[calc(100vh-var(--ui-header-height)-var(--gqlmd-footer-height))] lg:overflow-y-auto'
8
7
  "
9
8
  >
10
- <ProseCodeGroup v-if="cards.length > 1">
9
+ <!-- Even a lone SDL card goes through the code group so every type gets
10
+ the same tab-bar frame, keeping the code box identical across types. -->
11
+ <ProseCodeGroup v-if="cards.length">
11
12
  <SchemaCodeCard v-for="card in cards" :key="card.label" v-bind="card" />
12
13
  </ProseCodeGroup>
13
- <template v-else-if="cards.length === 1">
14
- <SchemaCodeCard v-bind="singleCard!" />
15
- </template>
16
14
  </section>
17
15
  </template>
18
16
 
19
17
  <script setup lang="ts">
20
18
  import { computed } from "vue";
21
19
 
22
- interface CodeCard {
23
- label: string;
24
- kind: string;
25
- code: string;
26
- html: string;
27
- }
20
+ import type { CodeCard } from "~/composables/useApiCodeCards";
28
21
 
29
22
  const props = withDefaults(
30
23
  defineProps<{
31
24
  definitionCard: CodeCard | undefined;
32
25
  exampleCards: CodeCard[];
33
- /** Pins the column to the viewport as its page scrolls — right for
34
- * `[...slug].vue`'s one-definition-per-page view, wrong when this column
35
- * repeats once per entry down a long single-page view (every instance
36
- * would compete for the same sticky viewport slot). Off there. */
37
- sticky?: boolean;
26
+ /** "page" pins the column to the viewport for `[...slug].vue`'s
27
+ * one-definition-per-page view, stopping above the sticky reference footer.
28
+ * "entry" is for the single-page view, where
29
+ * it sticks inside its own `<article>` grid cell — a sticky element's
30
+ * containing block is its parent, so each entry's box only sticks while
31
+ * that entry is on screen and hands off to the next, with no competition
32
+ * for one viewport slot. It starts level with the entry title (no top
33
+ * padding on lg). */
34
+ variant?: "entry" | "page";
38
35
  }>(),
39
- { sticky: true },
36
+ { variant: "page" },
40
37
  );
41
38
 
42
39
  const cards = computed<CodeCard[]>(() => {
@@ -46,8 +43,4 @@ const cards = computed<CodeCard[]>(() => {
46
43
  ];
47
44
  return allCards.filter((card): card is CodeCard => Boolean(card));
48
45
  });
49
-
50
- const singleCard = computed<CodeCard | undefined>(() => {
51
- return cards.value.length === 1 ? cards.value[0] : undefined;
52
- });
53
46
  </script>
@@ -3,7 +3,7 @@
3
3
  <UPageHeader
4
4
  headline="GRAPHQL SCHEMA REFERENCE"
5
5
  :title="title"
6
- :description="description"
6
+ :description="document ? undefined : description"
7
7
  :ui="{
8
8
  root: 'border-0 pt-0 pb-0',
9
9
  headline: 'font-mono font-normal',
@@ -12,6 +12,12 @@
12
12
  }"
13
13
  />
14
14
 
15
+ <ContentRenderer
16
+ v-if="document"
17
+ :value="document"
18
+ class="markdown-text-body markdown-lead mb-8 max-w-2xl"
19
+ />
20
+
15
21
  <ApiOverviewGrid :items="items" />
16
22
  </div>
17
23
  </template>
@@ -22,6 +28,8 @@ import type { ApiNavigationNode } from "~/composables/useApiNavigation";
22
28
  defineProps<{
23
29
  title: string;
24
30
  description: string;
31
+ /** Rendered in place of `description` when present (the schema homepage). */
32
+ document?: Record<string, any>;
25
33
  items: Array<
26
34
  ApiNavigationNode | (ApiNavigationNode & { sectionTitle: string })
27
35
  >;
@@ -30,7 +30,7 @@
30
30
  </section>
31
31
 
32
32
  <ApiCodeColumn
33
- :sticky="false"
33
+ variant="entry"
34
34
  :definition-card="entry.definitionCard"
35
35
  :example-cards="entry.exampleCards"
36
36
  />
@@ -62,6 +62,8 @@ defineProps<{ entry: ApiSinglePageEntry }>();
62
62
  font-weight: 600;
63
63
  color: var(--ui-text-highlighted);
64
64
  margin-bottom: 1.5rem;
65
+ /* Anchor jumps land the title below the sticky header, not under it. */
66
+ scroll-margin-top: calc(var(--ui-header-height) + 1.5rem);
65
67
  }
66
68
 
67
69
  .api-single-page-entry h3 {
@@ -20,16 +20,38 @@
20
20
 
21
21
  <div class="relative overflow-x-auto p-5 font-mono text-sm">
22
22
  <!-- Inside a code group the tab bar carries the label, so the card drops
23
- its header and the copy button floats over the snippet instead. -->
24
- <UButton
23
+ its header. The kind badge and copy button float over the snippet
24
+ instead, so the kind stays visible for every type. -->
25
+ <div
25
26
  v-if="hideHeader"
26
- v-bind="copyButtonProps"
27
- class="absolute top-3 right-3 z-10"
28
- @click="copy(code)"
29
- />
27
+ class="absolute top-3 right-3 z-10 flex items-center gap-2"
28
+ >
29
+ <UBadge color="primary" variant="subtle" size="sm">{{ kind }}</UBadge>
30
+
31
+ <UButton v-bind="copyButtonProps" @click="copy(code)" />
32
+ </div>
30
33
 
31
34
  <div class="blueprint-code" v-html="html" />
32
35
  </div>
36
+
37
+ <!-- Example variables stack under the query, with their own copy button. -->
38
+ <div
39
+ v-if="variables"
40
+ class="overflow-x-auto border-t border-accented p-5 font-mono text-sm"
41
+ >
42
+ <div class="mb-3 flex items-center justify-between">
43
+ <span class="font-mono text-xs tracking-wider text-muted uppercase"
44
+ >Variables</span
45
+ >
46
+
47
+ <UButton
48
+ v-bind="variablesCopyButtonProps"
49
+ @click="copyVariables(variables.code)"
50
+ />
51
+ </div>
52
+
53
+ <div class="blueprint-code" v-html="variables.html" />
54
+ </div>
33
55
  </div>
34
56
  </template>
35
57
 
@@ -45,9 +67,15 @@ const props = defineProps<{
45
67
  code: string;
46
68
  /** Set by `ProseCodeGroup` on its children; drops the card's own header. */
47
69
  hideHeader?: boolean;
70
+ /** Example variables, highlighted, stacked under the snippet. */
71
+ variables?: { code: string; html: string };
48
72
  }>();
49
73
 
50
74
  const { copy, copyButtonProps } = useClipboardCopy(() => props.label);
75
+
76
+ // Its own instance, so the variables' copied state is independent.
77
+ const { copy: copyVariables, copyButtonProps: variablesCopyButtonProps } =
78
+ useClipboardCopy(() => `${props.label} variables`);
51
79
  </script>
52
80
 
53
81
  <style>
@@ -1,7 +1,5 @@
1
1
  <template>
2
- <UFooter
3
- :ui="{ root: 'border-t border-default bg-muted', container: 'py-6' }"
4
- >
2
+ <UFooter :ui="footerUi">
5
3
  <ULink
6
4
  to="https://graphql-markdown.dev/"
7
5
  target="_blank"
@@ -11,3 +9,21 @@
11
9
  </ULink>
12
10
  </UFooter>
13
11
  </template>
12
+
13
+ <script setup lang="ts">
14
+ import { buildFooterUi } from "~/utils/footer-ui";
15
+ // The reference layout pins the footer like the header and makes it full-bleed
16
+ // so it spans under the fixed sidebar; the landing page keeps the default
17
+ // flow footer.
18
+ const props = withDefaults(
19
+ defineProps<{ containerClass?: string; sticky?: boolean }>(),
20
+ { containerClass: undefined, sticky: false },
21
+ );
22
+
23
+ const footerUi = computed(() =>
24
+ buildFooterUi({
25
+ containerClass: props.containerClass,
26
+ sticky: props.sticky,
27
+ }),
28
+ );
29
+ </script>
@@ -0,0 +1,166 @@
1
+ /** Fallback sticky header height (px) when `--ui-header-height` is unusable. */
2
+ const DEFAULT_HEADER_HEIGHT = 64;
3
+
4
+ /** Reads the sticky header height from the `--ui-header-height` CSS var,
5
+ * accepting `px` and `rem` values. */
6
+ const readHeaderHeight = (): number => {
7
+ const raw = getComputedStyle(document.documentElement)
8
+ .getPropertyValue("--ui-header-height")
9
+ .trim();
10
+ const value = Number.parseFloat(raw);
11
+ if (Number.isNaN(value)) {
12
+ return DEFAULT_HEADER_HEIGHT;
13
+ }
14
+ if (raw.endsWith("rem")) {
15
+ return (
16
+ value *
17
+ Number.parseFloat(getComputedStyle(document.documentElement).fontSize)
18
+ );
19
+ }
20
+ return value;
21
+ };
22
+
23
+ /**
24
+ * Tracks which single-page entry is currently under the sticky header, so the
25
+ * sidebar can highlight it and the URL hash can follow the scroll position.
26
+ *
27
+ * Nuxt UI's `useScrollspy` is deliberately not used: it only tracks headings
28
+ * that are currently visible, so it loses track of the active entry midway
29
+ * through a long entry whose `h2` has already scrolled out of view. Here a
30
+ * `requestAnimationFrame`-throttled `scroll` listener picks the entry spanning
31
+ * the line just under the header (or the last entry when scrolled to the
32
+ * bottom), so the entry crossing that line stays active for as long as any
33
+ * part of it is there. When the page is scrolled back above the first entry,
34
+ * the anchor and the URL hash are cleared.
35
+ *
36
+ * `history.replaceState` (not `router.replace`) keeps the hash in sync without
37
+ * triggering navigation or a scroll jump; a reload then returns to the same
38
+ * entry.
39
+ */
40
+ export const useActiveEntry = (
41
+ enabled: Ref<boolean> | boolean,
42
+ ): { activeAnchor: Ref<string | undefined> } => {
43
+ const route = useRoute();
44
+ const activeAnchor = ref<string | undefined>(
45
+ route.hash.replace(/^#/, "") || undefined,
46
+ );
47
+
48
+ let headerHeight = DEFAULT_HEADER_HEIGHT;
49
+ let frame: number | undefined;
50
+
51
+ const update = (): void => {
52
+ frame = undefined;
53
+ if (!toValue(enabled)) {
54
+ return;
55
+ }
56
+ const entries = [...document.querySelectorAll(".api-single-page-entry")];
57
+ if (entries.length === 0) {
58
+ return;
59
+ }
60
+
61
+ const atBottom =
62
+ window.innerHeight + window.scrollY >=
63
+ document.documentElement.scrollHeight - 1;
64
+ const target = atBottom
65
+ ? entries.at(-1)
66
+ : entries.find((el) => {
67
+ const r = el.getBoundingClientRect();
68
+ return r.top <= headerHeight && r.bottom > headerHeight;
69
+ });
70
+
71
+ if (target) {
72
+ const id = target.querySelector("h2[id]")?.id;
73
+ if (id) {
74
+ activeAnchor.value = id;
75
+ }
76
+ return;
77
+ }
78
+
79
+ // No entry spans the line: if the page is above the first entry, we are
80
+ // back on the intro, so nothing should stay highlighted.
81
+ if (entries[0]!.getBoundingClientRect().top > headerHeight) {
82
+ activeAnchor.value = undefined;
83
+ if (location.hash) {
84
+ history.replaceState(
85
+ history.state,
86
+ "",
87
+ location.pathname + location.search,
88
+ );
89
+ }
90
+ }
91
+ };
92
+
93
+ const onScroll = (): void => {
94
+ frame ??= requestAnimationFrame(update);
95
+ };
96
+
97
+ const onResize = (): void => {
98
+ headerHeight = readHeaderHeight();
99
+ onScroll();
100
+ };
101
+
102
+ /**
103
+ * A link in the content (`<baseURL>/<slug>`) redirects to `<baseURL>#<slug>`,
104
+ * a path change that re-mounts the page — but not this layout-level
105
+ * composable — and the router's own hash scroll ran before the new entries
106
+ * existed. Once the page has rendered, re-scan and scroll the hash target
107
+ * into view (its `h2` carries a `scroll-margin-top` that clears the sticky
108
+ * header).
109
+ */
110
+ const onPageFinish = (): void => {
111
+ void nextTick(() => {
112
+ headerHeight = readHeaderHeight();
113
+ const id = route.hash.replace(/^#/, "");
114
+ if (id && toValue(enabled)) {
115
+ activeAnchor.value = id;
116
+ document.getElementById(id)?.scrollIntoView();
117
+ } else {
118
+ update();
119
+ }
120
+ });
121
+ };
122
+
123
+ let removePageFinishHook: (() => void) | undefined;
124
+
125
+ onMounted(() => {
126
+ headerHeight = readHeaderHeight();
127
+ // With a hash, the router scrolls to the target (firing `scroll`); a scan
128
+ // now would run before that and replace the hash anchor with the top entry.
129
+ if (!route.hash) {
130
+ void nextTick(update);
131
+ }
132
+ removePageFinishHook = useNuxtApp().hook("page:finish", onPageFinish);
133
+ window.addEventListener("resize", onResize);
134
+ window.addEventListener("scroll", onScroll, { passive: true });
135
+ });
136
+
137
+ onBeforeUnmount(() => {
138
+ removePageFinishHook?.();
139
+ window.removeEventListener("resize", onResize);
140
+ window.removeEventListener("scroll", onScroll);
141
+ if (frame !== undefined) {
142
+ cancelAnimationFrame(frame);
143
+ frame = undefined;
144
+ }
145
+ });
146
+
147
+ watch(activeAnchor, (id) => {
148
+ if (import.meta.client && id && toValue(enabled)) {
149
+ history.replaceState(history.state, "", `#${id}`);
150
+ }
151
+ });
152
+
153
+ watch(
154
+ () => {
155
+ return route.hash;
156
+ },
157
+ (hash) => {
158
+ const id = hash.replace(/^#/, "");
159
+ if (id) {
160
+ activeAnchor.value = id;
161
+ }
162
+ },
163
+ );
164
+
165
+ return { activeAnchor };
166
+ };