<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>📝 Enhanced Markdown Editor</title>
<style>
body, html {
margin: 0; padding: 0;
height: 100%; width: 100%;
display: flex; flex-direction: column;
font-family: sans-serif;
}
#toolbar {
padding: 0.5em;
background: #f0f0f0;
border-bottom: 1px solid #ccc;
display: flex; /* Use flexbox for button layout */
align-items: center;
}
#toolbar button, #toolbar input[type="file"] {
margin-right: 0.5em; /* Space buttons out */
}
#editor {
flex: 1;
width: 100%;
box-sizing: border-box;
padding: 1em;
font-family: monospace;
font-size: 1rem;
line-height: 1.4;
border: none;
resize: none;
white-space: pre; /* Preserve whitespace for formatting */
overflow: auto; /* Add scrollbars if content overflows */
}
/* Optional: Basic table styling for potential preview (if added later) */
/* Or if you serve the .md directly and the browser renders it */
table { border-collapse: collapse; margin: 1em 0; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<div id="toolbar">
<input type="file" id="fileInput" accept=".md">
<button id="saveBtn" disabled>💾 Save & Download</button>
<button id="newTableBtn" disabled>➕ New Table</button>
<button id="formatTableBtn" disabled>📐 Format Selection</button>
</div>
<textarea id="editor" placeholder="Open a .md file to start editing…" disabled></textarea>
<script>
const fileInput = document.getElementById('fileInput');
const saveBtn = document.getElementById('saveBtn');
const editor = document.getElementById('editor');
const newTableBtn = document.getElementById('newTableBtn');
const formatTableBtn = document.getElementById('formatTableBtn');
let currentFileName = null;
// --- Helper to insert text at cursor position ---
function insertTextAtCursor(text) {
const start = editor.selectionStart;
const end = editor.selectionEnd;
const value = editor.value;
editor.value = value.substring(0, start) + text + value.substring(end);
editor.selectionStart = editor.selectionEnd = start + text.length;
editor.focus();
}
// --- 1) Load file into textarea ---
fileInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
currentFileName = file.name;
try {
const text = await file.text();
editor.value = text;
editor.disabled = false;
saveBtn.disabled = false;
newTableBtn.disabled = false;
formatTableBtn.disabled = false;
} catch (error) {
console.error("Error reading file:", error);
alert("Could not read file.");
}
});
// --- 2) Save & trigger download ---
saveBtn.addEventListener('click', () => {
const blob = new Blob([editor.value], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = currentFileName || 'untitled.md';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
// --- 3) Insert New Table ---
newTableBtn.addEventListener('click', () => {
const tableTemplate =
`
| Header 1 | Header 2 |
| -------- | -------- |
| Cell 1 | Cell 2 |
`; // Added newline before and after for better insertion
insertTextAtCursor(tableTemplate);
});
// --- 4) Format Selected Table-like Text ---
// This is a simple formatter. It works best on clearly defined table blocks.
formatTableBtn.addEventListener('click', () => {
const selectedText = editor.value.substring(editor.selectionStart, editor.selectionEnd);
if (!selectedText) {
alert("Please select the table text you want to format.");
return;
}
try {
const formattedText = formatMarkdownTable(selectedText);
// Replace the selected text with the formatted version
const start = editor.selectionStart;
const end = editor.selectionEnd;
const value = editor.value;
editor.value = value.substring(0, start) + formattedText + value.substring(end);
editor.selectionStart = start; // Keep selection at start
editor.selectionEnd = start + formattedText.length; // Select the formatted block
editor.focus();
} catch (error) {
console.error("Error formatting table:", error);
alert("Could not format selection. Is it a valid Markdown table?");
}
});
// --- Markdown Table Formatting Logic (Pure JS) ---
function formatMarkdownTable(markdownTableText) {
const lines = markdownTableText.trim().split('\n');
if (lines.length < 2) {
throw new Error("Not enough lines for a table.");
}
// Find the separator line (---|---|)
let separatorIndex = -1;
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes('---')) {
separatorIndex = i;
break;
}
}
if (separatorIndex === -1) {
throw new Error("Could not find separator line (---).");
}
// Parse lines and find max width for each column
const rows = lines.map(line => {
// Split by |, trim whitespace, handle empty first/last cells if line starts/ends with |
const cells = line.split('|').map(cell => cell.trim());
if (cells.length > 0 && cells[0] === '') cells.shift(); // Remove empty cell before first |
if (cells.length > 0 && cells[cells.length - 1] === '') cells.pop(); // Remove empty cell after last |
return cells;
});
const numColumns = rows[separatorIndex].length;
const colWidths = Array(numColumns).fill(0);
const alignments = Array(numColumns).fill('left'); // default left
rows.forEach(cells => {
if (cells.length !== numColumns) {
// This row doesn't match column count, might be noise or invalid table
// For simplicity, let's skip rows that don't match column count after parsing
// Or throw error for strict formatting: throw new Error("Inconsistent column counts.");
return; // Skip inconsistent rows for formatting
}
cells.forEach((cell, colIndex) => {
colWidths[colIndex] = Math.max(colWidths[colIndex], cell.length);
});
});
// Account for separator line width requirements and extract alignments
const separatorCells = rows[separatorIndex];
if (separatorCells.length !== numColumns) {
// This case should be caught above, but double check
throw new Error("Separator line column count mismatch.");
}
separatorCells.forEach((cell, colIndex) => {
// Minimum width for separator is 3 hyphens (---)
colWidths[colIndex] = Math.max(colWidths[colIndex], 3);
// Check alignment markers
const trimmedCell = cell.trim();
if (trimmedCell.startsWith(':') && trimmedCell.endsWith(':')) {
alignments[colIndex] = 'center';
} else if (trimmedCell.endsWith(':')) {
alignments[colIndex] = 'right';
} else {
alignments[colIndex] = 'left'; // Default or