Add cannonicalref support (#25177)

* Add cannonicalref support
This commit is contained in:
Hamish Willee 2025-07-09 16:44:12 +10:00 committed by GitHub
parent f3919d98fe
commit 98e0fefd4f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -66,7 +66,7 @@ export default defineConfig({
label: "English",
// other locale specific properties...
themeConfig: {
sidebar: getSidebar.sidebar("en"),
sidebar: getSidebar.sidebar("en"), // Generated sidebar from SUMMARY.md files
editLink: {
text:
/* We get a github link if CI env is defined,
@ -211,6 +211,53 @@ export default defineConfig({
],
},
async transformHead({ page, siteData, pageData, title }) {
// Start with an empty array to accumulate all head tags
const head = [];
let canonicalUrlToAdd; // This will be undefined initially
// Get value from frontmatter if defined
// Assumed to be an absolute URL in the frontmatter
const frontmatterCanonicalUrl = pageData.frontmatter?.canonicalUrl;
if (frontmatterCanonicalUrl) {
canonicalUrlToAdd = frontmatterCanonicalUrl;
} else {
// No frontmatter override, generate default based on site config
// Hostname and base path used for adding canonical URLs to pages
const hostname = "https://docs.px4.io/main/";
let path = pageData.relativePath.replace(/\.md$/, "");
if (path === "index") {
path = ""; // For the homepage (index.md), the path is empty
} else if (path.endsWith("/index")) {
path = path.slice(0, -"/index".length); // For directory index pages (e.g., /my-folder/index.md -> /my-folder/)
}
// Ensure fullPath does not start with a slash (makes it relative to the root)
const fullPath = path.startsWith("/") ? path.slice(1) : path;
// Construct the default canonical URL using hostname with main base and path
try {
const url = new URL(fullPath, hostname);
canonicalUrlToAdd = url.href;
} catch (error) {
// Fallback, though less robust
canonicalUrlToAdd = `${hostname}${fullPath}`;
}
}
// Add canonical link to accumulated head array
if (canonicalUrlToAdd) {
head.push(["link", { rel: "canonical", href: canonicalUrlToAdd }]);
}
// Add any other custom head tags you might want later
// Return head that will be merged.
return head;
},
head: [
[
"script",