|
1 | | -import React, { useState } from 'react'; |
| 1 | +import React, { useState, useEffect } from 'react'; |
2 | 2 | import CodeBlock from '@theme/CodeBlock'; |
3 | 3 | import styles from './styles.module.css'; |
4 | 4 |
|
5 | 5 | import CollapseButton from '@site/src/components/CollapseButton'; |
6 | 6 |
|
| 7 | +import * as prettier from 'prettier/standalone'; |
| 8 | +import tsParser from 'prettier/plugins/typescript'; |
| 9 | +import estreeParser from 'prettier/plugins/estree'; |
| 10 | + |
| 11 | +const prettierOptions = { |
| 12 | + parser: 'typescript', |
| 13 | + plugins: [tsParser, estreeParser], |
| 14 | +}; |
| 15 | + |
7 | 16 | interface Props { |
8 | 17 | src: string; |
| 18 | + label: string; |
| 19 | + expandedLabel: string; |
9 | 20 | lineBounds: number[]; |
10 | 21 | } |
11 | 22 |
|
12 | | -export default function CollapsibleCode({ src, lineBounds }: Props) { |
| 23 | +export default function CollapsibleCode({ |
| 24 | + src, |
| 25 | + label, |
| 26 | + expandedLabel, |
| 27 | + lineBounds, |
| 28 | +}: Props) { |
13 | 29 | const [collapsed, setCollapsed] = useState(true); |
| 30 | + const [code, setCode] = useState<string>(src); |
| 31 | + |
| 32 | + useEffect(() => { |
| 33 | + async function formatCode() { |
| 34 | + const formattedCode = await prettier.format(src, prettierOptions); |
| 35 | + setCode(formattedCode); |
| 36 | + } |
| 37 | + void formatCode(); |
| 38 | + }, [src]); |
14 | 39 |
|
15 | 40 | if (!lineBounds) { |
16 | | - return <CodeBlock language="jsx">{src}</CodeBlock>; |
| 41 | + return <CodeBlock language="tsx">{code}</CodeBlock>; |
17 | 42 | } |
18 | 43 |
|
19 | 44 | const [start, end] = lineBounds; |
20 | 45 |
|
21 | | - const codeLines = src.split('\n'); |
| 46 | + const codeLines = code.split('\n'); |
22 | 47 | const linesToShow = codeLines.slice(start, end + 1).join('\n'); |
23 | 48 |
|
24 | 49 | return ( |
25 | 50 | <div className={styles.container}> |
26 | 51 | <CollapseButton |
27 | | - label="Collapse the full code" |
28 | | - labelCollapsed="Expand the full code" |
| 52 | + label={label} |
| 53 | + expandedLabel={expandedLabel} |
29 | 54 | collapsed={collapsed} |
30 | 55 | onCollapse={() => setCollapsed(!collapsed)} |
31 | 56 | className={styles.collapseButton} |
32 | 57 | /> |
33 | | - <CodeBlock language="jsx">{collapsed ? linesToShow : src}</CodeBlock> |
| 58 | + <CodeBlock language="tsx">{collapsed ? linesToShow : code}</CodeBlock> |
34 | 59 | </div> |
35 | 60 | ); |
36 | 61 | } |
0 commit comments