I can help you create a simple local site with HTML/CSS and Python backend that handles Markdown tables. Here's a straightforward implementation:
from http.server import HTTPServer, BaseHTTPRequestHandler
import os
import re
# Path to the markdown file
MD_FILE = "tasks.md"
# HTML template
HTML = """
<!DOCTYPE html>
<html>
<head>
<title>Task Manager</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
.done { background-color: #d4edda; }
.not-done { background-color: #f8d7da; }
button { padding: 8px 12px; margin: 5px; cursor: pointer; }
.table-container { margin-bottom: 30px; }
.add-form { margin-bottom: 15px; }
.add-form input { padding: 8px; margin-right: 5px; }
</style>
<script>
function copyTableAsMd(tableId) {
const table = document.getElementById(tableId);
const rows = table.querySelectorAll('tr');
let mdTable = '';
// Header row
const headerCells = rows[0].querySelectorAll('th');
mdTable += '| ' + Array.from(headerCells).map(cell => cell.textContent).join(' | ') + ' |\\n';
// Separator row
mdTable += '| ' + Array.from(headerCells).map(() => '---').join(' | ') + ' |\\n';
// Data rows
for (let i = 1; i < rows.length; i++) {
const cells = rows[i].querySelectorAll('td');
mdTable += '| ' + Array.from(cells).map(cell => cell.textContent).join(' | ') + ' |\\n';
}
navigator.clipboard.writeText(mdTable);
alert('Table copied as Markdown!');
}
function toggleTaskStatus(taskId) {
fetch('/toggle/' + taskId, { method: 'POST' })
.then(response => {
if (response.ok) window.location.reload();
});
}
function addTask(tableId, event) {
event.preventDefault();
const form = event.target;
const taskName = form.querySelector('input[name="task"]').value;
fetch('/add/' + tableId, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'task=' + encodeURIComponent(taskName)
}).then(response => {
if (response.ok) window.location.reload();
});
return false;
}
</script>
</head>
<body>
<h1>Task Manager</h1>
{tables}
</body>
</html>
"""
# Parse markdown tables from file
def parse_md_tables(md_content):
tables = []
table_blocks = re.split(r'\n\s*\n', md_content)
for i, block in enumerate(table_blocks):
if '|' in block:
lines = block.strip().split('\n')
if len(lines) >= 3: # Valid table needs header, separator, and at least one row
# Extract table title if it exists (assuming it's a heading before the table)
title = f"Table {i+1}"
if i > 0 and table_blocks[i-1].startswith('#'):
title = table_blocks[i-1].strip('# \n')
tables.append({
'id': f"table_{i}",
'title': title,
'content': block
})
return tables
# Convert markdown table to HTML
def md_table_to_html(table_id, table_content):
lines = table_content.strip().split('\n')
# Parse header
header = lines[0].strip('|').split('|')
header = [h.strip() for h in header]
# Skip separator line
# Parse rows
rows = []
for i in range(2, len(lines)):
row = lines[i].strip('|').split('|')
rows.append([cell.strip() for cell in row])
# Generate HTML
html = f'<div class="table-container">\n'
html += f'<h2>{table_id}</h2>\n'
html += f'<form class="add-form" onsubmit="return addTask(\'{table_id}\', event)">\n'
html += f'<input type="text" name="task" placeholder="New task" required>\n'
html += f'<button type="submit">Add Task</button>\n'
html += f'</form>\n'
html += f'<table id="{table_id}">\n'
# Header row
html += '<tr>\n'
for h in header:
html += f'<th>{h}</th>\n'
html += '</tr>\n'
# Data rows
for i, row in enumerate(rows):
status_class = 'done' if 'done' in row[1].lower() else 'not-done'
html += f'<tr class="{status_class}">\n'
for j, cell in enumerate(row):
if j == 1: # Status column
html += f'<td><a href="#" onclick="toggleTaskStatus(\'{table_id}_{i}\'); return false;">{cell}</a></td>\n'
else:
html += f'<td>{cell}</td>\n'
html += '</tr>\n'
html += '</table>\n'
html += f'<button onclick="copyTableAsMd(\'{table_id}\')">Copy as Markdown</button>\n'
html += '</div>\n'
return html
# Update task status in markdown file
def toggle_task_status(table_id, task_id):
if not os.path.exists(MD_FILE):
return False
with open(MD_FILE, 'r') as f:
content = f.read()
tables = parse_md_tables(content)
table_index = int(table_id.split('_')[1])
task_index = int(task_id.split('_')[2])
if table_index < len(tables):
table_content = tables[table_index]['content']
lines = table_content.strip().split('\n')
if task_index + 2 < len(lines): # +2 to account for header and separator
row = lines[task_index + 2]
cells = row.strip('|').split('|')
if len(cells) > 1:
status = cells[1].strip()
new_status = "Not Done" if "done" in status.lower() else "Done"
cells[1] = " " + new_status + " "
lines[task_index + 2] = "|" + "|".join(cells) + "|"
tables[table_index]['content'] = "\n".join(lines)
# Reconstruct the full markdown content
new_content = ""
current_table = 0
for i, block in enumerate(re.split(r'\n\s*\n', content)):
if '|' in block and len(block.strip().split('\n')) >= 3:
new_content += tables[current_table]['content'] + "\n\n"
current_table += 1
else:
new_content += block + "\n\n"
with open(MD_FILE, 'w') as f:
f.write(new_content.strip())
return True
return False
# Add new task to a table
def add_task(table_id, task_name):
if not os.path.exists(MD_FILE):
return False
with open(MD_FILE, 'r') as f:
content = f.read()
tables = parse_md_tables(content)
table_index = int(table_id.split('_')[1])
if table_index < len(tables):
table_content = tables[table_index]['content']
lines = table_content.strip().split('\n')
# Create new row
new_row = f"| {task_name} | Not Done |"
lines.append(new_row)
tables[table_index]['content'] = "\n".join(lines)
# Reconstruct the full markdown content
new_content = ""
current_table = 0
for i, block in enumerate(re.split(r'\n\s*\n', content)):
if '|' in block and len(block.strip().split('\n')) >= 3:
new_content += tables[current_table]['content'] + "\n\n"
current_table += 1
else:
new_content += block + "\n\n"
with open(MD_FILE, 'w') as f:
f.write(new_content.strip())
return True
return False
# Create a sample markdown file if it doesn't exist
def create_sample_md():
if not os.path.exists(MD_FILE):
with open(MD_FILE, 'w') as f:
f.write("""# Work Tasks
| Task | Status | Priority |
| --- | --- | --- |
| Finish report | Not Done | High |
| Call client | Done | Medium |
| Update website | Not Done | Low |
# Personal Tasks
| Task | Status |
| --- | --- |
| Buy groceries | Done |
| Pay bills | Not Done |
""")
# HTTP request handler
class TaskHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# Read markdown file
if os.path.exists(MD_FILE):
with open(MD_FILE, 'r') as f:
md_content = f.read()
else:
create_sample_md()
with open(MD_FILE, 'r') as f:
md_content = f.read()
# Parse tables
tables = parse_md_tables(md_content)
# Generate HTML for each table
tables_html = ""
for table in tables:
tables_html += md_table_to_html(table['id'], table['content'])
# Send response
self.wfile.write(HTML.format(tables=tables_html).encode())
else:
self.send_response(404)
self.end_headers()
def do_POST(self):
if self.path.startswith('/toggle/'):
task_id = self.path[8:]
table_id, _ = task_id.rsplit('_', 1)
if toggle_task_status(table_id, task_id):
self.send_response(200)
else:
self.send_response(400)
self.end_headers()
elif self.path.startswith('/add/'):
table_id = self.path[5:]
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf-8')
import urllib.parse
params = urllib.parse.parse_qs(post_data)
task_name = params.get('task', [''])[0]
if task_name and add_task(table_id, task_name):
self.send_response(200)
else:
self.send_response(400)
self.end_headers()
else:
self.send_response(404)
self.end_headers()
# Main function
def main():
# Create sample markdown file if it doesn't exist
create_sample_md()
# Start HTTP server
server_address = ('', 8000)
httpd = HTTPServer(server_address, TaskHandler)
print('Server running at http://localhost:8000/')
httpd.serve_forever()
if __name__ == '__main__':
main()
Would you like me to explain or break down this code?