|
| 1 | +import Link from "@docusaurus/Link"; |
| 2 | +import useDocusaurusContext from "@docusaurus/useDocusaurusContext"; |
| 3 | + |
| 4 | +const docsPluginPath = "./src/js/docsPluginWithTopLevel404.js"; |
| 5 | + |
| 6 | +// extract the plugin configuration from docusaurus and use this to deduce the "version" references |
| 7 | +// for the link component |
| 8 | +const useVersionConfigs = () => { |
| 9 | + const { siteConfig } = useDocusaurusContext(); |
| 10 | + |
| 11 | + const [_, docsPluginConfig] = siteConfig.plugins.find( |
| 12 | + (pair) => pair[0] == docsPluginPath |
| 13 | + ); |
| 14 | + if (!docsPluginConfig) { |
| 15 | + throw new Error( |
| 16 | + `failed to find docs plugin at ${docsPluginPath} in docusaurus.config.js; has something been renamed?` |
| 17 | + ); |
| 18 | + } |
| 19 | + |
| 20 | + const current = docsPluginConfig.versions.current; |
| 21 | + return { |
| 22 | + "current-dev": current, |
| 23 | + // When running the dev server, we might be only showing the "current" docs (unless |
| 24 | + // PANTSBUILD_ORG_INCLUDE_VERSIONS is set), in which lastVersion may not be set, so we just |
| 25 | + // fallback to the current version to keep things working |
| 26 | + "last-stable": docsPluginConfig.lastVersion |
| 27 | + ? docsPluginConfig.versions[docsPluginConfig.lastVersion] |
| 28 | + : current, |
| 29 | + }; |
| 30 | +}; |
| 31 | + |
| 32 | +/** |
| 33 | + * Link to a particular path within auto-generated docs & reference, "live" for the appropriate version. |
| 34 | + * |
| 35 | + * For instance, to link to /2.19/docs/introduction/welcome-to-pants |
| 36 | + * for whatever the current stable version is, use: |
| 37 | + * |
| 38 | + * <VersionedDocsLink version="latest-stable" unversionedPath="docs/introduction/welcome-to-pants">Welcome!</VersionedDocsLink> |
| 39 | + * |
| 40 | + * @param unversionedPath - the URL path without the leading /2.x/ version bit |
| 41 | + * @param version - the description of the version to link to: `current-dev` (Pants' main branch), `last-stable` (most recent stable) |
| 42 | + * @param linkProps - any other parameters to pass to @docusaurus/Link (including `children`) |
| 43 | + */ |
| 44 | +export default function VersionedDocsLink({ |
| 45 | + unversionedPath, |
| 46 | + version, |
| 47 | + ...linkProps |
| 48 | +}) { |
| 49 | + const versionConfigs = useVersionConfigs(); |
| 50 | + |
| 51 | + const versionConfig = versionConfigs[version]; |
| 52 | + if (!versionConfig) { |
| 53 | + const supported = Object.keys(versionConfigs).join(", "); |
| 54 | + throw new Error( |
| 55 | + `failed to find configuration for version="${version}" with unversionedPath="${unversionedPath}"; supported version values are: ${supported}` |
| 56 | + ); |
| 57 | + } |
| 58 | + |
| 59 | + const to = `/${versionConfig.path}/${unversionedPath}`; |
| 60 | + return <Link to={to} {...linkProps} />; |
| 61 | +} |
0 commit comments