Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions app/router.options.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
import type { RouterConfig } from '@nuxt/schema';
import { useMutationObserver } from '@vueuse/core';
import { nextTick } from 'vue';

export const scrollPositions = new Map<string, number>();

const DEFAULT_HASH_OFFSET = 80;
const HASH_SCROLL_PADDING = 16;

function parseCssPixels(value: string): number {
const parsed = Number.parseFloat(value);
return Number.isFinite(parsed) ? parsed : 0;
}

function getHashScrollOffset() {
const pane = document.querySelector('.docs-pane') as HTMLElement | null;
const styles = getComputedStyle(pane ?? document.documentElement);
const headerHeight = parseCssPixels(styles.getPropertyValue('--ui-header-height'));
const subnavHeight = parseCssPixels(styles.getPropertyValue('--ui-subnav-height'));
const measuredOffset = headerHeight + subnavHeight + HASH_SCROLL_PADDING;

return Math.max(DEFAULT_HASH_OFFSET, measuredOffset);
}

function getHashTarget(hash: string): HTMLElement | null {
const id = decodeURIComponent(hash.replace(/^#/, ''));
return document.getElementById(id) ?? document.querySelector(hash) as HTMLElement | null;
Expand All @@ -13,14 +32,26 @@ function scrollToHash(scroller: HTMLElement | null, hash: string): boolean {
if (!target) return false;

if (scroller) {
scroller.scrollTo({ top: Math.max(0, target.offsetTop - 80), behavior: 'smooth' });
scroller.scrollTo({ top: Math.max(0, target.offsetTop - getHashScrollOffset()), behavior: 'smooth' });
}
else {
window.scrollTo({ top: Math.max(0, target.offsetTop - 80), behavior: 'smooth' });
window.scrollTo({ top: Math.max(0, target.offsetTop - getHashScrollOffset()), behavior: 'smooth' });
}
return true;
}

function scrollToHashWhenReady(scroller: HTMLElement | null, hash: string) {
if (scrollToHash(scroller, hash)) return;

const root = scroller ?? document.body;
const { stop } = useMutationObserver(root, () => {
if (window.location.hash !== hash || !scrollToHash(scroller, hash)) return;
stop();
window.clearTimeout(timeout);
}, { childList: true, subtree: true });
const timeout = window.setTimeout(stop, 3000);
}

export default <RouterConfig>{
scrollBehavior: async (to, from, savedPosition) => {
const scroller = document.getElementById('docs-scroll');
Expand All @@ -36,7 +67,7 @@ export default <RouterConfig>{

if (to.hash) {
await nextTick();
requestAnimationFrame(() => scrollToHash(scroller, to.hash));
scrollToHashWhenReady(scroller, to.hash);
return false;
}

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"@types/node": "^22",
"@vue/test-utils": "^2.4.10",
"dotenv": "^17.4.2",
"github-slugger": "2.0.0",
"gray-matter": "^4.0.3",
"happy-dom": "^20.9.0",
"js-yaml": "^4.1.1",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions scripts/index-docs-chunker.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import fs from 'node:fs';
import path from 'node:path';
import matter from 'gray-matter';
import GithubSlugger from 'github-slugger';
import { load as loadYaml } from 'js-yaml';
import { remark } from 'remark';
import remarkParse from 'remark-parse';
import remarkMdc from 'remark-mdc';
import { findSectionByPath } from '../shared/utils/docsSections.ts';
import slugify from '../app/utils/slugify.ts';
import { listRoutableContentFiles } from './_content-lib.ts';

const CONTENT_DIR = path.resolve('content');
Expand Down Expand Up @@ -171,6 +171,14 @@ function buildChunkSearchTitle(pageSearchTitle: string, heading?: string) {
return heading?.trim() || pageSearchTitle;
}

function buildSectionAnchors(sections: MarkdownSection[]) {
const slugger = new GithubSlugger();
return sections.map((section) => {
const heading = section.h3 ?? section.h2;
return heading ? slugger.slug(heading) : undefined;
});
}

function normalizeText(value: string): string {
return value
.replace(/\u00a0/g, ' ')
Expand Down Expand Up @@ -520,6 +528,7 @@ export function chunkMarkdownPage({ sourcePath, updatedAt, partials }: ChunkMark
const tree = remark().use(remarkParse).use(remarkMdc).parse(parsed.content) as { children: MdastNode[] };
const blocks = extractBlocks(tree.children, partials);
const sections = blocksToSections(blocks);
const sectionAnchors = buildSectionAnchors(sections);
const rawChunks: RawChunk[] = [];
const summaryChunk = createSummaryChunk(routePath, pageSearchTitle, frontmatter.description, sectionLabel, sections);
if (summaryChunk) rawChunks.push(summaryChunk);
Expand All @@ -529,7 +538,7 @@ export function chunkMarkdownPage({ sourcePath, updatedAt, partials }: ChunkMark
? sectionBlock.textParts
: [sectionBlock.h3 ?? sectionBlock.h2 ?? title];
const contentChunks = chunkSectionText(textParts);
const anchor = sectionBlock.h3 ? slugify(sectionBlock.h3) : sectionBlock.h2 ? slugify(sectionBlock.h2) : undefined;
const anchor = sectionAnchors[sectionIndex];
const heading = sectionBlock.h3 ?? sectionBlock.h2;
const hierarchy = buildSectionHierarchy(sectionLabel, pageSearchTitle, sectionBlock);
const codeBlocks = [...new Set(sectionBlock.codeBlocks.map(normalizeCode).filter(Boolean))];
Expand Down
56 changes: 56 additions & 0 deletions tests/router.options.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// @vitest-environment happy-dom

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import routerOptions from '../app/router.options';

describe('router scroll behavior', () => {
beforeEach(() => {
document.body.innerHTML = '<div id="docs-scroll"></div>';
window.history.pushState({}, '', '/docs/guides/connect/query-parameters#deep');
});

afterEach(() => {
document.body.innerHTML = '';
});

it('waits for a routed hash target rendered after navigation', async () => {
const scroller = document.getElementById('docs-scroll') as HTMLElement;
scroller.scrollTo = vi.fn();

await routerOptions.scrollBehavior?.(
{ path: '/guides/connect/query-parameters', hash: '#deep' } as never,
{ path: '/' } as never,
null as never,
);

expect(scroller.scrollTo).not.toHaveBeenCalled();

const target = document.createElement('h2');
target.id = 'deep';
Object.defineProperty(target, 'offsetTop', { value: 320 });
scroller.appendChild(target);

await new Promise(resolve => setTimeout(resolve, 0));

expect(scroller.scrollTo).toHaveBeenCalledWith({ top: 240, behavior: 'smooth' });
});

it('includes sticky subnav height in the hash scroll offset', async () => {
document.body.innerHTML = '<div id="docs-scroll"><div class="docs-pane" style="--ui-header-height: 64px; --ui-subnav-height: 48px;"></div></div>';
const scroller = document.getElementById('docs-scroll') as HTMLElement;
scroller.scrollTo = vi.fn();

const target = document.createElement('h2');
target.id = 'deep';
Object.defineProperty(target, 'offsetTop', { value: 320 });
scroller.appendChild(target);

await routerOptions.scrollBehavior?.(
{ path: '/guides/connect/query-parameters', hash: '#deep' } as never,
{ path: '/' } as never,
null as never,
);

expect(scroller.scrollTo).toHaveBeenCalledWith({ top: 192, behavior: 'smooth' });
});
});
18 changes: 18 additions & 0 deletions tests/scripts/index-docs-chunker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,22 @@ describe('index-docs chunker', () => {
expect(combined).toContain('Operations');
expect(combined).not.toContain('shiny-card');
});

it('matches rendered heading anchors for duplicate and punctuated headings', () => {
const sourcePath = path.resolve('content/guides/06.flows/4.operations.md');
const partials = loadPartials();
const documents = chunkMarkdownPage({
sourcePath,
updatedAt: Math.round(fs.statSync(sourcePath).mtimeMs),
partials,
});

const optionsAnchors = [...new Set(documents
.filter(document => document.heading === 'Options')
.map(document => document.anchor))];

expect(optionsAnchors.slice(0, 4)).toEqual(['options', 'options-1', 'options-2', 'options-3']);
expect(optionsAnchors).toHaveLength(new Set(optionsAnchors).size);
expect(documents.find(document => document.heading === 'Webhook / Request URL')?.anchor).toBe('webhook--request-url');
});
});
Loading