@stacksjs/bunpress 0.2.3 → 0.2.5
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/bin/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{t as a,u as b,v as c}from"../chunk-
|
|
3
|
+
import{t as a,u as b,v as c}from"../chunk-8shhd6mj.js";import"../chunk-5cxb3t2e.js";import"../chunk-he00q0q4.js";import"../chunk-3f29kjd8.js";export{b as resolveConfig,a as findMarkdownFiles,c as buildDocs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{A as v4,x as w4,y as C4}from"./chunk-5cxb3t2e.js";import{$ as P4,C as b4,D as z,F as o,I as I4,J as L4,K as x4,Z as k4}from"./chunk-he00q0q4.js";import{aa as F}from"./chunk-3f29kjd8.js";var{Glob:h4}=globalThis.Bun;import{copyFile as I6,mkdir as m4,readdir as L6,rename as x6,rm as t}from"fs/promises";import{existsSync as E6}from"fs";import{join as D,resolve as S6}from"path";import S from"process";import{CLI as F6}from"@stacksjs/clapp";var f="0.2.
|
|
2
|
+
import{A as v4,x as w4,y as C4}from"./chunk-5cxb3t2e.js";import{$ as P4,C as b4,D as z,F as o,I as I4,J as L4,K as x4,Z as k4}from"./chunk-he00q0q4.js";import{aa as F}from"./chunk-3f29kjd8.js";var{Glob:h4}=globalThis.Bun;import{copyFile as I6,mkdir as m4,readdir as L6,rename as x6,rm as t}from"fs/promises";import{existsSync as E6}from"fs";import{join as D,resolve as S6}from"path";import S from"process";import{CLI as F6}from"@stacksjs/clapp";var f="0.2.5";var{Glob:n4}=globalThis.Bun;import{dirname as i4,relative as s4,resolve as d,sep as X4}from"path";import{mkdir as r4}from"fs/promises";function Y4(K){return X4==="/"?K:K.split(X4).join("/")}function o4(K){let Z=new Bun.CryptoHasher("sha256");return Z.update(K),Z.digest("hex")}async function q4(K,Z,Q){let $=d(K),N=Q?Y4(s4($,d(Q))):void 0,X=[],q=new n4("**/*");for await(let j of q.scan({cwd:$,onlyFiles:!0})){let _=Y4(j);if(_===N)continue;X.push(_)}X.sort((j,_)=>j.localeCompare(_));let Y=[],W=new Bun.CryptoHasher("sha256");for(let j of X){let _=new Uint8Array(await Bun.file(d($,j)).arrayBuffer()),R=o4(_);Y.push({path:j,bytes:_.byteLength,sha256:R}),W.update(`${j}\x00${_.byteLength}\x00${R}
|
|
3
3
|
`)}return{schema_version:1,generator:"bunpress",generator_version:Z,outputs:Y,tree_sha256:W.digest("hex")}}async function H4(K,Z,Q){let $=await q4(K,Q,Z);return await r4(i4(d(Z)),{recursive:!0}),await Bun.write(Z,`${JSON.stringify($,null,2)}
|
|
4
4
|
`),$}function N4(K){return new Map(K.outputs.map((Z)=>[Z.path,Z]))}async function _4(K,Z,Q){let $=await Bun.file(Z).json();if($.schema_version!==1||$.generator!=="bunpress"||!Array.isArray($.outputs))throw Error(`Unsupported or malformed BunPress build manifest: ${Z}`);let N=await q4(K,Q,Z);if(JSON.stringify(N)===JSON.stringify($))return N;let X=N4($),q=N4(N),Y=N.outputs.filter((R)=>!X.has(R.path)).map((R)=>R.path),W=$.outputs.filter((R)=>!q.has(R.path)).map((R)=>R.path),j=N.outputs.filter((R)=>{let G=X.get(R.path);return G&&(G.bytes!==R.bytes||G.sha256!==R.sha256)}).map((R)=>{let G=X.get(R.path);return`${R.path} [bytes ${G.bytes} -> ${R.bytes}; sha256 ${G.sha256} -> ${R.sha256}]`}),_=[$.generator_version!==N.generator_version?`generator ${$.generator_version} -> ${N.generator_version}`:"",Y.length?`added: ${Y.join(", ")}`:"",W.length?`removed: ${W.join(", ")}`:"",j.length?`changed: ${j.join(", ")}`:""].filter(Boolean);throw Error(`BunPress output does not match ${Z}: ${_.join("; ")||"tree hash changed"}`)}import{existsSync as t4}from"fs";import{rm as e4}from"fs/promises";import{join as K6}from"path";var L={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m"};function O(K,Z){return`${L[Z]}${K}${L.reset}`}function T(K){console.log(`${L.green}\u2713${L.reset} ${K}`)}function U(K){console.error(`${L.red}\u2717${L.reset} ${K}`)}function p(K){console.warn(`${L.yellow}\u26A0${L.reset} ${K}`)}function M(K){console.log(`${L.blue}\u2139${L.reset} ${K}`)}function b(K){if(K===0)return"0 B";let Z=1024,Q=["B","KB","MB","GB"],$=Math.floor(Math.log(K)/Math.log(Z));return`${Number.parseFloat((K/Z**$).toFixed(2))} ${Q[$]}`}function a(K){if(K<1000)return`${K}ms`;if(K<60000)return`${(K/1000).toFixed(2)}s`;return`${(K/60000).toFixed(2)}m`}var W4=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);class v{frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;interval=null;text;constructor(K){this.text=K}start(){if(W4){console.log(` ${this.text}`);return}process.stdout.write("\x1B[?25l"),this.interval=setInterval(()=>{let K=this.frames[this.index];process.stdout.write(`\r${L.cyan}${K}${L.reset} ${this.text}`),this.index=(this.index+1)%this.frames.length},80)}succeed(K){this.stop(),T(K||this.text)}fail(K){this.stop(),U(K||this.text)}stop(){if(this.interval)clearInterval(this.interval),this.interval=null;if(!W4)process.stdout.write("\r\x1B[K"),process.stdout.write("\x1B[?25h")}update(K){this.text=K}}async function c(K,Z=!1){let Q=Z?"Y/n":"y/N";process.stdout.write(`${L.cyan}?${L.reset} ${K} ${L.dim}(${Q})${L.reset}: `);let $=Bun.file("/dev/stdin").stream().getReader(),N=new TextDecoder,{value:X}=await $.read(),q=N.decode(X).trim().toLowerCase();if(!q)return Z;return q==="y"||q==="yes"}function m(K){if(K.length===0)return;let Z=Object.keys(K[0]),Q={};for(let N of Z)Q[N]=Math.max(N.length,...K.map((X)=>String(X[N]).length));let $=Z.map((N)=>N.padEnd(Q[N])).join(" ");console.log(O($,"bold")),console.log("\u2500".repeat($.length));for(let N of K){let X=Z.map((q)=>String(N[q]).padEnd(Q[q])).join(" ");console.log(X)}}async function l(K){try{return Bun.file(K).size}catch{return 0}}async function Q6(K){try{let{Glob:Z}=awaitPromise.resolve(globalThis.Bun),Q=new Z("**/*"),$=0;for await(let N of Q.scan(K)){let X=`${K}/${N}`,q=await l(X);$+=q}return $}catch{return 0}}async function R4(K={}){let Z=await z,Q=K.outdir||Z.outDir||"./dist",$=K6(Q,".bunpress"),N=K.force||!1,X=K.verbose||!1;try{if(!t4($))return M(`Directory "${$}" does not exist, nothing to clean`),!0;let Y=await Q6($);if(X)M(`Found "${$}" (${b(Y)})`);if(!N){if(!await c(`Delete "${$}" directory? (${b(Y)})`,!1))return M("Clean cancelled"),!1}let W=process.env.VITEST==="true"||!1,j=null;if(!W&&!X)j=new v("Cleaning build artifacts..."),j.start();if(await e4($,{recursive:!0,force:!0}),j)j.succeed(`Cleaned ${b(Y)} from "${$}"`);else if(X||W)T(`Cleaned ${b(Y)} from "${$}"`);return!0}catch(q){return U(`Failed to clean directory: ${q}`),!1}}import{existsSync as n}from"fs";import{join as i}from"path";async function j4(K={}){try{let Z=["bunpress.config.ts","bunpress.config.js"],Q=null;for(let N of Z){let X=i(process.cwd(),N);if(n(X)){Q=X;break}}if(!Q)return U("No configuration file found"),M('Run "bunpress config init" to create one'),!1;T(`Configuration file: ${Q}`),console.log();let $=await Bun.file(Q).text();return console.log(O("Configuration:","bold")),console.log($),!0}catch(Z){return U(`Failed to show configuration: ${Z}`),!1}}async function G4(K={}){let Z=K.verbose||!1;try{let Q=["bunpress.config.ts","bunpress.config.js"],$=null;for(let Y of Q){let W=i(process.cwd(),Y);if(n(W)){$=W;break}}if(!$)return U("No configuration file found"),!1;if(Z)M(`Validating ${$}...`);let X=(await import($)).default;if(!X)return U("Configuration file does not export a default object"),!1;let q=[];if(X.markdown){if(X.markdown.toc&&typeof X.markdown.toc!=="object"&&typeof X.markdown.toc!=="boolean")q.push("markdown.toc should be an object or boolean");if(X.markdown.features){if(typeof X.markdown.features!=="object")q.push("markdown.features should be an object")}}if(X.nav){if(!Array.isArray(X.nav))q.push("nav should be an array");else for(let[Y,W]of X.nav.entries())if(!W.text||!W.link)q.push(`nav[${Y}] is missing required fields (text, link)`)}if(X.sitemap){if(!X.sitemap.hostname)q.push("sitemap.hostname is required for SEO")}if(q.length>0){U("Configuration validation failed:");for(let Y of q)console.log(` \u2022 ${Y}`);return!1}return T("Configuration is valid \u2713"),!0}catch(Q){return U(`Failed to validate configuration: ${Q}`),!1}}async function U4(K={}){let Z=i(process.cwd(),"bunpress.config.ts");if(n(Z))return U("Configuration file already exists"),!1;let Q=`import type { BunPressConfig } from '@stacksjs/bunpress'
|
|
5
5
|
|
|
@@ -389,5 +389,5 @@ Detected change in ${q}, rebuilding...`),await D4(K)}),await new Promise(()=>{})
|
|
|
389
389
|
`}Y+=`---
|
|
390
390
|
|
|
391
391
|
`}return await Bun.write($,Y),console.log(`
|
|
392
|
-
LLM markdown generated successfully: ${$}`),console.log(`Total size: ${(Y.length/1024).toFixed(2)} KB`),!0}I.command("llm","Generate LLM-friendly markdown file from documentation").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--output <output>","Output file path",{default:"./docs.md"}).option("--full","Include full content (not just titles and headings)",{default:!1}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await P6(K))S.exit(1)});I.command("init","Initialize a new BunPress project").option("--name <name>","Project name").option("--template <template>","Template to use").option("--force","Overwrite existing files",{default:!1}).action(async(K)=>{if(!await J4(K))S.exit(1)});I.command("preview","Preview the built documentation site").option("--port <port>","Port to listen on",{default:J.port}).option("--outdir <outdir>","Output directory (looks for .bunpress folder inside)").option("--open","Open in browser",{default:!1}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{await z4(K)});I.command("clean","Clean build artifacts").option("--outdir <outdir>","Output directory to clean",{default:J.outdir}).option("--force","Skip confirmation prompt",{default:!1}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await R4(K))S.exit(1)});I.command("doctor","Run diagnostic checks on the project").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await A4(K))S.exit(1)});I.command("config:show","Show current configuration").option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await j4(K))S.exit(1)});I.command("config:validate","Validate configuration file").option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await G4(K))S.exit(1)});I.command("config:init","Initialize configuration file").action(async(K)=>{if(!await U4(K))S.exit(1)});I.command("new <path>","Create a new markdown file").option("--title <title>","Page title").option("--template <template>","Template to use (default, guide, api, blog)",{default:"default"}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K,Z)=>{if(!await B4(K,Z))S.exit(1)});I.command("stats","Show documentation statistics").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await y4(K))S.exit(1)});I.command("seo:check","Check SEO for all documentation pages").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--fix","Automatically fix issues (add missing titles/descriptions)",{default:!1}).action(async(K)=>{await S4(K)});I.command("deploy","Deploy documentation to AWS using CloudFormation (S3 + CloudFront + Route53)").option("--region <region>","AWS region for S3 bucket",{default:"us-east-1"}).option("--bucket <bucket>","S3 bucket name (auto-generated if not provided)").option("--domain <domain>","Custom domain (e.g., docs.example.com)").option("--subdomain <subdomain>","Subdomain (used with --base-domain)").option("--base-domain <baseDomain>","Base domain (e.g., example.com) - must have Route53 hosted zone").option("--stack-name <stackName>","CloudFormation stack name").option("--hosted-zone-id <hostedZoneId>","Route53 hosted zone ID (auto-detected from domain)").option("--certificate-arn <certificateArn>","ACM certificate ARN (auto-created if not provided)").option("--dry-run","Show configuration without deploying",{default:!1}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{let{deployCommand:Z}=await import("./chunk-
|
|
392
|
+
LLM markdown generated successfully: ${$}`),console.log(`Total size: ${(Y.length/1024).toFixed(2)} KB`),!0}I.command("llm","Generate LLM-friendly markdown file from documentation").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--output <output>","Output file path",{default:"./docs.md"}).option("--full","Include full content (not just titles and headings)",{default:!1}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await P6(K))S.exit(1)});I.command("init","Initialize a new BunPress project").option("--name <name>","Project name").option("--template <template>","Template to use").option("--force","Overwrite existing files",{default:!1}).action(async(K)=>{if(!await J4(K))S.exit(1)});I.command("preview","Preview the built documentation site").option("--port <port>","Port to listen on",{default:J.port}).option("--outdir <outdir>","Output directory (looks for .bunpress folder inside)").option("--open","Open in browser",{default:!1}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{await z4(K)});I.command("clean","Clean build artifacts").option("--outdir <outdir>","Output directory to clean",{default:J.outdir}).option("--force","Skip confirmation prompt",{default:!1}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await R4(K))S.exit(1)});I.command("doctor","Run diagnostic checks on the project").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await A4(K))S.exit(1)});I.command("config:show","Show current configuration").option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await j4(K))S.exit(1)});I.command("config:validate","Validate configuration file").option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await G4(K))S.exit(1)});I.command("config:init","Initialize configuration file").action(async(K)=>{if(!await U4(K))S.exit(1)});I.command("new <path>","Create a new markdown file").option("--title <title>","Page title").option("--template <template>","Template to use (default, guide, api, blog)",{default:"default"}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K,Z)=>{if(!await B4(K,Z))S.exit(1)});I.command("stats","Show documentation statistics").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{if(!await y4(K))S.exit(1)});I.command("seo:check","Check SEO for all documentation pages").option("--dir <dir>","Documentation directory (defaults to config docsDir)").option("--fix","Automatically fix issues (add missing titles/descriptions)",{default:!1}).action(async(K)=>{await S4(K)});I.command("deploy","Deploy documentation to AWS using CloudFormation (S3 + CloudFront + Route53)").option("--region <region>","AWS region for S3 bucket",{default:"us-east-1"}).option("--bucket <bucket>","S3 bucket name (auto-generated if not provided)").option("--domain <domain>","Custom domain (e.g., docs.example.com)").option("--subdomain <subdomain>","Subdomain (used with --base-domain)").option("--base-domain <baseDomain>","Base domain (e.g., example.com) - must have Route53 hosted zone").option("--stack-name <stackName>","CloudFormation stack name").option("--hosted-zone-id <hostedZoneId>","Route53 hosted zone ID (auto-detected from domain)").option("--certificate-arn <certificateArn>","ACM certificate ARN (auto-created if not provided)").option("--dry-run","Show configuration without deploying",{default:!1}).option("--verbose","Enable verbose logging",{default:J.verbose}).action(async(K)=>{let{deployCommand:Z}=await import("./chunk-tg73rxw0.js");if(!await Z(K))S.exit(1)});I.help();I.version(f);var e=Bun.argv[1]||"",h6=e.endsWith("/bunpress")||e.endsWith("/cli.ts")||e.endsWith("/cli.js");if(h6)I.parse();
|
|
393
393
|
export{T as p,U as q,M as r,v as s,g4 as t,C6 as u,D4 as v};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{p as $,q as I,r as f,s as h,v as x}from"./chunk-
|
|
2
|
+
import{p as $,q as I,r as f,s as h,v as x}from"./chunk-8shhd6mj.js";import"./chunk-5cxb3t2e.js";import{D as _}from"./chunk-he00q0q4.js";import"./chunk-3f29kjd8.js";import{join as D}from"path";var E="@stacksjs/ts-cloud";async function Y(){try{return await import(E)}catch(j){throw Error(`Deploying requires @stacksjs/ts-cloud, which is an optional dependency.
|
|
3
3
|
Install it with: bun add -d @stacksjs/ts-cloud
|
|
4
4
|
Original error: ${j instanceof Error?j.message:String(j)}`)}}function W(j,A){let k=A||j?.provider;if(!k||k==="route53")return null;if(k==="porkbun"){let m=j?.apiKey||process.env.PORKBUN_API_KEY,w=j?.secretKey||process.env.PORKBUN_SECRET_KEY;if(!m||!w)throw Error("Porkbun API credentials not found. Set PORKBUN_API_KEY and PORKBUN_SECRET_KEY environment variables, or configure them in bunpress.config.ts under cloud.dnsProvider");return{provider:"porkbun",apiKey:m,secretKey:w}}if(k==="godaddy"){let m=j?.apiKey||process.env.GODADDY_API_KEY,w=j?.secretKey||process.env.GODADDY_API_SECRET,J=j?.environment||process.env.GODADDY_ENVIRONMENT;if(!m||!w)throw Error("GoDaddy API credentials not found. Set GODADDY_API_KEY and GODADDY_API_SECRET environment variables, or configure them in bunpress.config.ts under cloud.dnsProvider");return{provider:"godaddy",apiKey:m,apiSecret:w,environment:J}}throw Error(`Unknown DNS provider: ${k}. Supported: porkbun, godaddy, route53`)}async function F(j={}){let A=await _,k=A.cloud||{},m=j.verbose??A.verbose??!1,w=j.region||k.region||"us-east-1",J=j.domain||k.domain,M=j.subdomain||k.subdomain,N=j.baseDomain||k.baseDomain,O=j.bucket||k.bucket,P=j.stackName||k.stackName,U=j.hostedZoneId||k.hostedZoneId,Q=j.certificateArn||k.certificateArn,V=k.cacheControl||"max-age=31536000, public",B;if(J)B=J;else if(M&&N)B=`${M}.${N}`;let K=B?.replace(/\./g,"-")||"bunpress-site",G=null;try{G=W(k.dnsProvider,j.dnsProvider)}catch(H){return I(H.message),!1}let L=G!==null;if(j.dryRun){if(f("Dry run mode - no changes will be made"),console.log(`
|
|
5
5
|
Configuration:`),console.log(` Region: ${w}`),console.log(` Site Name: ${K}`),console.log(` Bucket: ${O||"auto-generated"}`),console.log(` Domain: ${B||"not specified"}`),console.log(` Stack Name: ${P||`${K}-static-site`}`),console.log(` DNS Provider: ${G?.provider||"route53 (AWS)"}`),!L)console.log(` Hosted Zone ID: ${U||"auto-detected"}`);return console.log(` Certificate ARN: ${Q||"auto-created"}`),!0}if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY)return I("AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables."),!1;let z=new h("Building documentation...");try{if(!m)z.start();if(!await x({verbose:m})){if(!m)z.fail("Build failed");return!1}if(!m)z.succeed("Documentation built successfully");let C=A.outDir||"./dist",X=D(C,".bunpress");if(!m)z.text="Deploying infrastructure with CloudFormation...",z.start();else if(console.log(`
|
|
@@ -203,6 +203,16 @@ function initPageTOC() {
|
|
|
203
203
|
activeId = headingPositions[0].id;
|
|
204
204
|
}
|
|
205
205
|
|
|
206
|
+
// At the bottom of the page the remaining headings can never reach the top
|
|
207
|
+
// of the viewport, so the rule above freezes on whichever one got there
|
|
208
|
+
// last. The reader is looking at the final section, so mark it: without
|
|
209
|
+
// this, the last few entries are unreachable and clicking one visibly
|
|
210
|
+
// snaps the highlight back to an earlier heading.
|
|
211
|
+
const atBottom = scrollY + scrollContainer.clientHeight >= scrollContainer.scrollHeight - 2;
|
|
212
|
+
if (atBottom && headingPositions.length > 0) {
|
|
213
|
+
activeId = headingPositions[headingPositions.length - 1].id;
|
|
214
|
+
}
|
|
215
|
+
|
|
206
216
|
// Activate the link
|
|
207
217
|
activateLink(activeId ? '#' + activeId : null);
|
|
208
218
|
}
|
|
@@ -229,6 +239,14 @@ function initPageTOC() {
|
|
|
229
239
|
|
|
230
240
|
// Update URL without page reload
|
|
231
241
|
history.pushState(null, '', '#' + targetId);
|
|
242
|
+
|
|
243
|
+
// Clicking the entry for a heading near the end of the page cannot
|
|
244
|
+
// scroll far enough to make that heading the topmost one, so the
|
|
245
|
+
// scroll handler would settle on an earlier entry and the click would
|
|
246
|
+
// appear to jump to the wrong place. Mark the clicked one, then let
|
|
247
|
+
// the settle pass reconcile once the scroll finishes.
|
|
248
|
+
activateLink('#' + targetId);
|
|
249
|
+
settleActiveLink();
|
|
232
250
|
}
|
|
233
251
|
});
|
|
234
252
|
});
|
|
@@ -241,23 +259,75 @@ function initPageTOC() {
|
|
|
241
259
|
scrollContainer.__bpTocScroll = onScroll;
|
|
242
260
|
scrollContainer.addEventListener('scroll', onScroll);
|
|
243
261
|
|
|
262
|
+
/**
|
|
263
|
+
* Recompute the highlight once a programmatic scroll has come to rest.
|
|
264
|
+
*
|
|
265
|
+
* A scroll this code starts itself cannot be relied on to drive the scroll
|
|
266
|
+
* listener. When the browser has already jumped to the anchor on its own,
|
|
267
|
+
* the scrollTo below asks for the position the container is ALREADY at, no
|
|
268
|
+
* scroll event fires at all, and nothing recomputes the highlight. Prefer
|
|
269
|
+
* the real `scrollend` event and fall back to a timer where it is missing.
|
|
270
|
+
*/
|
|
271
|
+
function settleActiveLink() {
|
|
272
|
+
if ('onscrollend' in window) {
|
|
273
|
+
scrollContainer.addEventListener('scrollend', setActiveLink, { once: true });
|
|
274
|
+
// scrollend never arrives when the scroll was a no-op, so still arm a
|
|
275
|
+
// fallback; setActiveLink is idempotent, so running twice is harmless.
|
|
276
|
+
setTimeout(setActiveLink, 400);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
setTimeout(setActiveLink, 400);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Scroll the container so the hash target sits just below the nav. */
|
|
283
|
+
function scrollToHashTarget(behavior) {
|
|
284
|
+
if (!window.location.hash) return;
|
|
285
|
+
const targetId = decodeURIComponent(window.location.hash.substring(1));
|
|
286
|
+
const targetElement = document.getElementById(targetId);
|
|
287
|
+
if (!targetElement) return;
|
|
288
|
+
|
|
289
|
+
const containerRect = scrollContainer.getBoundingClientRect();
|
|
290
|
+
const targetRect = targetElement.getBoundingClientRect();
|
|
291
|
+
|
|
292
|
+
scrollContainer.scrollTo({
|
|
293
|
+
top: targetRect.top - containerRect.top + scrollContainer.scrollTop - 80,
|
|
294
|
+
behavior: behavior
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
// The initial update runs ~16ms in, long before this, so without this the
|
|
298
|
+
// highlight stayed on whatever heading was on screen at scroll position
|
|
299
|
+
// zero and every deep link arrived with the wrong entry marked.
|
|
300
|
+
settleActiveLink();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Once the reader takes over, this script stops moving the page under them.
|
|
304
|
+
let userScrolled = false;
|
|
305
|
+
['wheel', 'touchstart', 'keydown'].forEach((evt) => {
|
|
306
|
+
scrollContainer.addEventListener(evt, () => { userScrolled = true; }, { once: true, passive: true });
|
|
307
|
+
});
|
|
308
|
+
|
|
244
309
|
// Handle URL hash on page load
|
|
245
310
|
if (window.location.hash) {
|
|
246
|
-
setTimeout(() =>
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
311
|
+
setTimeout(() => scrollToHashTarget('smooth'), 100);
|
|
312
|
+
|
|
313
|
+
// Every offset above is measured against the layout as it stands right
|
|
314
|
+
// then. Web fonts and late-loading media reflow the document afterwards,
|
|
315
|
+
// and on a long page the scroll computed against the OLD layout can end up
|
|
316
|
+
// past the new maximum — the browser clamps it, and the reader lands at
|
|
317
|
+
// the foot of the page instead of at their heading, with the outline
|
|
318
|
+
// faithfully highlighting the last entry. So re-aim once things settle.
|
|
319
|
+
const reaim = () => { if (!userScrolled) scrollToHashTarget('auto'); };
|
|
320
|
+
if (document.fonts && document.fonts.ready) document.fonts.ready.then(reaim);
|
|
321
|
+
window.addEventListener('load', reaim, { once: true });
|
|
322
|
+
}
|
|
253
323
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
}
|
|
259
|
-
}, 100);
|
|
324
|
+
// A hash change that this script did not initiate (back/forward, or a link
|
|
325
|
+
// elsewhere on the page) scrolls without passing through the click handler.
|
|
326
|
+
if (window.__bpTocHashChange) {
|
|
327
|
+
window.removeEventListener('hashchange', window.__bpTocHashChange);
|
|
260
328
|
}
|
|
329
|
+
window.__bpTocHashChange = settleActiveLink;
|
|
330
|
+
window.addEventListener('hashchange', settleActiveLink);
|
|
261
331
|
|
|
262
332
|
// Initial update
|
|
263
333
|
requestAnimationFrame(setActiveLink);
|