|
| 1 | +/** |
| 2 | + * Copyright (c) HashiCorp, Inc. |
| 3 | + * SPDX-License-Identifier: MPL-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +// Types |
| 7 | +import type { VersionSwitcherProps } from 'components/version-switcher' |
| 8 | +import type { ApiDocsVersionData } from 'lib/api-docs/types' |
| 9 | + |
| 10 | +/** |
| 11 | + * Given version data and other OpenAPI docs details, |
| 12 | + * Return version switcher dropdown props for use in `OpenApiDocsView`. |
| 13 | + * |
| 14 | + * Note: If there is only one version, we return null. |
| 15 | + */ |
| 16 | +export function getVersionSwitcherProps({ |
| 17 | + projectName, |
| 18 | + versionData, |
| 19 | + targetVersion, |
| 20 | + defaultVersion, |
| 21 | + basePath, |
| 22 | +}: { |
| 23 | + projectName: string |
| 24 | + versionData: ApiDocsVersionData[] |
| 25 | + targetVersion: ApiDocsVersionData |
| 26 | + defaultVersion: ApiDocsVersionData |
| 27 | + basePath: string |
| 28 | +}): VersionSwitcherProps | null { |
| 29 | + // Return null early if we only have one version |
| 30 | + if (versionData.length === 1) { |
| 31 | + return null |
| 32 | + } |
| 33 | + |
| 34 | + // Otherwise, we have multiple versions, we need to build dropdown props |
| 35 | + const label = projectName |
| 36 | + |
| 37 | + // Each version becomes an option in the dropdown |
| 38 | + const options = versionData.map( |
| 39 | + ({ versionId, releaseStage }: ApiDocsVersionData) => { |
| 40 | + /** |
| 41 | + * Determine the version label suffix to show. |
| 42 | + * - Default case is to show the version only, no (suffix) |
| 43 | + * - If this is the default version, show 'latest'. For information on |
| 44 | + * what "default version" means, see `findDefaultVersion`. |
| 45 | + * - If we have a defined releaseStage that isn't 'stable', show it |
| 46 | + */ |
| 47 | + const isLatest = versionId === defaultVersion.versionId |
| 48 | + let versionLabelSuffix = '' |
| 49 | + if (isLatest) { |
| 50 | + versionLabelSuffix = ' (latest)' |
| 51 | + } else if (releaseStage && releaseStage !== 'stable') { |
| 52 | + versionLabelSuffix = ` (${releaseStage})` |
| 53 | + } |
| 54 | + // Construct the label to show in the dropdown |
| 55 | + const label = versionId + versionLabelSuffix |
| 56 | + // Construct the aria-label for the version dropdown. |
| 57 | + const ariaLabel = `Choose a version of the API docs for ${projectName}. Currently viewing version ${label}.` |
| 58 | + // Construct the `href` for this version, which is special if latest |
| 59 | + const href = isLatest ? basePath : `${basePath}/${versionId}` |
| 60 | + // Mark this version option as selected if it's the current option |
| 61 | + const isSelected = versionId === targetVersion.versionId |
| 62 | + // Return all the props |
| 63 | + return { ariaLabel, href, isLatest, isSelected, label } |
| 64 | + } |
| 65 | + ) |
| 66 | + |
| 67 | + // Return the dropdown props |
| 68 | + return { label, options } |
| 69 | +} |
0 commit comments