diff --git a/astro.config.mjs b/astro.config.mjs index b37c279740..d69b0610f8 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -96,6 +96,7 @@ export default defineConfig({ Footer: 'src/components/overrides/Footer.astro', ThemeSelect: 'src/components/overrides/ThemeSelect.astro', PageFrame: 'src/components/overrides/PageFrame.astro', + TableOfContents: 'src/components/overrides/TableOfContents.astro', }, head: [ { diff --git a/src/components/overrides/TableOfContents.astro b/src/components/overrides/TableOfContents.astro new file mode 100644 index 0000000000..c18084eeec --- /dev/null +++ b/src/components/overrides/TableOfContents.astro @@ -0,0 +1,25 @@ +--- +import TableOfContentsList from './TableOfContents/TableOfContentsList.astro'; +import type { Props as BaseProps } from '@astrojs/starlight/props'; + +type Props = BaseProps & { + toc: BaseProps['toc'] & { + collapseLevel?: number; + }; +}; + +const { labels, toc } = Astro.props; +--- + +{ + toc && ( + + + + ) +} + + diff --git a/src/components/overrides/TableOfContents/TableOfContentsList.astro b/src/components/overrides/TableOfContents/TableOfContentsList.astro new file mode 100644 index 0000000000..655b4b753a --- /dev/null +++ b/src/components/overrides/TableOfContents/TableOfContentsList.astro @@ -0,0 +1,144 @@ +--- +import type { TocItem } from 'node_modules/@astrojs/starlight/utils/generateToC'; + +interface Props { + toc: TocItem[]; + depth?: number; + collapseLevel?: number; + isMobile?: boolean; +} + +const { toc, isMobile = false, depth = 0, collapseLevel = 1 } = Astro.props; +--- + + + + diff --git a/src/components/overrides/TableOfContents/starlight-toc.ts b/src/components/overrides/TableOfContents/starlight-toc.ts new file mode 100644 index 0000000000..c20e309f3f --- /dev/null +++ b/src/components/overrides/TableOfContents/starlight-toc.ts @@ -0,0 +1,110 @@ +import { PAGE_TITLE_ID } from 'node_modules/@astrojs/starlight/constants'; + +export class StarlightTOC extends HTMLElement { + private _current = this.querySelector('a[aria-current="true"]'); + private minH = parseInt(this.dataset.minH || '2', 10); + private maxH = parseInt(this.dataset.maxH || '3', 10); + + protected set current(link: HTMLAnchorElement) { + if (link === this._current) return; + if (this._current) this._current.removeAttribute('aria-current'); + link.setAttribute('aria-current', 'true'); + this._current = link; + } + + private onIdle = (cb: IdleRequestCallback) => + (window.requestIdleCallback || ((cb) => setTimeout(cb, 1)))(cb); + + constructor() { + super(); + this.onIdle(() => this.init()); + } + + private init = (): void => { + /** All the links in the table of contents. */ + const links = [...this.querySelectorAll('a')]; + + /** Test if an element is a table-of-contents heading. */ + const isHeading = (el: Element): el is HTMLHeadingElement => { + if (el instanceof HTMLHeadingElement) { + // Special case for page title h1 + if (el.id === PAGE_TITLE_ID) return true; + // Check the heading level is within the user-configured limits for the ToC + const level = el.tagName[1]; + if (level) { + const int = parseInt(level, 10); + if (int >= this.minH && int <= this.maxH) return true; + } + } + return false; + }; + + /** Walk up the DOM to find the nearest heading. */ + const getElementHeading = (el: Element | null): HTMLHeadingElement | null => { + if (!el) return null; + const origin = el; + while (el) { + if (isHeading(el)) return el; + // Assign the previous sibling’s last, most deeply nested child to el. + el = el.previousElementSibling; + while (el?.lastElementChild) { + el = el.lastElementChild; + } + // Look for headings amongst siblings. + const h = getElementHeading(el); + if (h) return h; + } + // Walk back up the parent. + return getElementHeading(origin.parentElement); + }; + + /** Handle intersections and set the current link to the heading for the current intersection. */ + const setCurrent: IntersectionObserverCallback = (entries) => { + for (const { isIntersecting, target } of entries) { + if (!isIntersecting) continue; + const heading = getElementHeading(target); + if (!heading) continue; + const link = links.find((link) => link.hash === '#' + encodeURIComponent(heading.id)); + if (link) { + this.current = link; + break; + } + } + }; + + // Observe elements with an `id` (most likely headings) and their siblings. + // Also observe direct children of `.content` to include elements before + // the first heading. + const toObserve = document.querySelectorAll('main [id], main [id] ~ *, main .content > *'); + + let observer: IntersectionObserver | undefined; + const observe = () => { + if (observer) return; + observer = new IntersectionObserver(setCurrent, { rootMargin: this.getRootMargin() }); + toObserve.forEach((h) => observer!.observe(h)); + }; + observe(); + + let timeout: NodeJS.Timeout; + window.addEventListener('resize', () => { + // Disable intersection observer while window is resizing. + if (observer) observer.disconnect(); + clearTimeout(timeout); + timeout = setTimeout(() => this.onIdle(observe), 200); + }); + }; + + private getRootMargin(): `-${number}px 0% ${number}px` { + const navBarHeight = document.querySelector('header')?.getBoundingClientRect().height || 0; + // `` only exists in mobile ToC, so will fall back to 0 in large viewport component. + const mobileTocHeight = this.querySelector('summary')?.getBoundingClientRect().height || 0; + /** Start intersections at nav height + 2rem padding. */ + const top = navBarHeight + mobileTocHeight + 32; + /** End intersections `53px` later. This is slightly more than the maximum `margin-top` in Markdown content. */ + const bottom = top + 53; + const height = document.documentElement.clientHeight; + return `-${top}px 0% ${bottom - height}px`; + } +} + +customElements.define('starlight-toc', StarlightTOC); diff --git a/src/content/config.ts b/src/content/config.ts index 55ae1f9a1f..da3de68edf 100644 --- a/src/content/config.ts +++ b/src/content/config.ts @@ -1,8 +1,10 @@ import { defineCollection } from 'astro:content'; -import { docsSchema, i18nSchema } from '@astrojs/starlight/schema'; -import { blogSchema } from 'starlight-blog/schema'; +import { i18nSchema } from '@astrojs/starlight/schema'; +import { docsSchema } from 'src/schemas/docsSchema'; export const collections = { - docs: defineCollection({ schema: docsSchema({ extend: (context) => blogSchema(context) }) }), + docs: defineCollection({ + schema: docsSchema, + }), i18n: defineCollection({ type: 'data', schema: i18nSchema() }), }; diff --git a/src/content/docs/start/frontend/nextjs.mdx b/src/content/docs/start/frontend/nextjs.mdx index f525a1e353..9b49fa0fa8 100644 --- a/src/content/docs/start/frontend/nextjs.mdx +++ b/src/content/docs/start/frontend/nextjs.mdx @@ -2,6 +2,7 @@ title: Next.js i18nReady: true tableOfContents: + collapseLevel: 1 minHeadingLevel: 2 maxHeadingLevel: 5 --- diff --git a/src/schemas/docsSchema.ts b/src/schemas/docsSchema.ts new file mode 100644 index 0000000000..70b4447362 --- /dev/null +++ b/src/schemas/docsSchema.ts @@ -0,0 +1,14 @@ +import { z } from 'astro:content'; +import { blogSchema } from 'starlight-blog/schema'; +import { docsSchema as baseDocsSchema } from '@astrojs/starlight/schema'; +import { tableOfContentsSchema } from './tableOfContentsSchema'; + +export const docsSchema = baseDocsSchema({ + extend: (context) => + z.intersection( + blogSchema(context), + z.object({ + tableOfContents: tableOfContentsSchema.optional(), + }) + ), +}); diff --git a/src/schemas/tableOfContentsSchema.ts b/src/schemas/tableOfContentsSchema.ts new file mode 100644 index 0000000000..cf6759ea4a --- /dev/null +++ b/src/schemas/tableOfContentsSchema.ts @@ -0,0 +1,18 @@ +import { z } from 'astro:content'; +import { TableOfContentsSchema as BaseTableOfContentsSchema } from 'node_modules/@astrojs/starlight/schemas/tableOfContents'; + +const tableOfContentsDefaults = { + collapseLevel: 1, + minHeadingLevel: 2, + maxHeadingLevel: 3, +}; + +export const tableOfContentsSchema = z.intersection( + BaseTableOfContentsSchema(), + z.union([ + z.object({ + collapseLevel: z.number().min(0).default(1).optional(), + }), + z.boolean().transform((enabled) => (enabled ? tableOfContentsDefaults : false)), + ]) +); pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy