diff --git a/public/locales/en/string.json b/public/locales/en/string.json index 77a0cfd8..9218f342 100644 --- a/public/locales/en/string.json +++ b/public/locales/en/string.json @@ -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", diff --git a/src/pages/tools/string/index.ts b/src/pages/tools/string/index.ts index 87fe2416..14ffb69b 100644 --- a/src/pages/tools/string/index.ts +++ b/src/pages/tools/string/index.ts @@ -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 ]; diff --git a/src/pages/tools/string/table-text-converter/index.tsx b/src/pages/tools/string/table-text-converter/index.tsx new file mode 100644 index 00000000..79a44799 --- /dev/null +++ b/src/pages/tools/string/table-text-converter/index.tsx @@ -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[] = [ + { + 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: ` + + + +
ProductPrice
Apple1.99
Banana0.99
`, + 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(''); + const [result, setResult] = useState(''); + + 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 = ({ + values, + updateField + }) => [ + { + title: t('tableTextConverter.options'), + component: ( + + updateField('inputFormat', value)} + description={t('tableTextConverter.inputFormat')} + /> + updateField('outputFormat', value)} + description={t('tableTextConverter.outputFormat')} + /> + + ) + } + ]; + + return ( + + } + resultComponent={ + + } + getGroups={getGroups} + toolInfo={{ + title: `What is a ${title}?`, + description: longDescription + }} + /> + ); +} diff --git a/src/pages/tools/string/table-text-converter/meta.ts b/src/pages/tools/string/table-text-converter/meta.ts new file mode 100644 index 00000000..16eccef3 --- /dev/null +++ b/src/pages/tools/string/table-text-converter/meta.ts @@ -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'] + } +}); diff --git a/src/pages/tools/string/table-text-converter/service.ts b/src/pages/tools/string/table-text-converter/service.ts new file mode 100644 index 00000000..bd57bfca --- /dev/null +++ b/src/pages/tools/string/table-text-converter/service.ts @@ -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 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 (/]/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 = ` \n${header + .map((cell) => ` `) + .join('\n')}\n `; + const bodyRows = body + .map( + (row) => + ` \n${row + .map((cell) => ` `) + .join('\n')}\n ` + ) + .join('\n'); + return `
${cell}
${cell}
\n \n${headerRow}\n \n \n${bodyRows}\n \n
`; +} + +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); +} diff --git a/src/pages/tools/string/table-text-converter/table-text-converter.service.test.ts b/src/pages/tools/string/table-text-converter/table-text-converter.service.test.ts new file mode 100644 index 00000000..388f2c04 --- /dev/null +++ b/src/pages/tools/string/table-text-converter/table-text-converter.service.test.ts @@ -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 = ` + + +
ProductPrice
Apple1.99
`; + 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('
no table
', '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('
a
')).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'); + }); + }); +}); diff --git a/src/pages/tools/string/table-text-converter/types.ts b/src/pages/tools/string/table-text-converter/types.ts new file mode 100644 index 00000000..0944a434 --- /dev/null +++ b/src/pages/tools/string/table-text-converter/types.ts @@ -0,0 +1,12 @@ +export type TableFormat = + | 'markdown' + | 'csv' + | 'tsv' + | 'html' + | 'mysql' + | 'json'; + +export type InitialValuesType = { + inputFormat: TableFormat | 'auto'; + outputFormat: TableFormat; +};