(props: { children: ReactElement })
| 64 | } |
| 65 | |
| 66 | export function TableWrapper(props: { children: ReactElement }) { |
| 67 | const ref = useRef<HTMLDivElement>(null) |
| 68 | const [isCopied, setIsCopied] = useState(false) |
| 69 | const [tableMarkdown, setTableMarkdown] = useState('') |
| 70 | const [isModalOpen, setIsModalOpen] = useState(false) |
| 71 | const [tableHtml, setTableHtml] = useState('') |
| 72 | const [tableTextMarkdown, setTableTextMarkdown] = useState('') |
| 73 | |
| 74 | useEffect(() => { |
| 75 | if (ref.current) { |
| 76 | const table = ref.current.querySelector('table') |
| 77 | if (table) { |
| 78 | const markdown = convertTableToMarkdown(table) |
| 79 | setTableMarkdown(markdown) |
| 80 | setTableHtml(table.outerHTML) |
| 81 | |
| 82 | const textMarkdown = convertTableToTextList(table) |
| 83 | setTableTextMarkdown(textMarkdown) |
| 84 | } |
| 85 | } |
| 86 | }, [props.children]) |
| 87 | |
| 88 | const convertTableToMarkdown = (table: HTMLTableElement): string => { |
| 89 | const rows: string[][] = [] |
| 90 | const thead = table.querySelector('thead') |
| 91 | const tbody = table.querySelector('tbody') |
| 92 | |
| 93 | if (thead) { |
| 94 | const headerRow = thead.querySelector('tr') |
| 95 | if (headerRow) { |
| 96 | const headers = Array.from(headerRow.querySelectorAll('th')).map( |
| 97 | (th) => th.textContent?.trim() || '' |
| 98 | ) |
| 99 | rows.push(headers) |
| 100 | rows.push(headers.map(() => '---')) |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | if (tbody) { |
| 105 | const bodyRows = tbody.querySelectorAll('tr') |
| 106 | bodyRows.forEach((tr) => { |
| 107 | const cells = Array.from(tr.querySelectorAll('td')).map( |
| 108 | (td) => td.textContent?.trim() || '' |
| 109 | ) |
| 110 | rows.push(cells) |
| 111 | }) |
| 112 | } |
| 113 | |
| 114 | return rows.map((row) => '| ' + row.join(' | ') + ' |').join('\n') |
| 115 | } |
| 116 | |
| 117 | const convertTableToTextList = (table: HTMLTableElement): string => { |
| 118 | const thead = table.querySelector('thead') |
| 119 | const tbody = table.querySelector('tbody') |
| 120 | |
| 121 | let headers: string[] = [] |
| 122 | if (thead) { |
| 123 | const headerRow = thead.querySelector('tr') |
nothing calls this directly
no test coverage detected