Add table-text-converter

This commit is contained in:
Jamie Kohns committed 2026-09-03 17:08:53 -04:00
1 parent 89a50e3e3d
commit b9867b4332
7 files changed
+533 -1

No files matched your search

+13
View File
@@ -245,6 +245,19 @@
"wordFrequencyAnalysis": "Word Frequency Analysis",
"wordFrequencyAnalysisDescription": "Count how often each word appears in the text"
},
"tableTextConverter": {
"title": "Table Text Converter",
"description": "Convert tabular text between Markdown, CSV, TSV, HTML, MySQL query output, and JSON formats.",
"shortDescription": "Convert tables between Markdown, CSV, HTML, MySQL, and JSON",
"longDescription": "This tool converts tabular text between multiple formats, including Markdown tables, CSV, TSV, HTML tables, MySQL/CLI query result output, and JSON arrays. Paste your table in any supported format, choose the output format (or let the tool auto-detect the input format), and get the converted table instantly. Useful for turning a MySQL query result into a Markdown table for documentation, converting an HTML table into CSV for spreadsheets, or transforming JSON data into a readable table.",
"inputTitle": "Input table",
"resultTitle": "Converted table",
"options": "Conversion Options",
"inputFormat": "Input format",
"outputFormat": "Output format",
"autoDetect": "Auto-detect",
"error": "Error"
},
"textCompare": {
"description": "Analyze two text blocks to highlight differences, including additions, deletions, and changes.",
"inputTitle": "Input Text",
+3 -1
View File
@@ -27,6 +27,7 @@ import { tool as stringCompare } from './text-compare/meta';
import { tool as stringUnicode } from './unicode/meta';
import { tool as stringEmailExtractor } from './email-extractor/meta';
import { tool as stringBcrypt } from './bcrypt/meta';
import { tool as stringTableTextConverter } from './table-text-converter/meta';
export const stringTools = [
stringSplit,
@@ -58,5 +59,6 @@ export const stringTools = [
stringEmailExtractor,
stringCompare,
stringSlugGenerator,
stringBcrypt
stringBcrypt,
stringTableTextConverter
];
@@ -0,0 +1,152 @@
import React, { useState } from 'react';
import { Box } from '@mui/material';
import ToolContent from '@components/ToolContent';
import ToolTextInput from '@components/input/ToolTextInput';
import ToolTextResult from '@components/result/ToolTextResult';
import SelectWithDesc from '@components/options/SelectWithDesc';
import { GetGroupsType } from '@components/options/ToolOptions';
import { CardExampleType } from '@components/examples/ToolExamples';
import { ToolComponentProps } from '@tools/defineTool';
import { useTranslation } from 'react-i18next';
import { convertTable } from './service';
import { InitialValuesType, TableFormat } from './types';
const initialValues: InitialValuesType = {
inputFormat: 'auto',
outputFormat: 'markdown'
};
const formatOptions: { label: string; value: TableFormat }[] = [
{ label: 'Markdown', value: 'markdown' },
{ label: 'CSV', value: 'csv' },
{ label: 'TSV', value: 'tsv' },
{ label: 'HTML', value: 'html' },
{ label: 'MySQL', value: 'mysql' },
{ label: 'JSON', value: 'json' }
];
const exampleCards: CardExampleType<InitialValuesType>[] = [
{
title: 'Markdown table to CSV',
description: 'Convert a markdown table into CSV format.',
sampleText: `| Name | Age | City |
| ----- | --- | -------- |
| John | 30 | New York |
| Alice | 25 | London |`,
sampleResult: `Name,Age,City
John,30,New York
Alice,25,London`,
sampleOptions: { inputFormat: 'markdown', outputFormat: 'csv' }
},
{
title: 'HTML table to Markdown',
description: 'Convert an HTML table into a markdown table.',
sampleText: `<table>
<tr><th>Product</th><th>Price</th></tr>
<tr><td>Apple</td><td>1.99</td></tr>
<tr><td>Banana</td><td>0.99</td></tr>
</table>`,
sampleResult: `| Product | Price |
| --- | --- |
| Apple | 1.99 |
| Banana | 0.99 |`,
sampleOptions: { inputFormat: 'html', outputFormat: 'markdown' }
},
{
title: 'MySQL output to Markdown',
description: 'Convert a MySQL query result to a markdown table.',
sampleText: `+----+-------+
| id | name |
+----+-------+
| 1 | John |
| 2 | Alice |
+----+-------+`,
sampleResult: `| id | name |
| --- | --- |
| 1 | John |
| 2 | Alice |`,
sampleOptions: { inputFormat: 'mysql', outputFormat: 'markdown' }
}
];
export default function TableTextConverter({
title,
longDescription
}: ToolComponentProps) {
const { t } = useTranslation('string');
const [input, setInput] = useState<string>('');
const [result, setResult] = useState<string>('');
const compute = (values: InitialValuesType, input: string) => {
if (!input) {
setResult('');
return;
}
try {
setResult(convertTable(input, values.inputFormat, values.outputFormat));
} catch (error) {
setResult(
`${t('tableTextConverter.error')}: ${
error instanceof Error ? error.message : String(error)
}`
);
}
};
const getGroups: GetGroupsType<InitialValuesType> = ({
values,
updateField
}) => [
{
title: t('tableTextConverter.options'),
component: (
<Box>
<SelectWithDesc
selected={values.inputFormat}
options={[
{ label: t('tableTextConverter.autoDetect'), value: 'auto' },
...formatOptions
]}
onChange={(value) => updateField('inputFormat', value)}
description={t('tableTextConverter.inputFormat')}
/>
<SelectWithDesc
selected={values.outputFormat}
options={formatOptions}
onChange={(value) => updateField('outputFormat', value)}
description={t('tableTextConverter.outputFormat')}
/>
</Box>
)
}
];
return (
<ToolContent
title={title}
input={input}
setInput={setInput}
initialValues={initialValues}
compute={compute}
exampleCards={exampleCards}
inputComponent={
<ToolTextInput
title={t('tableTextConverter.inputTitle')}
value={input}
onChange={setInput}
/>
}
resultComponent={
<ToolTextResult
title={t('tableTextConverter.resultTitle')}
value={result}
/>
}
getGroups={getGroups}
toolInfo={{
title: `What is a ${title}?`,
description: longDescription
}}
/>
);
}
@@ -0,0 +1,25 @@
import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const tool = defineTool('string', {
path: 'table-text-converter',
icon: 'material-symbols-light:table-convert',
keywords: [
'table',
'text',
'converter',
'markdown',
'csv',
'html',
'mysql',
'json'
],
component: lazy(() => import('./index')),
i18n: {
name: 'string:tableTextConverter.title',
description: 'string:tableTextConverter.description',
shortDescription: 'string:tableTextConverter.shortDescription',
longDescription: 'string:tableTextConverter.longDescription',
userTypes: ['generalUsers', 'developers']
}
});
@@ -0,0 +1,227 @@
import { splitCsv } from '@utils/csv';
import { TableFormat } from './types';
type TableRows = string[][];
function isSeparatorRow(cells: string[]): boolean {
return cells.every((cell) => /^:?-+:?$/.test(cell.trim()));
}
function parseDelimited(input: string, delimiter: string): TableRows {
return splitCsv(input, false, '', true, delimiter).filter(
(row) => row.length > 0
);
}
function parsePipeDelimited(input: string): TableRows {
const rows: TableRows = [];
for (const line of input.split('\n')) {
const trimmed = line.trim();
if (!trimmed || /^[+|][-+|]*[+|]$/.test(trimmed)) {
// skip empty lines and mysql/ascii border lines like +---+---+
continue;
}
const cells = trimmed
.replace(/^\|/, '')
.replace(/\|$/, '')
.split('|')
.map((cell) => cell.trim());
if (isSeparatorRow(cells)) {
// skip markdown header separator row, e.g. |---|---|
continue;
}
rows.push(cells);
}
return rows;
}
function parseHtml(input: string): TableRows {
const doc = new DOMParser().parseFromString(input, 'text/html');
const table = doc.querySelector('table');
if (!table) {
throw new Error('No <table> element found in the input');
}
const rows: TableRows = [];
table.querySelectorAll('tr').forEach((tr) => {
const cells = Array.from(tr.querySelectorAll('th,td')).map((cell) =>
(cell.textContent ?? '').trim()
);
if (cells.length > 0) {
rows.push(cells);
}
});
return rows;
}
function parseJson(input: string): TableRows {
const data = JSON.parse(input);
if (!Array.isArray(data)) {
throw new Error('JSON input must be an array of objects');
}
const headers: string[] = [];
data.forEach((item) => {
if (item && typeof item === 'object') {
Object.keys(item).forEach((key) => {
if (!headers.includes(key)) {
headers.push(key);
}
});
}
});
const body = data.map((item) =>
headers.map((header) => {
const value = item?.[header];
return value === undefined || value === null ? '' : String(value);
})
);
return [headers, ...body];
}
export function detectTableFormat(input: string): TableFormat {
const trimmed = input.trim();
if (/<table[\s>]/i.test(trimmed)) {
return 'html';
}
if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
return 'json';
}
const firstLine = trimmed.split('\n')[0]?.trim() ?? '';
if (/^\+[-+]+\+$/.test(firstLine)) {
return 'mysql';
}
if (firstLine.includes('|')) {
return 'markdown';
}
if (firstLine.includes('\t')) {
return 'tsv';
}
return 'csv';
}
export function parseTable(input: string, format: TableFormat): TableRows {
switch (format) {
case 'markdown':
case 'mysql':
return parsePipeDelimited(input);
case 'csv':
return parseDelimited(input, ',');
case 'tsv':
return parseDelimited(input, '\t');
case 'html':
return parseHtml(input);
case 'json':
return parseJson(input);
}
}
function escapeCsvField(field: string, delimiter: string): string {
if (
field.includes(delimiter) ||
field.includes('"') ||
field.includes('\n')
) {
return `"${field.replace(/"/g, '""')}"`;
}
return field;
}
function toDelimited(rows: TableRows, delimiter: string): string {
return rows
.map((row) =>
row.map((cell) => escapeCsvField(cell, delimiter)).join(delimiter)
)
.join('\n');
}
function toMarkdown(rows: TableRows): string {
if (rows.length === 0) return '';
const [header, ...body] = rows;
const headerLine = `| ${header.join(' | ')} |`;
const separatorLine = `| ${header.map(() => '---').join(' | ')} |`;
const bodyLines = body.map((row) => `| ${row.join(' | ')} |`);
return [headerLine, separatorLine, ...bodyLines].join('\n');
}
function toMysql(rows: TableRows): string {
if (rows.length === 0) return '';
const columnCount = rows[0].length;
const widths = Array.from({ length: columnCount }, (_, colIndex) =>
Math.max(...rows.map((row) => (row[colIndex] ?? '').length))
);
const border = `+${widths.map((width) => '-'.repeat(width + 2)).join('+')}+`;
const formatRow = (row: string[]) =>
`| ${row
.map((cell, colIndex) => (cell ?? '').padEnd(widths[colIndex]))
.join(' | ')} |`;
const [header, ...body] = rows;
return [
border,
formatRow(header),
border,
...body.map(formatRow),
border
].join('\n');
}
function toHtml(rows: TableRows): string {
if (rows.length === 0) return '';
const [header, ...body] = rows;
const headerRow = ` <tr>\n${header
.map((cell) => ` <th>${cell}</th>`)
.join('\n')}\n </tr>`;
const bodyRows = body
.map(
(row) =>
` <tr>\n${row
.map((cell) => ` <td>${cell}</td>`)
.join('\n')}\n </tr>`
)
.join('\n');
return `<table>\n <thead>\n${headerRow}\n </thead>\n <tbody>\n${bodyRows}\n </tbody>\n</table>`;
}
function toJson(rows: TableRows): string {
if (rows.length === 0) return '[]';
const [header, ...body] = rows;
const data = body.map((row) =>
Object.fromEntries(
header.map((key, colIndex) => [key, row[colIndex] ?? ''])
)
);
return JSON.stringify(data, null, 2);
}
export function formatTable(rows: TableRows, format: TableFormat): string {
switch (format) {
case 'markdown':
return toMarkdown(rows);
case 'csv':
return toDelimited(rows, ',');
case 'tsv':
return toDelimited(rows, '\t');
case 'html':
return toHtml(rows);
case 'mysql':
return toMysql(rows);
case 'json':
return toJson(rows);
}
}
export function convertTable(
input: string,
inputFormat: TableFormat | 'auto',
outputFormat: TableFormat
): string {
if (!input.trim()) {
return '';
}
const format =
inputFormat === 'auto' ? detectTableFormat(input) : inputFormat;
const rows = parseTable(input, format);
if (rows.length === 0) {
throw new Error('No table data could be parsed from the input');
}
return formatTable(rows, outputFormat);
}
@@ -0,0 +1,101 @@
import { describe, expect, it } from 'vitest';
import { convertTable, detectTableFormat } from './service';
describe('convertTable', () => {
it('converts a markdown table to CSV', () => {
const input = `| Name | Age |
| ----- | --- |
| John | 30 |
| Alice | 25 |`;
const result = convertTable(input, 'markdown', 'csv');
expect(result).toBe('Name,Age\nJohn,30\nAlice,25');
});
it('converts an HTML table to markdown', () => {
const input = `<table>
<tr><th>Product</th><th>Price</th></tr>
<tr><td>Apple</td><td>1.99</td></tr>
</table>`;
const result = convertTable(input, 'html', 'markdown');
expect(result).toBe('| Product | Price |\n| --- | --- |\n| Apple | 1.99 |');
});
it('converts a MySQL result table to markdown', () => {
const input = `+----+-------+
| id | name |
+----+-------+
| 1 | John |
| 2 | Alice |
+----+-------+`;
const result = convertTable(input, 'mysql', 'markdown');
expect(result).toBe(
'| id | name |\n| --- | --- |\n| 1 | John |\n| 2 | Alice |'
);
});
it('converts CSV to JSON', () => {
const input = 'name,age\nJohn,30\nAlice,25';
const result = convertTable(input, 'csv', 'json');
expect(JSON.parse(result)).toEqual([
{ name: 'John', age: '30' },
{ name: 'Alice', age: '25' }
]);
});
it('converts JSON to CSV', () => {
const input = JSON.stringify([
{ name: 'John', age: 30 },
{ name: 'Alice', age: 25 }
]);
const result = convertTable(input, 'json', 'csv');
expect(result).toBe('name,age\nJohn,30\nAlice,25');
});
it('converts markdown to a MySQL-style ASCII table', () => {
const input = `| a | bb |
| --- | --- |
| 1 | 2 |`;
const result = convertTable(input, 'markdown', 'mysql');
expect(result).toBe(
'+---+----+\n| a | bb |\n+---+----+\n| 1 | 2 |\n+---+----+'
);
});
it('returns an empty string for empty input', () => {
expect(convertTable('', 'auto', 'csv')).toBe('');
});
it('throws for html input without a table', () => {
expect(() => convertTable('<div>no table</div>', 'html', 'csv')).toThrow();
});
describe('detectTableFormat', () => {
it('detects markdown tables', () => {
expect(detectTableFormat('| a | b |\n| --- | --- |')).toBe('markdown');
});
it('detects mysql ascii tables', () => {
expect(detectTableFormat('+---+---+\n| a | b |\n+---+---+')).toBe(
'mysql'
);
});
it('detects html tables', () => {
expect(detectTableFormat('<table><tr><td>a</td></tr></table>')).toBe(
'html'
);
});
it('detects json arrays', () => {
expect(detectTableFormat('[{"a":1}]')).toBe('json');
});
it('detects tsv', () => {
expect(detectTableFormat('a\tb\n1\t2')).toBe('tsv');
});
it('falls back to csv', () => {
expect(detectTableFormat('a,b\n1,2')).toBe('csv');
});
});
});
@@ -0,0 +1,12 @@
export type TableFormat =
| 'markdown'
| 'csv'
| 'tsv'
| 'html'
| 'mysql'
| 'json';
export type InitialValuesType = {
inputFormat: TableFormat | 'auto';
outputFormat: TableFormat;
};