Below is one way to implement your requirements with no external dependencies, using only HTML, CSS, and a Python backend built on the standard library. This solution stores all tables (in Markdown format) in a single file (“tables.md”) and lets you add new tables, add tasks (rows) with a “done” marker, and copy any table as Markdown. The user interface also features a “+ ADD” button for a new table. You can run this locally with Python.
Below are two files you’ll need:
1. index.html
Save this file in the same directory as the Python script. It contains the HTML/CSS/JavaScript code for your UI. (The JavaScript makes HTTP requests to your Python server endpoints.)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Markdown Task Tables</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 1000px;
margin: 20px auto;
padding: 10px;
}
h1 {
text-align: center;
}
.table-container {
margin-bottom: 30px;
border: 1px solid #ddd;
border-radius: 5px;
padding: 15px;
}
.table-title {
font-size: 1.2em;
margin-bottom: 10px;
font-weight: bold;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 15px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
.controls {
display: flex;
gap: 10px;
margin-top: 10px;
}
button {
padding: 8px 12px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.add-row {
background-color: #2196f3;
}
.add-row:hover {
background-color: #0b7dda;
}
.copy-md {
background-color: #ff9800;
}
.copy-md:hover {
background-color: #e68a00;
}
.add-table {
display: block;
margin: 20px auto;
padding: 10px 15px;
font-size: 1.1em;
}
.new-table-form {
margin: 20px 0;
padding: 15px;
border: 1px solid #ddd;
border-radius: 5px;
display: none;
}
input[type="text"] {
padding: 8px;
width: 100%;
margin-bottom: 10px;
box-sizing: border-box;
}
.checkbox {
width: 20px;
height: 20px;
}
</style>
</head>
<body>
<h1>Markdown Task Tables</h1>
<div id="tables-container"></div>
<button id="show-add-table" class="add-table">+ ADD NEW TABLE</button>
<div id="new-table-form" class="new-table-form">
<h2>Create New Table</h2>
<input type="text" id="table-title" placeholder="Table Title" />
<button id="create-table">Create Table</button>
</div>
<script>
// When the document is loaded, fetch tables from the backend.
document.addEventListener("DOMContentLoaded", function () {
loadTables();
document
.getElementById("show-add-table")
.addEventListener("click", () => {
document.getElementById("new-table-form").style.display = "block";
});
document
.getElementById("create-table")
.addEventListener("click", () => {
const title = document.getElementById("table-title").value.trim();
if (title) {
createNewTable(title);
}
});
});
function loadTables() {
fetch("/get_tables")
.then((response) => response.json())
.then((data) => {
renderTables(data.tables);
})
.catch((error) => console.error("Error loading tables:", error));
}
function renderTables(tables) {
const container = document.getElementById("tables-container");
container.innerHTML = "";
tables.forEach((table) => {
const tableContainer = document.createElement("div");
tableContainer.className = "table-container";
tableContainer.id = "table-" + table.id;
const titleDiv = document.createElement("div");
titleDiv.className = "table-title";
titleDiv.textContent = table.title;
tableContainer.appendChild(titleDiv);
// Create table element
const tableEl = document.createElement("table");
// Header
const thead = document.createElement("thead");
const headerRow = document.createElement("tr");
["Task", "Status"].forEach((h) => {
const th = document.createElement("th");
th.textContent = h;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
tableEl.appendChild(thead);
// Body
const tbody = document.createElement("tbody");
table.tasks.forEach((task) => {
tbody.appendChild(createTaskRow(task.name, task.done));
});
tableEl.appendChild(tbody);
tableContainer.appendChild(tableEl);
// Controls: add row, copy markdown, save table
const controls = document.createElement("div");
controls.className = "controls";
// + Add Task button
const addRowBtn = document.createElement("button");
addRowBtn.className = "add-row";
addRowBtn.textContent = "+ Add Task";
addRowBtn.addEventListener("click", () => {
tbody.appendChild(createTaskRow("", false));
});
controls.appendChild(addRowBtn);
// Copy Markdown button
const copyMdBtn = document.createElement("button");
copyMdBtn.className = "copy-md";
copyMdBtn.textContent = "Copy as Markdown";
copyMdBtn.addEventListener("click", () => {
copyTableAsMarkdown(table.id);
});
controls.appendChild(copyMdBtn);
// Save Changes button
const saveBtn = document.createElement("button");
saveBtn.textContent = "Save Changes";
saveBtn.addEventListener("click", () => {
saveTableChanges(table.id, tbody);
});
controls.appendChild(saveBtn);
tableContainer.appendChild(controls);
container.appendChild(tableContainer);
});
}
function createTaskRow(name, done) {
const row = document.createElement("tr");
const taskCell = document.createElement("td");
const taskInput = document.createElement("input");
taskInput.type = "text";
taskInput.value = name;
taskInput.className = "task-name";
taskCell.appendChild(taskInput);
const statusCell = document.createElement("td");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.className = "checkbox";
checkbox.checked = done;
statusCell.appendChild(checkbox);
row.appendChild(taskCell);
row.appendChild(statusCell);
return row;
}
function createNewTable(title) {
fetch("/create_table", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: title }),
})
.then((response) => response.json())
.then((data) => {
if (data.success) {
document.getElementById("table-title").value = "";
document.getElementById("new-table-form").style.display = "none";
loadTables();
}
})
.catch((error) => console.error("Error creating table:", error));
}
function saveTableChanges(tableId, tbody) {
const rows = tbody.querySelectorAll("tr");
const tasks = [];
rows.forEach((row) => {
const taskName = row.querySelector(".task-name").value.trim();
const done = row.querySelector(".checkbox").checked;
if (taskName) {
tasks.push({ name: taskName, done: done });
}
});
fetch("/update_table", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: tableId, tasks: tasks }),
})
.then((response) => response.json())
.then((data) => {
if (data.success) {
alert("Table saved successfully!");
loadTables();
}
})
.catch((error) => console.error("Error saving table:", error));
}
function copyTableAsMarkdown(tableId) {
fetch("/get_table_markdown/" + tableId)
.then((response) => response.text())
.then((md) => {
navigator.clipboard
.writeText(md)
.then(() => alert("Markdown copied to clipboard!"));
})
.catch((error) =>
console.error("Error copying markdown:", error)
);
}
</script>
</body>
</html>
2. server.py
This Python script uses only built‐in modules. It implements a basic HTTP server that serves the HTML page and provides these endpoints:
- GET /: Serves the
index.html file.
- GET /get_tables: Parses the Markdown file (
tables.md) and returns a JSON list of tables.
- POST /create_table: Creates a new table with the given title.
- POST /update_table: Updates a table’s tasks.
- GET /get_table_markdown/<table_id>: Returns just the Markdown version of one table.
The Markdown file is assumed to have a structure like this:
# Task Tables
## My Table Title id:some-unique-id
| Task | Status |
| ----------- | ------ |
| Example A | X |
| Example B | |
## Another Table id:another-unique-id
| Task | Status |
| ----------- | ------ |
| Task 1 | |
Save this file in the same folder as your index.html.
#!/usr/bin/env python3
import json
import os
import re
import uuid
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
# File to hold the markdown tables
DATA_FILE = "tables.md"
# Initialize the markdown file if it does not exist.
if not os.path.exists(DATA_FILE):
with open(DATA_FILE, "w", encoding="utf-8") as f:
f.write("# Task Tables\n\n")
def parse_markdown_tables():
"""
Look for sections that begin with a table heading in the form:
## Table Title id:TABLE_ID
Followed by a header (| Task | Status |), a divider line, then rows.
"""
tables = []
with open(DATA_FILE, "r", encoding="utf-8") as f:
content = f.read()
# Pattern matches a heading line starting with "## " then title and id,
# then skip an empty line, then header and divider, then rows.
pattern = re.compile(
r"##\s+(.*?)\s+id:(\S+)\s*\n\n\|.*\n\|(?:\s*-+\s*\|)+\n((?:\|.*\n)+)",
re.MULTILINE,
)
for match in pattern.finditer(content):
title, table_id, rows_str = match.groups()
tasks = []
for row in rows_str.strip().splitlines():
# Each row is expected to be like: | task name | status |
cols = [col.strip() for col in row.split("|")[1:-1]]
if len(cols) >= 2:
task_name = cols[0]
# Consider "X" (case-insensitive) as the marker for done
done = cols[1].strip().lower() in ("x", "done")
tasks.append({"name": task_name, "done": done})
tables.append({"id": table_id, "title": title, "tasks": tasks})
return tables
def save_tables_to_markdown(tables):
lines = ["# Task Tables", ""]
for table in tables:
# Write a heading with table title and id.
lines.append(f"## {table['title']} id:{table['id']}")
lines.append("")
lines.append("| Task | Status |")
lines.append("| ---- | ------ |")
for task in table["tasks"]:
status = "X" if task.get("done") else ""
lines.append(f"| {task.get('name', '')} | {status} |")
lines.append("") # Blank line between tables
with open(DATA_FILE, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
def get_table_markdown(table):
md_lines = [f"## {table['title']}", ""]
md_lines.append("| Task | Status |")
md_lines.append("| ---- | ------ |")
for task in table["tasks"]:
status = "X" if task.get("done") else ""
md_lines.append(f"| {task.get('name', '')} | {status} |")
md_lines.append("")
return "\n".join(md_lines)
class SimpleRequestHandler(BaseHTTPRequestHandler):
def _set_headers(self, content_type="text/html", status=200):
self.send_response(status)
self.send_header("Content-type", content_type)
self.end_headers()
def do_GET(self):
parsed_path = urlparse(self.path)
path = parsed_path.path
if path == "/":
# Serve index.html
try:
with open("index.html", "rb") as f:
self._set_headers("text/html")
self.wfile.write(f.read())
except IOError:
self.send_error(404, "File Not Found: index.html")
elif path == "/get_tables":
tables = parse_markdown_tables()
self._set_headers("application/json")
self.wfile.write(json.dumps({"tables": tables}).encode("utf-8"))
elif path.startswith("/get_table_markdown/"):
table_id = path.split("/")[-1]
tables = parse_markdown_tables()
for table in tables:
if table["id"] == table_id:
md = get_table_markdown(table)
self._set_headers("text/plain")
self.wfile.write(md.encode("utf-8"))
return
self.send_error(404, "Table not found")
else:
self.send_error(404, "Endpoint not found")
def do_POST(self):
parsed_path = urlparse(self.path)
path = parsed_path.path
content_length = int(self.headers.get("Content-Length", 0))
post_data = self.rfile.read(content_length) if content_length else b""
try:
data = json.loads(post_data.decode("utf-8"))
except Exception as e:
self.send_error(400, "Invalid JSON")
return
tables = parse_markdown_tables()
if path == "/create_table":
title = data.get("title", "Untitled Table")
new_id = str(uuid.uuid4())
new_table = {"id": new_id, "title": title, "tasks": []}
tables.append(new_table)
save_tables_to_markdown(tables)
self._set_headers("application/json")
self.wfile.write(json.dumps({"success": True, "id": new_id}).encode("utf-8"))
elif path == "/update_table":
table_id = data.get("id")
tasks = data.get("tasks", [])
found = False
for table in tables:
if table["id"] == table_id:
table["tasks"] = tasks
found = True
break
if found:
save_tables_to_markdown(tables)
self._set_headers("application/json")
self.wfile.write(json.dumps({"success": True}).encode("utf-8"))
else:
self.send_error(404, "Table not found")
else:
self.send_error(404, "Endpoint not found")
def log_message(self, format, *args):
# Override to suppress logging to stderr
return
def run(server_class=HTTPServer, handler_class=SimpleRequestHandler, port=8000):
print(f"Starting local server on http://localhost:{port}")
server_address = ("", port)
httpd = server_class(server_address, handler_class)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nShutting down the server.")
httpd.server_close()
if __name__ == "__main__":
run()
How to Run
- Place both files (
index.html and server.py) in the same folder.
- Run the Python server:
Open a terminal in that folder and execute:
python3 server.py
- Open your browser and navigate to http://localhost:8000.
You will then be able to:
- Click "+ ADD NEW TABLE" to show the creation form.
- Enter a table title and click "Create Table".
- Add rows to the table using "+ Add Task".
- Mark tasks as done (checkbox).
- Save changes with "Save Changes" (this updates the Markdown file).
- Use "Copy as Markdown" to copy the table’s Markdown output to the clipboard.
All changes are saved in the file tables.md in the same folder.
This self-contained solution uses only built-in Python modules and works well for local use. Enjoy building your task tables!