|
| 1 | +import React, {ReactElement, useState} from 'react'; |
| 2 | +import CodeBlock from '@theme/CodeBlock'; |
| 3 | + |
| 4 | +export type Snippet = { |
| 5 | + label: string; // visible tab label (e.g. "Shell", "Helm", "Go") |
| 6 | + language: string; // language prop for CodeBlock (e.g. "sh", "yaml", "go") |
| 7 | + code: string; // the snippet to display |
| 8 | +}; |
| 9 | + |
| 10 | +type Props = { |
| 11 | + snippets: Snippet[]; |
| 12 | + defaultIndex?: number; |
| 13 | + className?: string; |
| 14 | +}; |
| 15 | + |
| 16 | +export function MultiLangCodeBlock({snippets, defaultIndex = 0, className}: Props): ReactElement | null { |
| 17 | + const safeDefault = Math.max(0, Math.min(defaultIndex, snippets.length - 1)); |
| 18 | + const [active, setActive] = useState<number>(snippets.length > 0 ? safeDefault : -1); |
| 19 | + |
| 20 | + if (snippets.length === 0) return null; |
| 21 | + |
| 22 | + const tabStyle: React.CSSProperties = { |
| 23 | + padding: '0.3rem 0.5rem', |
| 24 | + cursor: 'pointer', |
| 25 | + border: '0', |
| 26 | + borderRadius: 'var(--ifm-code-border-radius)', |
| 27 | + margin: '0 0 0 0', |
| 28 | + fontSize: '0.8125rem', |
| 29 | + color: 'inherit', |
| 30 | + }; |
| 31 | + |
| 32 | + const activeTabStyle: React.CSSProperties = { |
| 33 | + ...tabStyle, |
| 34 | + fontWeight: 700, |
| 35 | + }; |
| 36 | + |
| 37 | + const tabsContainerStyle: React.CSSProperties = { |
| 38 | + display: 'flex', |
| 39 | + alignItems: 'flex-end', |
| 40 | + justifyContent: 'flex-end', |
| 41 | + gap: '0.25rem', |
| 42 | + margin: '0 0 -0.5rem', |
| 43 | + padding: '0.5rem 0.5rem 1rem', |
| 44 | + flexWrap: 'wrap', |
| 45 | + }; |
| 46 | + |
| 47 | + const wrapperStyle: React.CSSProperties = { |
| 48 | + overflow: 'hidden', |
| 49 | + padding: '0', |
| 50 | + }; |
| 51 | + |
| 52 | + return ( |
| 53 | + <div className={className} style={wrapperStyle}> |
| 54 | + <div role="tablist" aria-label="Code snippets" style={tabsContainerStyle}> |
| 55 | + {snippets.map((ex, idx) => ( |
| 56 | + <button |
| 57 | + key={ex.label + idx} |
| 58 | + role="tab" |
| 59 | + aria-selected={active === idx} |
| 60 | + aria-controls={`code-panel-${idx}`} |
| 61 | + id={`code-tab-${idx}`} |
| 62 | + onClick={() => setActive(idx)} |
| 63 | + style={active === idx ? activeTabStyle : tabStyle} |
| 64 | + > |
| 65 | + {ex.label} |
| 66 | + </button> |
| 67 | + ))} |
| 68 | + </div> |
| 69 | + |
| 70 | + <div role="tabpanel" id={`code-panel-${active}`} aria-labelledby={`code-tab-${active}`}> |
| 71 | + <CodeBlock language={snippets[active].language}> |
| 72 | +{snippets[active].code} |
| 73 | + </CodeBlock> |
| 74 | + </div> |
| 75 | + </div> |
| 76 | + ); |
| 77 | +} |
| 78 | + |
| 79 | +export default MultiLangCodeBlock; |
0 commit comments